diff --git a/dist/cleanup.js b/dist/cleanup.js index 58ae8e5db..e4ed83793 100644 --- a/dist/cleanup.js +++ b/dist/cleanup.js @@ -34,287 +34,6 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// node_modules/@actions/core/lib/utils.js -var require_utils = __commonJS({ - "node_modules/@actions/core/lib/utils.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.toCommandValue = toCommandValue; - exports2.toCommandProperties = toCommandProperties; - function toCommandValue(input) { - if (input === null || input === void 0) { - return ""; - } else if (typeof input === "string" || input instanceof String) { - return input; - } - return JSON.stringify(input); - } - function toCommandProperties(annotationProperties) { - if (!Object.keys(annotationProperties).length) { - return {}; - } - return { - title: annotationProperties.title, - file: annotationProperties.file, - line: annotationProperties.startLine, - endLine: annotationProperties.endLine, - col: annotationProperties.startColumn, - endColumn: annotationProperties.endColumn - }; - } - } -}); - -// node_modules/@actions/core/lib/command.js -var require_command = __commonJS({ - "node_modules/@actions/core/lib/command.js"(exports2) { - "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - 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 ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - } - __setModuleDefault(result, mod); - return result; - }; - })(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.issueCommand = issueCommand; - exports2.issue = issue; - var os = __importStar(require("os")); - var utils_1 = require_utils(); - function issueCommand(command, properties, message) { - const cmd = new Command(command, properties, message); - process.stdout.write(cmd.toString() + os.EOL); - } - function issue(name, message = "") { - issueCommand(name, {}, message); - } - var CMD_STRING = "::"; - var Command = class { - constructor(command, properties, message) { - if (!command) { - command = "missing.command"; - } - this.command = command; - this.properties = properties; - this.message = message; - } - toString() { - let cmdStr = CMD_STRING + this.command; - if (this.properties && Object.keys(this.properties).length > 0) { - cmdStr += " "; - let first = true; - for (const key in this.properties) { - if (this.properties.hasOwnProperty(key)) { - const val = this.properties[key]; - if (val) { - if (first) { - first = false; - } else { - cmdStr += ","; - } - cmdStr += `${key}=${escapeProperty(val)}`; - } - } - } - } - cmdStr += `${CMD_STRING}${escapeData(this.message)}`; - return cmdStr; - } - }; - function escapeData(s) { - return (0, utils_1.toCommandValue)(s).replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A"); - } - function escapeProperty(s) { - return (0, utils_1.toCommandValue)(s).replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A").replace(/:/g, "%3A").replace(/,/g, "%2C"); - } - } -}); - -// node_modules/@actions/core/lib/file-command.js -var require_file_command = __commonJS({ - "node_modules/@actions/core/lib/file-command.js"(exports2) { - "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - 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 ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - } - __setModuleDefault(result, mod); - return result; - }; - })(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.issueFileCommand = issueFileCommand; - exports2.prepareKeyValueMessage = prepareKeyValueMessage; - var crypto = __importStar(require("crypto")); - var fs = __importStar(require("fs")); - var os = __importStar(require("os")); - var utils_1 = require_utils(); - function issueFileCommand(command, message) { - const filePath = process.env[`GITHUB_${command}`]; - if (!filePath) { - throw new Error(`Unable to find environment variable for file command ${command}`); - } - if (!fs.existsSync(filePath)) { - throw new Error(`Missing file at path: ${filePath}`); - } - fs.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os.EOL}`, { - encoding: "utf8" - }); - } - function prepareKeyValueMessage(key, value) { - const delimiter = `ghadelimiter_${crypto.randomUUID()}`; - const convertedValue = (0, utils_1.toCommandValue)(value); - if (key.includes(delimiter)) { - throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); - } - if (convertedValue.includes(delimiter)) { - throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); - } - return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`; - } - } -}); - -// node_modules/@actions/core/node_modules/@actions/http-client/lib/proxy.js -var require_proxy = __commonJS({ - "node_modules/@actions/core/node_modules/@actions/http-client/lib/proxy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getProxyUrl = getProxyUrl; - exports2.checkBypass = checkBypass; - function getProxyUrl(reqUrl) { - const usingSsl = reqUrl.protocol === "https:"; - if (checkBypass(reqUrl)) { - return void 0; - } - const proxyVar = (() => { - if (usingSsl) { - return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; - } else { - return process.env["http_proxy"] || process.env["HTTP_PROXY"]; - } - })(); - if (proxyVar) { - try { - return new DecodedURL(proxyVar); - } catch (_a) { - if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) - return new DecodedURL(`http://${proxyVar}`); - } - } else { - return void 0; - } - } - function checkBypass(reqUrl) { - if (!reqUrl.hostname) { - return false; - } - const reqHost = reqUrl.hostname; - if (isLoopbackAddress(reqHost)) { - return true; - } - const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; - if (!noProxy) { - return false; - } - let reqPort; - if (reqUrl.port) { - reqPort = Number(reqUrl.port); - } else if (reqUrl.protocol === "http:") { - reqPort = 80; - } else if (reqUrl.protocol === "https:") { - reqPort = 443; - } - const upperReqHosts = [reqUrl.hostname.toUpperCase()]; - if (typeof reqPort === "number") { - upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); - } - for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { - if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { - return true; - } - } - return false; - } - function isLoopbackAddress(host) { - const hostLower = host.toLowerCase(); - return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); - } - var DecodedURL = class extends URL { - constructor(url, base) { - super(url, base); - this._decodedUsername = decodeURIComponent(super.username); - this._decodedPassword = decodeURIComponent(super.password); - } - get username() { - return this._decodedUsername; - } - get password() { - return this._decodedPassword; - } - }; - } -}); - // node_modules/tunnel/lib/tunnel.js var require_tunnel = __commonJS({ "node_modules/tunnel/lib/tunnel.js"(exports2) { @@ -326,28 +45,28 @@ var require_tunnel = __commonJS({ var events = require("events"); var assert = require("assert"); var util = require("util"); - exports2.httpOverHttp = httpOverHttp; - exports2.httpsOverHttp = httpsOverHttp; - exports2.httpOverHttps = httpOverHttps; - exports2.httpsOverHttps = httpsOverHttps; - function httpOverHttp(options) { + exports2.httpOverHttp = httpOverHttp2; + exports2.httpsOverHttp = httpsOverHttp2; + exports2.httpOverHttps = httpOverHttps2; + exports2.httpsOverHttps = httpsOverHttps2; + function httpOverHttp2(options) { var agent = new TunnelingAgent(options); agent.request = http.request; return agent; } - function httpsOverHttp(options) { + function httpsOverHttp2(options) { var agent = new TunnelingAgent(options); agent.request = http.request; agent.createSocket = createSecureSocket; agent.defaultPort = 443; return agent; } - function httpOverHttps(options) { + function httpOverHttps2(options) { var agent = new TunnelingAgent(options); agent.request = https.request; return agent; } - function httpsOverHttps(options) { + function httpsOverHttps2(options) { var agent = new TunnelingAgent(options); agent.request = https.request; agent.createSocket = createSecureSocket; @@ -418,7 +137,7 @@ var require_tunnel = __commonJS({ connectOptions.headers = connectOptions.headers || {}; connectOptions.headers["Proxy-Authorization"] = "Basic " + new Buffer(connectOptions.proxyAuth).toString("base64"); } - debug("making CONNECT request"); + debug2("making CONNECT request"); var connectReq = self2.request(connectOptions); connectReq.useChunkedEncodingByDefault = false; connectReq.once("response", onResponse); @@ -438,7 +157,7 @@ var require_tunnel = __commonJS({ connectReq.removeAllListeners(); socket.removeAllListeners(); if (res.statusCode !== 200) { - debug( + debug2( "tunneling socket could not be established, statusCode=%d", res.statusCode ); @@ -450,7 +169,7 @@ var require_tunnel = __commonJS({ return; } if (head.length > 0) { - debug("got illegal response body from proxy"); + debug2("got illegal response body from proxy"); socket.destroy(); var error2 = new Error("got illegal response body from proxy"); error2.code = "ECONNRESET"; @@ -458,13 +177,13 @@ var require_tunnel = __commonJS({ self2.removeSocket(placeholder); return; } - debug("tunneling connection has established"); + debug2("tunneling connection has established"); self2.sockets[self2.sockets.indexOf(placeholder)] = socket; return cb(socket); } function onError(cause) { connectReq.removeAllListeners(); - debug( + debug2( "tunneling socket could not be established, cause=%s\n", cause.message, cause.stack @@ -526,9 +245,9 @@ var require_tunnel = __commonJS({ } return target; } - var debug; + var debug2; if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { - debug = function() { + debug2 = function() { var args = Array.prototype.slice.call(arguments); if (typeof args[0] === "string") { args[0] = "TUNNEL: " + args[0]; @@ -538,10 +257,10 @@ var require_tunnel = __commonJS({ console.error.apply(console, args); }; } else { - debug = function() { + debug2 = function() { }; } - exports2.debug = debug; + exports2.debug = debug2; } }); @@ -2905,7 +2624,7 @@ var require_connect = __commonJS({ }); // node_modules/undici/lib/llhttp/utils.js -var require_utils2 = __commonJS({ +var require_utils = __commonJS({ "node_modules/undici/lib/llhttp/utils.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); @@ -2930,7 +2649,7 @@ var require_constants2 = __commonJS({ "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.SPECIAL_HEADERS = exports2.HEADER_STATE = exports2.MINOR = exports2.MAJOR = exports2.CONNECTION_TOKEN_CHARS = exports2.HEADER_CHARS = exports2.TOKEN = exports2.STRICT_TOKEN = exports2.HEX = exports2.URL_CHAR = exports2.STRICT_URL_CHAR = exports2.USERINFO_CHARS = exports2.MARK = exports2.ALPHANUM = exports2.NUM = exports2.HEX_MAP = exports2.NUM_MAP = exports2.ALPHA = exports2.FINISH = exports2.H_METHOD_MAP = exports2.METHOD_MAP = exports2.METHODS_RTSP = exports2.METHODS_ICE = exports2.METHODS_HTTP = exports2.METHODS = exports2.LENIENT_FLAGS = exports2.FLAGS = exports2.TYPE = exports2.ERROR = void 0; - var utils_1 = require_utils2(); + var utils_1 = require_utils(); var ERROR; (function(ERROR2) { ERROR2[ERROR2["OK"] = 0] = "OK"; @@ -6001,7 +5720,7 @@ var require_client_h1 = __commonJS({ kResume, kHTTPContext } = require_symbols(); - var constants = require_constants2(); + var constants3 = require_constants2(); var EMPTY_BUF = Buffer.alloc(0); var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; @@ -6076,7 +5795,7 @@ var require_client_h1 = __commonJS({ constructor(client, socket, { exports: exports3 }) { assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0); this.llhttp = exports3; - this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE); + this.ptr = this.llhttp.llhttp_alloc(constants3.TYPE.RESPONSE); this.client = client; this.socket = socket; this.timeout = null; @@ -6171,11 +5890,11 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants.ERROR.OK) { + if (ret !== constants3.ERROR.OK) { const body = data.subarray(offset); - if (ret === constants.ERROR.PAUSED_UPGRADE) { + if (ret === constants3.ERROR.PAUSED_UPGRADE) { this.onUpgrade(body); - } else if (ret === constants.ERROR.PAUSED) { + } else if (ret === constants3.ERROR.PAUSED) { this.paused = true; socket.unshift(body); } else { @@ -6198,10 +5917,10 @@ var require_client_h1 = __commonJS({ } finally { currentParser = null; } - if (ret === constants.ERROR.OK) { + if (ret === constants3.ERROR.OK) { return null; } - if (ret === constants.ERROR.PAUSED || ret === constants.ERROR.PAUSED_UPGRADE) { + if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { this.paused = true; return null; } @@ -6218,7 +5937,7 @@ var require_client_h1 = __commonJS({ const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } - return new HTTPParserError(message, constants.ERROR[ret], data); + return new HTTPParserError(message, constants3.ERROR[ret], data); } destroy() { assert(this.ptr != null); @@ -6397,7 +6116,7 @@ var require_client_h1 = __commonJS({ socket[kBlocking] = false; client[kResume](); } - return pause ? constants.ERROR.PAUSED : 0; + return pause ? constants3.ERROR.PAUSED : 0; } onBody(buf) { const { client, socket, statusCode, maxResponseSize } = this; @@ -6419,7 +6138,7 @@ var require_client_h1 = __commonJS({ } this.bytesRead += buf.length; if (request.onData(buf) === false) { - return constants.ERROR.PAUSED; + return constants3.ERROR.PAUSED; } } onMessageComplete() { @@ -6455,13 +6174,13 @@ var require_client_h1 = __commonJS({ if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); - return constants.ERROR.PAUSED; + return constants3.ERROR.PAUSED; } else if (!shouldKeepAlive) { util.destroy(socket, new InformationalError("reset")); - return constants.ERROR.PAUSED; + return constants3.ERROR.PAUSED; } else if (socket[kReset] && client[kRunning] === 0) { util.destroy(socket, new InformationalError("reset")); - return constants.ERROR.PAUSED; + return constants3.ERROR.PAUSED; } else if (client[kPipelining] == null || client[kPipelining] === 1) { setImmediate(() => client[kResume]()); } else { @@ -8949,7 +8668,7 @@ var require_proxy_agent = __commonJS({ return this.#client.destroy(err); } }; - var ProxyAgent = class extends DispatcherBase { + var ProxyAgent2 = class extends DispatcherBase { constructor(opts) { super(); if (!opts || typeof opts === "object" && !(opts instanceof URL2) && !opts.uri) { @@ -9090,7 +8809,7 @@ var require_proxy_agent = __commonJS({ throw new InvalidArgumentError("Proxy-Authorization should be sent in ProxyAgent constructor"); } } - module2.exports = ProxyAgent; + module2.exports = ProxyAgent2; } }); @@ -9100,7 +8819,7 @@ var require_env_http_proxy_agent = __commonJS({ "use strict"; var DispatcherBase = require_dispatcher_base(); var { kClose, kDestroy, kClosed, kDestroyed, kDispatch, kNoProxyAgent, kHttpProxyAgent, kHttpsProxyAgent } = require_symbols(); - var ProxyAgent = require_proxy_agent(); + var ProxyAgent2 = require_proxy_agent(); var Agent = require_agent(); var DEFAULT_PORTS = { "http:": 80, @@ -9124,13 +8843,13 @@ var require_env_http_proxy_agent = __commonJS({ this[kNoProxyAgent] = new Agent(agentOpts); const HTTP_PROXY = httpProxy ?? process.env.http_proxy ?? process.env.HTTP_PROXY; if (HTTP_PROXY) { - this[kHttpProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTP_PROXY }); + this[kHttpProxyAgent] = new ProxyAgent2({ ...agentOpts, uri: HTTP_PROXY }); } else { this[kHttpProxyAgent] = this[kNoProxyAgent]; } const HTTPS_PROXY = httpsProxy ?? process.env.https_proxy ?? process.env.HTTPS_PROXY; if (HTTPS_PROXY) { - this[kHttpsProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTPS_PROXY }); + this[kHttpsProxyAgent] = new ProxyAgent2({ ...agentOpts, uri: HTTPS_PROXY }); } else { this[kHttpsProxyAgent] = this[kHttpProxyAgent]; } @@ -12185,12 +11904,12 @@ var require_headers = __commonJS({ append(name, value, isLowerCase) { this[kHeadersSortedMap] = null; const lowercaseName = isLowerCase ? name : name.toLowerCase(); - const exists = this[kHeadersMap].get(lowercaseName); - if (exists) { + const exists2 = this[kHeadersMap].get(lowercaseName); + if (exists2) { const delimiter = lowercaseName === "cookie" ? "; " : ", "; this[kHeadersMap].set(lowercaseName, { - name: exists.name, - value: `${exists.value}${delimiter}${value}` + name: exists2.name, + value: `${exists2.value}${delimiter}${value}` }); } else { this[kHeadersMap].set(lowercaseName, { name, value }); @@ -12315,7 +12034,7 @@ var require_headers = __commonJS({ } } }; - var Headers = class _Headers { + var Headers2 = class _Headers { #guard; #headersList; constructor(init = void 0) { @@ -12465,13 +12184,13 @@ var require_headers = __commonJS({ o.#headersList = list; } }; - var { getHeadersGuard, setHeadersGuard, getHeadersList, setHeadersList } = Headers; - Reflect.deleteProperty(Headers, "getHeadersGuard"); - Reflect.deleteProperty(Headers, "setHeadersGuard"); - Reflect.deleteProperty(Headers, "getHeadersList"); - Reflect.deleteProperty(Headers, "setHeadersList"); - iteratorMixin("Headers", Headers, kHeadersSortedMap, 0, 1); - Object.defineProperties(Headers.prototype, { + var { getHeadersGuard, setHeadersGuard, getHeadersList, setHeadersList } = Headers2; + Reflect.deleteProperty(Headers2, "getHeadersGuard"); + Reflect.deleteProperty(Headers2, "setHeadersGuard"); + Reflect.deleteProperty(Headers2, "getHeadersList"); + Reflect.deleteProperty(Headers2, "setHeadersList"); + iteratorMixin("Headers", Headers2, kHeadersSortedMap, 0, 1); + Object.defineProperties(Headers2.prototype, { append: kEnumerableProperty, delete: kEnumerableProperty, get: kEnumerableProperty, @@ -12489,7 +12208,7 @@ var require_headers = __commonJS({ webidl.converters.HeadersInit = function(V, prefix, argument) { if (webidl.util.Type(V) === "Object") { const iterator = Reflect.get(V, Symbol.iterator); - if (!util.types.isProxy(V) && iterator === Headers.prototype.entries) { + if (!util.types.isProxy(V) && iterator === Headers2.prototype.entries) { try { return getHeadersList(V).entriesList; } catch { @@ -12510,7 +12229,7 @@ var require_headers = __commonJS({ fill, // for test. compareHeaderName, - Headers, + Headers: Headers2, HeadersList, getHeadersGuard, setHeadersGuard, @@ -12524,7 +12243,7 @@ var require_headers = __commonJS({ var require_response = __commonJS({ "node_modules/undici/lib/web/fetch/response.js"(exports2, module2) { "use strict"; - var { Headers, HeadersList, fill, getHeadersGuard, setHeadersGuard, setHeadersList } = require_headers(); + var { Headers: Headers2, HeadersList, fill, getHeadersGuard, setHeadersGuard, setHeadersList } = require_headers(); var { extractBody, cloneBody, mixinBody, hasFinalizationRegistry, streamRegistry, bodyUnusable } = require_body(); var util = require_util(); var nodeUtil = require("node:util"); @@ -12602,7 +12321,7 @@ var require_response = __commonJS({ } init = webidl.converters.ResponseInit(init); this[kState] = makeResponse({}); - this[kHeaders] = new Headers(kConstruct); + this[kHeaders] = new Headers2(kConstruct); setHeadersGuard(this[kHeaders], "response"); setHeadersList(this[kHeaders], this[kState].headersList); let bodyWithType = null; @@ -12846,7 +12565,7 @@ var require_response = __commonJS({ function fromInnerResponse(innerResponse, guard) { const response = new Response(kConstruct); response[kState] = innerResponse; - response[kHeaders] = new Headers(kConstruct); + response[kHeaders] = new Headers2(kConstruct); setHeadersList(response[kHeaders], innerResponse.headersList); setHeadersGuard(response[kHeaders], guard); if (hasFinalizationRegistry && innerResponse.body?.stream) { @@ -12966,7 +12685,7 @@ var require_request2 = __commonJS({ "node_modules/undici/lib/web/fetch/request.js"(exports2, module2) { "use strict"; var { extractBody, mixinBody, cloneBody, bodyUnusable } = require_body(); - var { Headers, fill: fillHeaders, HeadersList, setHeadersGuard, getHeadersGuard, setHeadersList, getHeadersList } = require_headers(); + var { Headers: Headers2, fill: fillHeaders, HeadersList, setHeadersGuard, getHeadersGuard, setHeadersList, getHeadersList } = require_headers(); var { FinalizationRegistry: FinalizationRegistry2 } = require_dispatcher_weakref()(); var util = require_util(); var nodeUtil = require("node:util"); @@ -13234,7 +12953,7 @@ var require_request2 = __commonJS({ requestFinalizer.register(ac, { signal, abort }, abort); } } - this[kHeaders] = new Headers(kConstruct); + this[kHeaders] = new Headers2(kConstruct); setHeadersList(this[kHeaders], request.headersList); setHeadersGuard(this[kHeaders], "request"); if (mode === "no-cors") { @@ -13523,7 +13242,7 @@ var require_request2 = __commonJS({ const request = new Request(kConstruct); request[kState] = innerRequest; request[kSignal] = signal; - request[kHeaders] = new Headers(kConstruct); + request[kHeaders] = new Headers2(kConstruct); setHeadersList(request[kHeaders], innerRequest.headersList); setHeadersGuard(request[kHeaders], guard); return request; @@ -16595,10 +16314,10 @@ var require_cookies = __commonJS({ var { parseSetCookie } = require_parse(); var { stringify } = require_util6(); var { webidl } = require_webidl(); - var { Headers } = require_headers(); + var { Headers: Headers2 } = require_headers(); function getCookies(headers) { webidl.argumentLengthCheck(arguments, 1, "getCookies"); - webidl.brandCheck(headers, Headers, { strict: false }); + webidl.brandCheck(headers, Headers2, { strict: false }); const cookie = headers.get("cookie"); const out = {}; if (!cookie) { @@ -16611,7 +16330,7 @@ var require_cookies = __commonJS({ return out; } function deleteCookie(headers, name, attributes) { - webidl.brandCheck(headers, Headers, { strict: false }); + webidl.brandCheck(headers, Headers2, { strict: false }); const prefix = "deleteCookie"; webidl.argumentLengthCheck(arguments, 2, prefix); name = webidl.converters.DOMString(name, prefix, "name"); @@ -16625,7 +16344,7 @@ var require_cookies = __commonJS({ } function getSetCookies(headers) { webidl.argumentLengthCheck(arguments, 1, "getSetCookies"); - webidl.brandCheck(headers, Headers, { strict: false }); + webidl.brandCheck(headers, Headers2, { strict: false }); const cookies = headers.getSetCookie(); if (!cookies) { return []; @@ -16634,7 +16353,7 @@ var require_cookies = __commonJS({ } function setCookie(headers, cookie) { webidl.argumentLengthCheck(arguments, 2, "setCookie"); - webidl.brandCheck(headers, Headers, { strict: false }); + webidl.brandCheck(headers, Headers2, { strict: false }); cookie = webidl.converters.Cookie(cookie); const str = stringify(cookie); if (str) { @@ -17324,7 +17043,7 @@ var require_connection = __commonJS({ var { CloseEvent } = require_events(); var { makeRequest } = require_request2(); var { fetching } = require_fetch(); - var { Headers, getHeadersList } = require_headers(); + var { Headers: Headers2, getHeadersList } = require_headers(); var { getDecodeSplit } = require_util2(); var { WebsocketFrameSend } = require_frame(); var crypto; @@ -17346,7 +17065,7 @@ var require_connection = __commonJS({ redirect: "error" }); if (options.headers) { - const headersList = getHeadersList(new Headers(options.headers)); + const headersList = getHeadersList(new Headers2(options.headers)); request.headersList = headersList; } const keyValue = crypto.randomBytes(16).toString("base64"); @@ -18843,2967 +18562,278 @@ var require_eventsource = __commonJS({ if (error2?.aborted === false) { this.close(); this.dispatchEvent(new Event("error")); - } - } - ); - }; - this.#controller = fetching(fetchParams); - } - /** - * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model - * @returns {Promise} - */ - async #reconnect() { - if (this.#readyState === CLOSED) return; - this.#readyState = CONNECTING; - this.dispatchEvent(new Event("error")); - await delay(this.#state.reconnectionTime); - if (this.#readyState !== CONNECTING) return; - if (this.#state.lastEventId.length) { - this.#request.headersList.set("last-event-id", this.#state.lastEventId, true); - } - this.#connect(); - } - /** - * Closes the connection, if any, and sets the readyState attribute to - * CLOSED. - */ - close() { - webidl.brandCheck(this, _EventSource); - if (this.#readyState === CLOSED) return; - this.#readyState = CLOSED; - this.#controller.abort(); - this.#request = null; - } - get onopen() { - return this.#events.open; - } - set onopen(fn) { - if (this.#events.open) { - this.removeEventListener("open", this.#events.open); - } - if (typeof fn === "function") { - this.#events.open = fn; - this.addEventListener("open", fn); - } else { - this.#events.open = null; - } - } - get onmessage() { - return this.#events.message; - } - set onmessage(fn) { - if (this.#events.message) { - this.removeEventListener("message", this.#events.message); - } - if (typeof fn === "function") { - this.#events.message = fn; - this.addEventListener("message", fn); - } else { - this.#events.message = null; - } - } - get onerror() { - return this.#events.error; - } - set onerror(fn) { - if (this.#events.error) { - this.removeEventListener("error", this.#events.error); - } - if (typeof fn === "function") { - this.#events.error = fn; - this.addEventListener("error", fn); - } else { - this.#events.error = null; - } - } - }; - var constantsPropertyDescriptors = { - CONNECTING: { - __proto__: null, - configurable: false, - enumerable: true, - value: CONNECTING, - writable: false - }, - OPEN: { - __proto__: null, - configurable: false, - enumerable: true, - value: OPEN, - writable: false - }, - CLOSED: { - __proto__: null, - configurable: false, - enumerable: true, - value: CLOSED, - writable: false - } - }; - Object.defineProperties(EventSource, constantsPropertyDescriptors); - Object.defineProperties(EventSource.prototype, constantsPropertyDescriptors); - Object.defineProperties(EventSource.prototype, { - close: kEnumerableProperty, - onerror: kEnumerableProperty, - onmessage: kEnumerableProperty, - onopen: kEnumerableProperty, - readyState: kEnumerableProperty, - url: kEnumerableProperty, - withCredentials: kEnumerableProperty - }); - webidl.converters.EventSourceInitDict = webidl.dictionaryConverter([ - { - key: "withCredentials", - converter: webidl.converters.boolean, - defaultValue: () => false - }, - { - key: "dispatcher", - // undici only - converter: webidl.converters.any - } - ]); - module2.exports = { - EventSource, - defaultReconnectionTime - }; - } -}); - -// node_modules/undici/index.js -var require_undici = __commonJS({ - "node_modules/undici/index.js"(exports2, module2) { - "use strict"; - var Client = require_client(); - var Dispatcher = require_dispatcher(); - var Pool = require_pool(); - var BalancedPool = require_balanced_pool(); - var Agent = require_agent(); - var ProxyAgent = require_proxy_agent(); - var EnvHttpProxyAgent = require_env_http_proxy_agent(); - var RetryAgent = require_retry_agent(); - var errors = require_errors(); - var util = require_util(); - var { InvalidArgumentError } = errors; - var api = require_api(); - var buildConnector = require_connect(); - var MockClient = require_mock_client(); - var MockAgent = require_mock_agent(); - var MockPool = require_mock_pool(); - var mockErrors = require_mock_errors(); - var RetryHandler = require_retry_handler(); - var { getGlobalDispatcher, setGlobalDispatcher } = require_global2(); - var DecoratorHandler = require_decorator_handler(); - var RedirectHandler = require_redirect_handler(); - var createRedirectInterceptor = require_redirect_interceptor(); - Object.assign(Dispatcher.prototype, api); - module2.exports.Dispatcher = Dispatcher; - module2.exports.Client = Client; - module2.exports.Pool = Pool; - module2.exports.BalancedPool = BalancedPool; - module2.exports.Agent = Agent; - module2.exports.ProxyAgent = ProxyAgent; - module2.exports.EnvHttpProxyAgent = EnvHttpProxyAgent; - module2.exports.RetryAgent = RetryAgent; - module2.exports.RetryHandler = RetryHandler; - module2.exports.DecoratorHandler = DecoratorHandler; - module2.exports.RedirectHandler = RedirectHandler; - module2.exports.createRedirectInterceptor = createRedirectInterceptor; - module2.exports.interceptors = { - redirect: require_redirect(), - retry: require_retry(), - dump: require_dump(), - dns: require_dns() - }; - module2.exports.buildConnector = buildConnector; - module2.exports.errors = errors; - module2.exports.util = { - parseHeaders: util.parseHeaders, - headerNameToString: util.headerNameToString - }; - function makeDispatcher(fn) { - return (url, opts, handler) => { - if (typeof opts === "function") { - handler = opts; - opts = null; - } - if (!url || typeof url !== "string" && typeof url !== "object" && !(url instanceof URL)) { - throw new InvalidArgumentError("invalid url"); - } - if (opts != null && typeof opts !== "object") { - throw new InvalidArgumentError("invalid opts"); - } - if (opts && opts.path != null) { - if (typeof opts.path !== "string") { - throw new InvalidArgumentError("invalid opts.path"); - } - let path = opts.path; - if (!opts.path.startsWith("/")) { - path = `/${path}`; - } - url = new URL(util.parseOrigin(url).origin + path); - } else { - if (!opts) { - opts = typeof url === "object" ? url : {}; - } - url = util.parseURL(url); - } - const { agent, dispatcher = getGlobalDispatcher() } = opts; - if (agent) { - throw new InvalidArgumentError("unsupported opts.agent. Did you mean opts.client?"); - } - return fn.call(dispatcher, { - ...opts, - origin: url.origin, - path: url.search ? `${url.pathname}${url.search}` : url.pathname, - method: opts.method || (opts.body ? "PUT" : "GET") - }, handler); - }; - } - module2.exports.setGlobalDispatcher = setGlobalDispatcher; - module2.exports.getGlobalDispatcher = getGlobalDispatcher; - var fetchImpl = require_fetch().fetch; - module2.exports.fetch = async function fetch2(init, options = void 0) { - try { - return await fetchImpl(init, options); - } catch (err) { - if (err && typeof err === "object") { - Error.captureStackTrace(err); - } - throw err; - } - }; - module2.exports.Headers = require_headers().Headers; - module2.exports.Response = require_response().Response; - module2.exports.Request = require_request2().Request; - module2.exports.FormData = require_formdata().FormData; - module2.exports.File = globalThis.File ?? require("node:buffer").File; - module2.exports.FileReader = require_filereader().FileReader; - var { setGlobalOrigin, getGlobalOrigin } = require_global(); - module2.exports.setGlobalOrigin = setGlobalOrigin; - module2.exports.getGlobalOrigin = getGlobalOrigin; - var { CacheStorage } = require_cachestorage(); - var { kConstruct } = require_symbols4(); - module2.exports.caches = new CacheStorage(kConstruct); - var { deleteCookie, getCookies, getSetCookies, setCookie } = require_cookies(); - module2.exports.deleteCookie = deleteCookie; - module2.exports.getCookies = getCookies; - module2.exports.getSetCookies = getSetCookies; - module2.exports.setCookie = setCookie; - var { parseMIMEType, serializeAMimeType } = require_data_url(); - module2.exports.parseMIMEType = parseMIMEType; - module2.exports.serializeAMimeType = serializeAMimeType; - var { CloseEvent, ErrorEvent, MessageEvent } = require_events(); - module2.exports.WebSocket = require_websocket().WebSocket; - module2.exports.CloseEvent = CloseEvent; - module2.exports.ErrorEvent = ErrorEvent; - module2.exports.MessageEvent = MessageEvent; - module2.exports.request = makeDispatcher(api.request); - module2.exports.stream = makeDispatcher(api.stream); - module2.exports.pipeline = makeDispatcher(api.pipeline); - module2.exports.connect = makeDispatcher(api.connect); - module2.exports.upgrade = makeDispatcher(api.upgrade); - module2.exports.MockClient = MockClient; - module2.exports.MockPool = MockPool; - module2.exports.MockAgent = MockAgent; - module2.exports.mockErrors = mockErrors; - var { EventSource } = require_eventsource(); - module2.exports.EventSource = EventSource; - } -}); - -// node_modules/@actions/core/node_modules/@actions/http-client/lib/index.js -var require_lib = __commonJS({ - "node_modules/@actions/core/node_modules/@actions/http-client/lib/index.js"(exports2) { - "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - 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 ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - } - __setModuleDefault(result, mod); - return result; - }; - })(); - var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); - } - return new (P || (P = 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.HttpClient = exports2.HttpClientResponse = exports2.HttpClientError = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; - exports2.getProxyUrl = getProxyUrl; - exports2.isHttps = isHttps; - var http = __importStar(require("http")); - var https = __importStar(require("https")); - var pm = __importStar(require_proxy()); - var tunnel = __importStar(require_tunnel2()); - var undici_1 = require_undici(); - var HttpCodes; - (function(HttpCodes2) { - HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; - HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; - HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; - HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; - HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; - HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; - HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; - HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; - HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; - HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; - HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; - HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; - HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; - HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; - HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; - HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; - HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; - HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; - HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; - HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; - HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; - HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; - HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; - HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; - HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; - HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; - HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; - })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); - var Headers; - (function(Headers2) { - Headers2["Accept"] = "accept"; - Headers2["ContentType"] = "content-type"; - })(Headers || (exports2.Headers = Headers = {})); - var MediaTypes; - (function(MediaTypes2) { - MediaTypes2["ApplicationJson"] = "application/json"; - })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); - function getProxyUrl(serverUrl) { - const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); - return proxyUrl ? proxyUrl.href : ""; - } - var HttpRedirectCodes = [ - HttpCodes.MovedPermanently, - HttpCodes.ResourceMoved, - HttpCodes.SeeOther, - HttpCodes.TemporaryRedirect, - HttpCodes.PermanentRedirect - ]; - var HttpResponseRetryCodes = [ - HttpCodes.BadGateway, - HttpCodes.ServiceUnavailable, - HttpCodes.GatewayTimeout - ]; - var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; - var ExponentialBackoffCeiling = 10; - var ExponentialBackoffTimeSlice = 5; - var HttpClientError = class _HttpClientError extends Error { - constructor(message, statusCode) { - super(message); - this.name = "HttpClientError"; - this.statusCode = statusCode; - Object.setPrototypeOf(this, _HttpClientError.prototype); - } - }; - exports2.HttpClientError = HttpClientError; - var HttpClientResponse = class { - constructor(message) { - this.message = message; - } - readBody() { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { - let output = Buffer.alloc(0); - this.message.on("data", (chunk) => { - output = Buffer.concat([output, chunk]); - }); - this.message.on("end", () => { - resolve(output.toString()); - }); - })); - }); - } - readBodyBuffer() { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { - const chunks = []; - this.message.on("data", (chunk) => { - chunks.push(chunk); - }); - this.message.on("end", () => { - resolve(Buffer.concat(chunks)); - }); - })); - }); - } - }; - exports2.HttpClientResponse = HttpClientResponse; - function isHttps(requestUrl) { - const parsedUrl = new URL(requestUrl); - return parsedUrl.protocol === "https:"; - } - var HttpClient = class { - constructor(userAgent, handlers, requestOptions) { - this._ignoreSslError = false; - this._allowRedirects = true; - this._allowRedirectDowngrade = false; - this._maxRedirects = 50; - this._allowRetries = false; - this._maxRetries = 1; - this._keepAlive = false; - this._disposed = false; - this.userAgent = this._getUserAgentWithOrchestrationId(userAgent); - this.handlers = handlers || []; - this.requestOptions = requestOptions; - if (requestOptions) { - if (requestOptions.ignoreSslError != null) { - this._ignoreSslError = requestOptions.ignoreSslError; - } - this._socketTimeout = requestOptions.socketTimeout; - if (requestOptions.allowRedirects != null) { - this._allowRedirects = requestOptions.allowRedirects; - } - if (requestOptions.allowRedirectDowngrade != null) { - this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; - } - if (requestOptions.maxRedirects != null) { - this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); - } - if (requestOptions.keepAlive != null) { - this._keepAlive = requestOptions.keepAlive; - } - if (requestOptions.allowRetries != null) { - this._allowRetries = requestOptions.allowRetries; - } - if (requestOptions.maxRetries != null) { - this._maxRetries = requestOptions.maxRetries; - } - } - } - options(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); - }); - } - get(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request("GET", requestUrl, null, additionalHeaders || {}); - }); - } - del(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request("DELETE", requestUrl, null, additionalHeaders || {}); - }); - } - post(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request("POST", requestUrl, data, additionalHeaders || {}); - }); - } - patch(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request("PATCH", requestUrl, data, additionalHeaders || {}); - }); - } - put(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request("PUT", requestUrl, data, additionalHeaders || {}); - }); - } - head(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request("HEAD", requestUrl, null, additionalHeaders || {}); - }); - } - sendStream(verb, requestUrl, stream, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request(verb, requestUrl, stream, additionalHeaders); - }); - } - /** - * Gets a typed object from an endpoint - * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise - */ - getJson(requestUrl_1) { - return __awaiter(this, arguments, void 0, function* (requestUrl, additionalHeaders = {}) { - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - const res = yield this.get(requestUrl, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - postJson(requestUrl_1, obj_1) { - return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); - const res = yield this.post(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - putJson(requestUrl_1, obj_1) { - return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); - const res = yield this.put(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - patchJson(requestUrl_1, obj_1) { - return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); - const res = yield this.patch(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - /** - * Makes a raw http request. - * All other methods such as get, post, patch, and request ultimately call this. - * Prefer get, del, post and patch - */ - request(verb, requestUrl, data, headers) { - return __awaiter(this, void 0, void 0, function* () { - if (this._disposed) { - throw new Error("Client has already been disposed."); - } - const parsedUrl = new URL(requestUrl); - let info2 = this._prepareRequest(verb, parsedUrl, headers); - const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; - let numTries = 0; - let response; - do { - response = yield this.requestRaw(info2, data); - if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { - let authenticationHandler; - for (const handler of this.handlers) { - if (handler.canHandleAuthentication(response)) { - authenticationHandler = handler; - break; - } - } - if (authenticationHandler) { - return authenticationHandler.handleAuthentication(this, info2, data); - } else { - return response; - } - } - let redirectsRemaining = this._maxRedirects; - while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { - const redirectUrl = response.message.headers["location"]; - if (!redirectUrl) { - break; - } - const parsedRedirectUrl = new URL(redirectUrl); - if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { - throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); - } - yield response.readBody(); - if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { - for (const header in headers) { - if (header.toLowerCase() === "authorization") { - delete headers[header]; - } - } - } - info2 = this._prepareRequest(verb, parsedRedirectUrl, headers); - response = yield this.requestRaw(info2, data); - redirectsRemaining--; - } - if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { - return response; - } - numTries += 1; - if (numTries < maxTries) { - yield response.readBody(); - yield this._performExponentialBackoff(numTries); - } - } while (numTries < maxTries); - return response; - }); - } - /** - * Needs to be called if keepAlive is set to true in request options. - */ - dispose() { - if (this._agent) { - this._agent.destroy(); - } - this._disposed = true; - } - /** - * Raw request. - * @param info - * @param data - */ - requestRaw(info2, data) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => { - function callbackForResult(err, res) { - if (err) { - reject(err); - } else if (!res) { - reject(new Error("Unknown error")); - } else { - resolve(res); - } - } - this.requestRawWithCallback(info2, data, callbackForResult); - }); - }); - } - /** - * Raw request with callback. - * @param info - * @param data - * @param onResult - */ - requestRawWithCallback(info2, data, onResult) { - if (typeof data === "string") { - if (!info2.options.headers) { - info2.options.headers = {}; - } - info2.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); - } - let callbackCalled = false; - function handleResult(err, res) { - if (!callbackCalled) { - callbackCalled = true; - onResult(err, res); - } - } - const req = info2.httpModule.request(info2.options, (msg) => { - const res = new HttpClientResponse(msg); - handleResult(void 0, res); - }); - let socket; - req.on("socket", (sock) => { - socket = sock; - }); - req.setTimeout(this._socketTimeout || 3 * 6e4, () => { - if (socket) { - socket.end(); - } - handleResult(new Error(`Request timeout: ${info2.options.path}`)); - }); - req.on("error", function(err) { - handleResult(err); - }); - if (data && typeof data === "string") { - req.write(data, "utf8"); - } - if (data && typeof data !== "string") { - data.on("close", function() { - req.end(); - }); - data.pipe(req); - } else { - req.end(); - } - } - /** - * Gets an http agent. This function is useful when you need an http agent that handles - * routing through a proxy server - depending upon the url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com - */ - getAgent(serverUrl) { - const parsedUrl = new URL(serverUrl); - return this._getAgent(parsedUrl); - } - getAgentDispatcher(serverUrl) { - const parsedUrl = new URL(serverUrl); - const proxyUrl = pm.getProxyUrl(parsedUrl); - const useProxy = proxyUrl && proxyUrl.hostname; - if (!useProxy) { - return; - } - return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); - } - _prepareRequest(method, requestUrl, headers) { - const info2 = {}; - info2.parsedUrl = requestUrl; - const usingSsl = info2.parsedUrl.protocol === "https:"; - info2.httpModule = usingSsl ? https : http; - const defaultPort = usingSsl ? 443 : 80; - info2.options = {}; - info2.options.host = info2.parsedUrl.hostname; - info2.options.port = info2.parsedUrl.port ? parseInt(info2.parsedUrl.port) : defaultPort; - info2.options.path = (info2.parsedUrl.pathname || "") + (info2.parsedUrl.search || ""); - info2.options.method = method; - info2.options.headers = this._mergeHeaders(headers); - if (this.userAgent != null) { - info2.options.headers["user-agent"] = this.userAgent; - } - info2.options.agent = this._getAgent(info2.parsedUrl); - if (this.handlers) { - for (const handler of this.handlers) { - handler.prepareRequest(info2.options); - } - } - return info2; - } - _mergeHeaders(headers) { - if (this.requestOptions && this.requestOptions.headers) { - return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); - } - return lowercaseKeys(headers || {}); - } - /** - * Gets an existing header value or returns a default. - * Handles converting number header values to strings since HTTP headers must be strings. - * Note: This returns string | string[] since some headers can have multiple values. - * For headers that must always be a single string (like Content-Type), use the - * specialized _getExistingOrDefaultContentTypeHeader method instead. - */ - _getExistingOrDefaultHeader(additionalHeaders, header, _default) { - let clientHeader; - if (this.requestOptions && this.requestOptions.headers) { - const headerValue = lowercaseKeys(this.requestOptions.headers)[header]; - if (headerValue) { - clientHeader = typeof headerValue === "number" ? headerValue.toString() : headerValue; - } - } - const additionalValue = additionalHeaders[header]; - if (additionalValue !== void 0) { - return typeof additionalValue === "number" ? additionalValue.toString() : additionalValue; - } - if (clientHeader !== void 0) { - return clientHeader; - } - return _default; - } - /** - * Specialized version of _getExistingOrDefaultHeader for Content-Type header. - * Always returns a single string (not an array) since Content-Type should be a single value. - * Converts arrays to comma-separated strings and numbers to strings to ensure type safety. - * This was split from _getExistingOrDefaultHeader to provide stricter typing for callers - * that assign the result to places expecting a string (e.g., additionalHeaders[Headers.ContentType]). - */ - _getExistingOrDefaultContentTypeHeader(additionalHeaders, _default) { - let clientHeader; - if (this.requestOptions && this.requestOptions.headers) { - const headerValue = lowercaseKeys(this.requestOptions.headers)[Headers.ContentType]; - if (headerValue) { - if (typeof headerValue === "number") { - clientHeader = String(headerValue); - } else if (Array.isArray(headerValue)) { - clientHeader = headerValue.join(", "); - } else { - clientHeader = headerValue; - } - } - } - const additionalValue = additionalHeaders[Headers.ContentType]; - if (additionalValue !== void 0) { - if (typeof additionalValue === "number") { - return String(additionalValue); - } else if (Array.isArray(additionalValue)) { - return additionalValue.join(", "); - } else { - return additionalValue; - } - } - if (clientHeader !== void 0) { - return clientHeader; - } - return _default; - } - _getAgent(parsedUrl) { - let agent; - const proxyUrl = pm.getProxyUrl(parsedUrl); - const useProxy = proxyUrl && proxyUrl.hostname; - if (this._keepAlive && useProxy) { - agent = this._proxyAgent; - } - if (!useProxy) { - agent = this._agent; - } - if (agent) { - return agent; - } - const usingSsl = parsedUrl.protocol === "https:"; - let maxSockets = 100; - if (this.requestOptions) { - maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; - } - if (proxyUrl && proxyUrl.hostname) { - const agentOptions = { - maxSockets, - keepAlive: this._keepAlive, - proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { - proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` - }), { host: proxyUrl.hostname, port: proxyUrl.port }) - }; - let tunnelAgent; - const overHttps = proxyUrl.protocol === "https:"; - if (usingSsl) { - tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; - } else { - tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; - } - agent = tunnelAgent(agentOptions); - this._proxyAgent = agent; - } - if (!agent) { - const options = { keepAlive: this._keepAlive, maxSockets }; - agent = usingSsl ? new https.Agent(options) : new http.Agent(options); - this._agent = agent; - } - if (usingSsl && this._ignoreSslError) { - agent.options = Object.assign(agent.options || {}, { - rejectUnauthorized: false - }); - } - return agent; - } - _getProxyAgentDispatcher(parsedUrl, proxyUrl) { - let proxyAgent; - if (this._keepAlive) { - proxyAgent = this._proxyAgentDispatcher; - } - if (proxyAgent) { - return proxyAgent; - } - const usingSsl = parsedUrl.protocol === "https:"; - proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { - token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` - })); - this._proxyAgentDispatcher = proxyAgent; - if (usingSsl && this._ignoreSslError) { - proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { - rejectUnauthorized: false - }); - } - return proxyAgent; - } - _getUserAgentWithOrchestrationId(userAgent) { - const baseUserAgent = userAgent || "actions/http-client"; - const orchId = process.env["ACTIONS_ORCHESTRATION_ID"]; - if (orchId) { - const sanitizedId = orchId.replace(/[^a-z0-9_.-]/gi, "_"); - return `${baseUserAgent} actions_orchestration_id/${sanitizedId}`; - } - return baseUserAgent; - } - _performExponentialBackoff(retryNumber) { - return __awaiter(this, void 0, void 0, function* () { - retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); - const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); - return new Promise((resolve) => setTimeout(() => resolve(), ms)); - }); - } - _processResponse(res, options) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { - const statusCode = res.message.statusCode || 0; - const response = { - statusCode, - result: null, - headers: {} - }; - if (statusCode === HttpCodes.NotFound) { - resolve(response); - } - function dateTimeDeserializer(key, value) { - if (typeof value === "string") { - const a = new Date(value); - if (!isNaN(a.valueOf())) { - return a; - } - } - return value; - } - let obj; - let contents; - try { - contents = yield res.readBody(); - if (contents && contents.length > 0) { - if (options && options.deserializeDates) { - obj = JSON.parse(contents, dateTimeDeserializer); - } else { - obj = JSON.parse(contents); - } - response.result = obj; - } - response.headers = res.message.headers; - } catch (err) { - } - if (statusCode > 299) { - let msg; - if (obj && obj.message) { - msg = obj.message; - } else if (contents && contents.length > 0) { - msg = contents; - } else { - msg = `Failed request: (${statusCode})`; - } - const err = new HttpClientError(msg, statusCode); - err.result = response.result; - reject(err); - } else { - resolve(response); - } - })); - }); - } - }; - exports2.HttpClient = HttpClient; - var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); - } -}); - -// node_modules/@actions/core/node_modules/@actions/http-client/lib/auth.js -var require_auth = __commonJS({ - "node_modules/@actions/core/node_modules/@actions/http-client/lib/auth.js"(exports2) { - "use strict"; - var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); - } - return new (P || (P = 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.PersonalAccessTokenCredentialHandler = exports2.BearerCredentialHandler = exports2.BasicCredentialHandler = void 0; - var BasicCredentialHandler = class { - constructor(username, password) { - this.username = username; - this.password = password; - } - prepareRequest(options) { - if (!options.headers) { - throw Error("The request has no headers"); - } - options.headers["Authorization"] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { - throw new Error("not implemented"); - }); - } - }; - exports2.BasicCredentialHandler = BasicCredentialHandler; - var BearerCredentialHandler = class { - constructor(token) { - this.token = token; - } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - if (!options.headers) { - throw Error("The request has no headers"); - } - options.headers["Authorization"] = `Bearer ${this.token}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { - throw new Error("not implemented"); - }); - } - }; - exports2.BearerCredentialHandler = BearerCredentialHandler; - var PersonalAccessTokenCredentialHandler = class { - constructor(token) { - this.token = token; - } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - if (!options.headers) { - throw Error("The request has no headers"); - } - options.headers["Authorization"] = `Basic ${Buffer.from(`PAT:${this.token}`).toString("base64")}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { - throw new Error("not implemented"); - }); - } - }; - exports2.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; - } -}); - -// node_modules/@actions/core/lib/oidc-utils.js -var require_oidc_utils = __commonJS({ - "node_modules/@actions/core/lib/oidc-utils.js"(exports2) { - "use strict"; - var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); - } - return new (P || (P = 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.OidcClient = void 0; - var http_client_1 = require_lib(); - var auth_1 = require_auth(); - var core_1 = require_core(); - var OidcClient = class _OidcClient { - static createHttpClient(allowRetry = true, maxRetry = 10) { - const requestOptions = { - allowRetries: allowRetry, - maxRetries: maxRetry - }; - return new http_client_1.HttpClient("actions/oidc-client", [new auth_1.BearerCredentialHandler(_OidcClient.getRequestToken())], requestOptions); - } - static getRequestToken() { - const token = process.env["ACTIONS_ID_TOKEN_REQUEST_TOKEN"]; - if (!token) { - throw new Error("Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable"); - } - return token; - } - static getIDTokenUrl() { - const runtimeUrl = process.env["ACTIONS_ID_TOKEN_REQUEST_URL"]; - if (!runtimeUrl) { - throw new Error("Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable"); - } - return runtimeUrl; - } - static getCall(id_token_url) { - return __awaiter(this, void 0, void 0, function* () { - var _a; - const httpclient = _OidcClient.createHttpClient(); - const res = yield httpclient.getJson(id_token_url).catch((error2) => { - throw new Error(`Failed to get ID Token. - - Error Code : ${error2.statusCode} - - Error Message: ${error2.message}`); - }); - const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; - if (!id_token) { - throw new Error("Response json body do not have ID Token field"); - } - return id_token; - }); - } - static getIDToken(audience) { - return __awaiter(this, void 0, void 0, function* () { - try { - let id_token_url = _OidcClient.getIDTokenUrl(); - if (audience) { - const encodedAudience = encodeURIComponent(audience); - id_token_url = `${id_token_url}&audience=${encodedAudience}`; - } - (0, core_1.debug)(`ID token url is ${id_token_url}`); - const id_token = yield _OidcClient.getCall(id_token_url); - (0, core_1.setSecret)(id_token); - return id_token; - } catch (error2) { - throw new Error(`Error message: ${error2.message}`); - } - }); - } - }; - exports2.OidcClient = OidcClient; - } -}); - -// node_modules/@actions/core/lib/summary.js -var require_summary = __commonJS({ - "node_modules/@actions/core/lib/summary.js"(exports2) { - "use strict"; - var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); - } - return new (P || (P = 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.summary = exports2.markdownSummary = exports2.SUMMARY_DOCS_URL = exports2.SUMMARY_ENV_VAR = void 0; - var os_1 = require("os"); - var fs_1 = require("fs"); - var { access, appendFile, writeFile } = fs_1.promises; - exports2.SUMMARY_ENV_VAR = "GITHUB_STEP_SUMMARY"; - exports2.SUMMARY_DOCS_URL = "https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary"; - var Summary = class { - constructor() { - this._buffer = ""; - } - /** - * Finds the summary file path from the environment, rejects if env var is not found or file does not exist - * Also checks r/w permissions. - * - * @returns step summary file path - */ - filePath() { - return __awaiter(this, void 0, void 0, function* () { - if (this._filePath) { - return this._filePath; - } - const pathFromEnv = process.env[exports2.SUMMARY_ENV_VAR]; - if (!pathFromEnv) { - throw new Error(`Unable to find environment variable for $${exports2.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); - } - try { - yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK); - } catch (_a) { - throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); - } - this._filePath = pathFromEnv; - return this._filePath; - }); - } - /** - * Wraps content in an HTML tag, adding any HTML attributes - * - * @param {string} tag HTML tag to wrap - * @param {string | null} content content within the tag - * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add - * - * @returns {string} content wrapped in HTML element - */ - wrap(tag, content, attrs = {}) { - const htmlAttrs = Object.entries(attrs).map(([key, value]) => ` ${key}="${value}"`).join(""); - if (!content) { - return `<${tag}${htmlAttrs}>`; - } - return `<${tag}${htmlAttrs}>${content}`; - } - /** - * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default. - * - * @param {SummaryWriteOptions} [options] (optional) options for write operation - * - * @returns {Promise} summary instance - */ - write(options) { - return __awaiter(this, void 0, void 0, function* () { - const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); - const filePath = yield this.filePath(); - const writeFunc = overwrite ? writeFile : appendFile; - yield writeFunc(filePath, this._buffer, { encoding: "utf8" }); - return this.emptyBuffer(); - }); - } - /** - * Clears the summary buffer and wipes the summary file - * - * @returns {Summary} summary instance - */ - clear() { - return __awaiter(this, void 0, void 0, function* () { - return this.emptyBuffer().write({ overwrite: true }); - }); - } - /** - * Returns the current summary buffer as a string - * - * @returns {string} string of summary buffer - */ - stringify() { - return this._buffer; - } - /** - * If the summary buffer is empty - * - * @returns {boolen} true if the buffer is empty - */ - isEmptyBuffer() { - return this._buffer.length === 0; - } - /** - * Resets the summary buffer without writing to summary file - * - * @returns {Summary} summary instance - */ - emptyBuffer() { - this._buffer = ""; - return this; - } - /** - * Adds raw text to the summary buffer - * - * @param {string} text content to add - * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false) - * - * @returns {Summary} summary instance - */ - addRaw(text, addEOL = false) { - this._buffer += text; - return addEOL ? this.addEOL() : this; - } - /** - * Adds the operating system-specific end-of-line marker to the buffer - * - * @returns {Summary} summary instance - */ - addEOL() { - return this.addRaw(os_1.EOL); - } - /** - * Adds an HTML codeblock to the summary buffer - * - * @param {string} code content to render within fenced code block - * @param {string} lang (optional) language to syntax highlight code - * - * @returns {Summary} summary instance - */ - addCodeBlock(code, lang) { - const attrs = Object.assign({}, lang && { lang }); - const element = this.wrap("pre", this.wrap("code", code), attrs); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML list to the summary buffer - * - * @param {string[]} items list of items to render - * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false) - * - * @returns {Summary} summary instance - */ - addList(items, ordered = false) { - const tag = ordered ? "ol" : "ul"; - const listItems = items.map((item) => this.wrap("li", item)).join(""); - const element = this.wrap(tag, listItems); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML table to the summary buffer - * - * @param {SummaryTableCell[]} rows table rows - * - * @returns {Summary} summary instance - */ - addTable(rows) { - const tableBody = rows.map((row) => { - const cells = row.map((cell) => { - if (typeof cell === "string") { - return this.wrap("td", cell); - } - const { header, data, colspan, rowspan } = cell; - const tag = header ? "th" : "td"; - const attrs = Object.assign(Object.assign({}, colspan && { colspan }), rowspan && { rowspan }); - return this.wrap(tag, data, attrs); - }).join(""); - return this.wrap("tr", cells); - }).join(""); - const element = this.wrap("table", tableBody); - return this.addRaw(element).addEOL(); - } - /** - * Adds a collapsable HTML details element to the summary buffer - * - * @param {string} label text for the closed state - * @param {string} content collapsable content - * - * @returns {Summary} summary instance - */ - addDetails(label, content) { - const element = this.wrap("details", this.wrap("summary", label) + content); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML image tag to the summary buffer - * - * @param {string} src path to the image you to embed - * @param {string} alt text description of the image - * @param {SummaryImageOptions} options (optional) addition image attributes - * - * @returns {Summary} summary instance - */ - addImage(src, alt, options) { - const { width, height } = options || {}; - const attrs = Object.assign(Object.assign({}, width && { width }), height && { height }); - const element = this.wrap("img", null, Object.assign({ src, alt }, attrs)); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML section heading element - * - * @param {string} text heading text - * @param {number | string} [level=1] (optional) the heading level, default: 1 - * - * @returns {Summary} summary instance - */ - addHeading(text, level) { - const tag = `h${level}`; - const allowedTag = ["h1", "h2", "h3", "h4", "h5", "h6"].includes(tag) ? tag : "h1"; - const element = this.wrap(allowedTag, text); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML thematic break (
) to the summary buffer - * - * @returns {Summary} summary instance - */ - addSeparator() { - const element = this.wrap("hr", null); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML line break (
) to the summary buffer - * - * @returns {Summary} summary instance - */ - addBreak() { - const element = this.wrap("br", null); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML blockquote to the summary buffer - * - * @param {string} text quote text - * @param {string} cite (optional) citation url - * - * @returns {Summary} summary instance - */ - addQuote(text, cite) { - const attrs = Object.assign({}, cite && { cite }); - const element = this.wrap("blockquote", text, attrs); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML anchor tag to the summary buffer - * - * @param {string} text link text/content - * @param {string} href hyperlink - * - * @returns {Summary} summary instance - */ - addLink(text, href) { - const element = this.wrap("a", text, { href }); - return this.addRaw(element).addEOL(); - } - }; - var _summary = new Summary(); - exports2.markdownSummary = _summary; - exports2.summary = _summary; - } -}); - -// node_modules/@actions/core/lib/path-utils.js -var require_path_utils = __commonJS({ - "node_modules/@actions/core/lib/path-utils.js"(exports2) { - "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - 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 ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - } - __setModuleDefault(result, mod); - return result; - }; - })(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.toPosixPath = toPosixPath; - exports2.toWin32Path = toWin32Path; - exports2.toPlatformPath = toPlatformPath; - var path = __importStar(require("path")); - function toPosixPath(pth) { - return pth.replace(/[\\]/g, "/"); - } - function toWin32Path(pth) { - return pth.replace(/[/]/g, "\\"); - } - function toPlatformPath(pth) { - return pth.replace(/[/\\]/g, path.sep); - } - } -}); - -// node_modules/@actions/io/lib/io-util.js -var require_io_util = __commonJS({ - "node_modules/@actions/io/lib/io-util.js"(exports2) { - "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - 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 ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - } - __setModuleDefault(result, mod); - return result; - }; - })(); - var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); - } - return new (P || (P = 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 _a; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.READONLY = exports2.UV_FS_O_EXLOCK = exports2.IS_WINDOWS = exports2.unlink = exports2.symlink = exports2.stat = exports2.rmdir = exports2.rm = exports2.rename = exports2.readdir = exports2.open = exports2.mkdir = exports2.lstat = exports2.copyFile = exports2.chmod = void 0; - exports2.readlink = readlink; - exports2.exists = exists; - exports2.isDirectory = isDirectory; - exports2.isRooted = isRooted; - exports2.tryGetExecutablePath = tryGetExecutablePath; - exports2.getCmdPath = getCmdPath; - var fs = __importStar(require("fs")); - var path = __importStar(require("path")); - _a = fs.promises, exports2.chmod = _a.chmod, exports2.copyFile = _a.copyFile, exports2.lstat = _a.lstat, exports2.mkdir = _a.mkdir, exports2.open = _a.open, exports2.readdir = _a.readdir, exports2.rename = _a.rename, exports2.rm = _a.rm, exports2.rmdir = _a.rmdir, exports2.stat = _a.stat, exports2.symlink = _a.symlink, exports2.unlink = _a.unlink; - exports2.IS_WINDOWS = process.platform === "win32"; - function readlink(fsPath) { - return __awaiter(this, void 0, void 0, function* () { - const result = yield fs.promises.readlink(fsPath); - if (exports2.IS_WINDOWS && !result.endsWith("\\")) { - return `${result}\\`; - } - return result; - }); - } - exports2.UV_FS_O_EXLOCK = 268435456; - exports2.READONLY = fs.constants.O_RDONLY; - function exists(fsPath) { - return __awaiter(this, void 0, void 0, function* () { - try { - yield (0, exports2.stat)(fsPath); - } catch (err) { - if (err.code === "ENOENT") { - return false; - } - throw err; - } - return true; - }); - } - function isDirectory(fsPath_1) { - return __awaiter(this, arguments, void 0, function* (fsPath, useStat = false) { - const stats = useStat ? yield (0, exports2.stat)(fsPath) : yield (0, exports2.lstat)(fsPath); - return stats.isDirectory(); - }); - } - function isRooted(p) { - p = normalizeSeparators(p); - if (!p) { - throw new Error('isRooted() parameter "p" cannot be empty'); - } - if (exports2.IS_WINDOWS) { - return p.startsWith("\\") || /^[A-Z]:/i.test(p); - } - return p.startsWith("/"); - } - function tryGetExecutablePath(filePath, extensions) { - return __awaiter(this, void 0, void 0, function* () { - let stats = void 0; - try { - stats = yield (0, exports2.stat)(filePath); - } catch (err) { - if (err.code !== "ENOENT") { - console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); - } - } - if (stats && stats.isFile()) { - if (exports2.IS_WINDOWS) { - const upperExt = path.extname(filePath).toUpperCase(); - if (extensions.some((validExt) => validExt.toUpperCase() === upperExt)) { - return filePath; - } - } else { - if (isUnixExecutable(stats)) { - return filePath; - } - } - } - const originalFilePath = filePath; - for (const extension of extensions) { - filePath = originalFilePath + extension; - stats = void 0; - try { - stats = yield (0, exports2.stat)(filePath); - } catch (err) { - if (err.code !== "ENOENT") { - console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); - } - } - if (stats && stats.isFile()) { - if (exports2.IS_WINDOWS) { - try { - const directory = path.dirname(filePath); - const upperName = path.basename(filePath).toUpperCase(); - for (const actualName of yield (0, exports2.readdir)(directory)) { - if (upperName === actualName.toUpperCase()) { - filePath = path.join(directory, actualName); - break; - } - } - } catch (err) { - console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`); - } - return filePath; - } else { - if (isUnixExecutable(stats)) { - return filePath; - } - } - } - } - return ""; - }); - } - function normalizeSeparators(p) { - p = p || ""; - if (exports2.IS_WINDOWS) { - p = p.replace(/\//g, "\\"); - return p.replace(/\\\\+/g, "\\"); - } - return p.replace(/\/\/+/g, "/"); - } - function isUnixExecutable(stats) { - return (stats.mode & 1) > 0 || (stats.mode & 8) > 0 && process.getgid !== void 0 && stats.gid === process.getgid() || (stats.mode & 64) > 0 && process.getuid !== void 0 && stats.uid === process.getuid(); - } - function getCmdPath() { - var _a2; - return (_a2 = process.env["COMSPEC"]) !== null && _a2 !== void 0 ? _a2 : `cmd.exe`; - } - } -}); - -// node_modules/@actions/io/lib/io.js -var require_io = __commonJS({ - "node_modules/@actions/io/lib/io.js"(exports2) { - "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - 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 ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - } - __setModuleDefault(result, mod); - return result; - }; - })(); - var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); - } - return new (P || (P = 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.cp = cp; - exports2.mv = mv; - exports2.rmRF = rmRF; - exports2.mkdirP = mkdirP; - exports2.which = which; - exports2.findInPath = findInPath; - var assert_1 = require("assert"); - var path = __importStar(require("path")); - var ioUtil = __importStar(require_io_util()); - function cp(source_1, dest_1) { - return __awaiter(this, arguments, void 0, function* (source, dest, options = {}) { - const { force, recursive, copySourceDirectory } = readCopyOptions(options); - const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null; - if (destStat && destStat.isFile() && !force) { - return; - } - const newDest = destStat && destStat.isDirectory() && copySourceDirectory ? path.join(dest, path.basename(source)) : dest; - if (!(yield ioUtil.exists(source))) { - throw new Error(`no such file or directory: ${source}`); - } - const sourceStat = yield ioUtil.stat(source); - if (sourceStat.isDirectory()) { - if (!recursive) { - throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`); - } else { - yield cpDirRecursive(source, newDest, 0, force); - } - } else { - if (path.relative(source, newDest) === "") { - throw new Error(`'${newDest}' and '${source}' are the same file`); - } - yield copyFile(source, newDest, force); - } - }); - } - function mv(source_1, dest_1) { - return __awaiter(this, arguments, void 0, function* (source, dest, options = {}) { - if (yield ioUtil.exists(dest)) { - let destExists = true; - if (yield ioUtil.isDirectory(dest)) { - dest = path.join(dest, path.basename(source)); - destExists = yield ioUtil.exists(dest); - } - if (destExists) { - if (options.force == null || options.force) { - yield rmRF(dest); - } else { - throw new Error("Destination already exists"); - } - } - } - yield mkdirP(path.dirname(dest)); - yield ioUtil.rename(source, dest); - }); - } - function rmRF(inputPath) { - return __awaiter(this, void 0, void 0, function* () { - if (ioUtil.IS_WINDOWS) { - if (/[*"<>|]/.test(inputPath)) { - throw new Error('File path must not contain `*`, `"`, `<`, `>` or `|` on Windows'); - } - } - try { - yield ioUtil.rm(inputPath, { - force: true, - maxRetries: 3, - recursive: true, - retryDelay: 300 - }); - } catch (err) { - throw new Error(`File was unable to be removed ${err}`); - } - }); - } - function mkdirP(fsPath) { - return __awaiter(this, void 0, void 0, function* () { - (0, assert_1.ok)(fsPath, "a path argument must be provided"); - yield ioUtil.mkdir(fsPath, { recursive: true }); - }); - } - function which(tool, check) { - return __awaiter(this, void 0, void 0, function* () { - if (!tool) { - throw new Error("parameter 'tool' is required"); - } - if (check) { - const result = yield which(tool, false); - if (!result) { - if (ioUtil.IS_WINDOWS) { - throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`); - } else { - throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`); - } - } - return result; - } - const matches = yield findInPath(tool); - if (matches && matches.length > 0) { - return matches[0]; - } - return ""; - }); - } - function findInPath(tool) { - return __awaiter(this, void 0, void 0, function* () { - if (!tool) { - throw new Error("parameter 'tool' is required"); - } - const extensions = []; - if (ioUtil.IS_WINDOWS && process.env["PATHEXT"]) { - for (const extension of process.env["PATHEXT"].split(path.delimiter)) { - if (extension) { - extensions.push(extension); - } - } - } - if (ioUtil.isRooted(tool)) { - const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions); - if (filePath) { - return [filePath]; - } - return []; - } - if (tool.includes(path.sep)) { - return []; - } - const directories = []; - if (process.env.PATH) { - for (const p of process.env.PATH.split(path.delimiter)) { - if (p) { - directories.push(p); - } - } - } - const matches = []; - for (const directory of directories) { - const filePath = yield ioUtil.tryGetExecutablePath(path.join(directory, tool), extensions); - if (filePath) { - matches.push(filePath); - } - } - return matches; - }); - } - function readCopyOptions(options) { - const force = options.force == null ? true : options.force; - const recursive = Boolean(options.recursive); - const copySourceDirectory = options.copySourceDirectory == null ? true : Boolean(options.copySourceDirectory); - return { force, recursive, copySourceDirectory }; - } - function cpDirRecursive(sourceDir, destDir, currentDepth, force) { - return __awaiter(this, void 0, void 0, function* () { - if (currentDepth >= 255) - return; - currentDepth++; - yield mkdirP(destDir); - const files = yield ioUtil.readdir(sourceDir); - for (const fileName of files) { - const srcFile = `${sourceDir}/${fileName}`; - const destFile = `${destDir}/${fileName}`; - const srcFileStat = yield ioUtil.lstat(srcFile); - if (srcFileStat.isDirectory()) { - yield cpDirRecursive(srcFile, destFile, currentDepth, force); - } else { - yield copyFile(srcFile, destFile, force); - } - } - yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode); - }); - } - function copyFile(srcFile, destFile, force) { - return __awaiter(this, void 0, void 0, function* () { - if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) { - try { - yield ioUtil.lstat(destFile); - yield ioUtil.unlink(destFile); - } catch (e) { - if (e.code === "EPERM") { - yield ioUtil.chmod(destFile, "0666"); - yield ioUtil.unlink(destFile); - } - } - const symlinkFull = yield ioUtil.readlink(srcFile); - yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? "junction" : null); - } else if (!(yield ioUtil.exists(destFile)) || force) { - yield ioUtil.copyFile(srcFile, destFile); - } - }); - } - } -}); - -// node_modules/@actions/exec/lib/toolrunner.js -var require_toolrunner = __commonJS({ - "node_modules/@actions/exec/lib/toolrunner.js"(exports2) { - "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - 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 ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - } - __setModuleDefault(result, mod); - return result; - }; - })(); - var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); - } - return new (P || (P = 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.ToolRunner = void 0; - exports2.argStringToArray = argStringToArray; - var os = __importStar(require("os")); - var events = __importStar(require("events")); - var child = __importStar(require("child_process")); - var path = __importStar(require("path")); - var io = __importStar(require_io()); - var ioUtil = __importStar(require_io_util()); - var timers_1 = require("timers"); - var IS_WINDOWS = process.platform === "win32"; - var ToolRunner = class extends events.EventEmitter { - constructor(toolPath, args, options) { - super(); - if (!toolPath) { - throw new Error("Parameter 'toolPath' cannot be null or empty."); - } - this.toolPath = toolPath; - this.args = args || []; - this.options = options || {}; - } - _debug(message) { - if (this.options.listeners && this.options.listeners.debug) { - this.options.listeners.debug(message); - } - } - _getCommandString(options, noPrefix) { - const toolPath = this._getSpawnFileName(); - const args = this._getSpawnArgs(options); - let cmd = noPrefix ? "" : "[command]"; - if (IS_WINDOWS) { - if (this._isCmdFile()) { - cmd += toolPath; - for (const a of args) { - cmd += ` ${a}`; - } - } else if (options.windowsVerbatimArguments) { - cmd += `"${toolPath}"`; - for (const a of args) { - cmd += ` ${a}`; - } - } else { - cmd += this._windowsQuoteCmdArg(toolPath); - for (const a of args) { - cmd += ` ${this._windowsQuoteCmdArg(a)}`; - } - } - } else { - cmd += toolPath; - for (const a of args) { - cmd += ` ${a}`; - } - } - return cmd; - } - _processLineBuffer(data, strBuffer, onLine) { - try { - let s = strBuffer + data.toString(); - let n = s.indexOf(os.EOL); - while (n > -1) { - const line = s.substring(0, n); - onLine(line); - s = s.substring(n + os.EOL.length); - n = s.indexOf(os.EOL); - } - return s; - } catch (err) { - this._debug(`error processing line. Failed with error ${err}`); - return ""; - } - } - _getSpawnFileName() { - if (IS_WINDOWS) { - if (this._isCmdFile()) { - return process.env["COMSPEC"] || "cmd.exe"; - } - } - return this.toolPath; - } - _getSpawnArgs(options) { - if (IS_WINDOWS) { - if (this._isCmdFile()) { - let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`; - for (const a of this.args) { - argline += " "; - argline += options.windowsVerbatimArguments ? a : this._windowsQuoteCmdArg(a); - } - argline += '"'; - return [argline]; - } - } - return this.args; - } - _endsWith(str, end) { - return str.endsWith(end); - } - _isCmdFile() { - const upperToolPath = this.toolPath.toUpperCase(); - return this._endsWith(upperToolPath, ".CMD") || this._endsWith(upperToolPath, ".BAT"); - } - _windowsQuoteCmdArg(arg) { - if (!this._isCmdFile()) { - return this._uvQuoteCmdArg(arg); - } - if (!arg) { - return '""'; - } - const cmdSpecialChars = [ - " ", - " ", - "&", - "(", - ")", - "[", - "]", - "{", - "}", - "^", - "=", - ";", - "!", - "'", - "+", - ",", - "`", - "~", - "|", - "<", - ">", - '"' - ]; - let needsQuotes = false; - for (const char of arg) { - if (cmdSpecialChars.some((x) => x === char)) { - needsQuotes = true; - break; - } - } - if (!needsQuotes) { - return arg; - } - let reverse = '"'; - let quoteHit = true; - for (let i = arg.length; i > 0; i--) { - reverse += arg[i - 1]; - if (quoteHit && arg[i - 1] === "\\") { - reverse += "\\"; - } else if (arg[i - 1] === '"') { - quoteHit = true; - reverse += '"'; - } else { - quoteHit = false; - } - } - reverse += '"'; - return reverse.split("").reverse().join(""); - } - _uvQuoteCmdArg(arg) { - if (!arg) { - return '""'; - } - if (!arg.includes(" ") && !arg.includes(" ") && !arg.includes('"')) { - return arg; - } - if (!arg.includes('"') && !arg.includes("\\")) { - return `"${arg}"`; - } - let reverse = '"'; - let quoteHit = true; - for (let i = arg.length; i > 0; i--) { - reverse += arg[i - 1]; - if (quoteHit && arg[i - 1] === "\\") { - reverse += "\\"; - } else if (arg[i - 1] === '"') { - quoteHit = true; - reverse += "\\"; - } else { - quoteHit = false; - } - } - reverse += '"'; - return reverse.split("").reverse().join(""); - } - _cloneExecOptions(options) { - options = options || {}; - const result = { - cwd: options.cwd || process.cwd(), - env: options.env || process.env, - silent: options.silent || false, - windowsVerbatimArguments: options.windowsVerbatimArguments || false, - failOnStdErr: options.failOnStdErr || false, - ignoreReturnCode: options.ignoreReturnCode || false, - delay: options.delay || 1e4 - }; - result.outStream = options.outStream || process.stdout; - result.errStream = options.errStream || process.stderr; - return result; - } - _getSpawnOptions(options, toolPath) { - options = options || {}; - const result = {}; - result.cwd = options.cwd; - result.env = options.env; - result["windowsVerbatimArguments"] = options.windowsVerbatimArguments || this._isCmdFile(); - if (options.windowsVerbatimArguments) { - result.argv0 = `"${toolPath}"`; - } - return result; - } - /** - * Exec a tool. - * Output will be streamed to the live console. - * Returns promise with return code - * - * @param tool path to tool to exec - * @param options optional exec options. See ExecOptions - * @returns number - */ - exec() { - return __awaiter(this, void 0, void 0, function* () { - if (!ioUtil.isRooted(this.toolPath) && (this.toolPath.includes("/") || IS_WINDOWS && this.toolPath.includes("\\"))) { - this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); - } - this.toolPath = yield io.which(this.toolPath, true); - return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { - this._debug(`exec tool: ${this.toolPath}`); - this._debug("arguments:"); - for (const arg of this.args) { - this._debug(` ${arg}`); - } - const optionsNonNull = this._cloneExecOptions(this.options); - if (!optionsNonNull.silent && optionsNonNull.outStream) { - optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL); - } - const state = new ExecState(optionsNonNull, this.toolPath); - state.on("debug", (message) => { - this._debug(message); - }); - if (this.options.cwd && !(yield ioUtil.exists(this.options.cwd))) { - return reject(new Error(`The cwd: ${this.options.cwd} does not exist!`)); - } - const fileName = this._getSpawnFileName(); - const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName)); - let stdbuffer = ""; - if (cp.stdout) { - cp.stdout.on("data", (data) => { - if (this.options.listeners && this.options.listeners.stdout) { - this.options.listeners.stdout(data); - } - if (!optionsNonNull.silent && optionsNonNull.outStream) { - optionsNonNull.outStream.write(data); - } - stdbuffer = this._processLineBuffer(data, stdbuffer, (line) => { - if (this.options.listeners && this.options.listeners.stdline) { - this.options.listeners.stdline(line); - } - }); - }); - } - let errbuffer = ""; - if (cp.stderr) { - cp.stderr.on("data", (data) => { - state.processStderr = true; - if (this.options.listeners && this.options.listeners.stderr) { - this.options.listeners.stderr(data); - } - if (!optionsNonNull.silent && optionsNonNull.errStream && optionsNonNull.outStream) { - const s = optionsNonNull.failOnStdErr ? optionsNonNull.errStream : optionsNonNull.outStream; - s.write(data); - } - errbuffer = this._processLineBuffer(data, errbuffer, (line) => { - if (this.options.listeners && this.options.listeners.errline) { - this.options.listeners.errline(line); - } - }); - }); - } - cp.on("error", (err) => { - state.processError = err.message; - state.processExited = true; - state.processClosed = true; - state.CheckComplete(); - }); - cp.on("exit", (code) => { - state.processExitCode = code; - state.processExited = true; - this._debug(`Exit code ${code} received from tool '${this.toolPath}'`); - state.CheckComplete(); - }); - cp.on("close", (code) => { - state.processExitCode = code; - state.processExited = true; - state.processClosed = true; - this._debug(`STDIO streams have closed for tool '${this.toolPath}'`); - state.CheckComplete(); - }); - state.on("done", (error2, exitCode) => { - if (stdbuffer.length > 0) { - this.emit("stdline", stdbuffer); - } - if (errbuffer.length > 0) { - this.emit("errline", errbuffer); - } - cp.removeAllListeners(); - if (error2) { - reject(error2); - } else { - resolve(exitCode); - } - }); - if (this.options.input) { - if (!cp.stdin) { - throw new Error("child process missing stdin"); - } - cp.stdin.end(this.options.input); - } - })); - }); - } - }; - exports2.ToolRunner = ToolRunner; - function argStringToArray(argString) { - const args = []; - let inQuotes = false; - let escaped = false; - let arg = ""; - function append(c) { - if (escaped && c !== '"') { - arg += "\\"; - } - arg += c; - escaped = false; - } - for (let i = 0; i < argString.length; i++) { - const c = argString.charAt(i); - if (c === '"') { - if (!escaped) { - inQuotes = !inQuotes; - } else { - append(c); - } - continue; - } - if (c === "\\" && escaped) { - append(c); - continue; - } - if (c === "\\" && inQuotes) { - escaped = true; - continue; - } - if (c === " " && !inQuotes) { - if (arg.length > 0) { - args.push(arg); - arg = ""; - } - continue; + } + } + ); + }; + this.#controller = fetching(fetchParams); + } + /** + * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model + * @returns {Promise} + */ + async #reconnect() { + if (this.#readyState === CLOSED) return; + this.#readyState = CONNECTING; + this.dispatchEvent(new Event("error")); + await delay(this.#state.reconnectionTime); + if (this.#readyState !== CONNECTING) return; + if (this.#state.lastEventId.length) { + this.#request.headersList.set("last-event-id", this.#state.lastEventId, true); } - append(c); + this.#connect(); } - if (arg.length > 0) { - args.push(arg.trim()); + /** + * Closes the connection, if any, and sets the readyState attribute to + * CLOSED. + */ + close() { + webidl.brandCheck(this, _EventSource); + if (this.#readyState === CLOSED) return; + this.#readyState = CLOSED; + this.#controller.abort(); + this.#request = null; } - return args; - } - var ExecState = class _ExecState extends events.EventEmitter { - constructor(options, toolPath) { - super(); - this.processClosed = false; - this.processError = ""; - this.processExitCode = 0; - this.processExited = false; - this.processStderr = false; - this.delay = 1e4; - this.done = false; - this.timeout = null; - if (!toolPath) { - throw new Error("toolPath must not be empty"); - } - this.options = options; - this.toolPath = toolPath; - if (options.delay) { - this.delay = options.delay; - } + get onopen() { + return this.#events.open; } - CheckComplete() { - if (this.done) { - return; + set onopen(fn) { + if (this.#events.open) { + this.removeEventListener("open", this.#events.open); } - if (this.processClosed) { - this._setResult(); - } else if (this.processExited) { - this.timeout = (0, timers_1.setTimeout)(_ExecState.HandleTimeout, this.delay, this); + if (typeof fn === "function") { + this.#events.open = fn; + this.addEventListener("open", fn); + } else { + this.#events.open = null; } } - _debug(message) { - this.emit("debug", message); + get onmessage() { + return this.#events.message; } - _setResult() { - let error2; - if (this.processExited) { - if (this.processError) { - error2 = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`); - } else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) { - error2 = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`); - } else if (this.processStderr && this.options.failOnStdErr) { - error2 = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`); - } + set onmessage(fn) { + if (this.#events.message) { + this.removeEventListener("message", this.#events.message); } - if (this.timeout) { - clearTimeout(this.timeout); - this.timeout = null; + if (typeof fn === "function") { + this.#events.message = fn; + this.addEventListener("message", fn); + } else { + this.#events.message = null; } - this.done = true; - this.emit("done", error2, this.processExitCode); } - static HandleTimeout(state) { - if (state.done) { - return; + get onerror() { + return this.#events.error; + } + set onerror(fn) { + if (this.#events.error) { + this.removeEventListener("error", this.#events.error); } - if (!state.processClosed && state.processExited) { - const message = `The STDIO streams did not close within ${state.delay / 1e3} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`; - state._debug(message); + if (typeof fn === "function") { + this.#events.error = fn; + this.addEventListener("error", fn); + } else { + this.#events.error = null; } - state._setResult(); } }; - } -}); - -// node_modules/@actions/exec/lib/exec.js -var require_exec = __commonJS({ - "node_modules/@actions/exec/lib/exec.js"(exports2) { - "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; + var constantsPropertyDescriptors = { + CONNECTING: { + __proto__: null, + configurable: false, + enumerable: true, + value: CONNECTING, + writable: false + }, + OPEN: { + __proto__: null, + configurable: false, + enumerable: true, + value: OPEN, + writable: false + }, + CLOSED: { + __proto__: null, + configurable: false, + enumerable: true, + value: CLOSED, + writable: false } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; + }; + Object.defineProperties(EventSource, constantsPropertyDescriptors); + Object.defineProperties(EventSource.prototype, constantsPropertyDescriptors); + Object.defineProperties(EventSource.prototype, { + close: kEnumerableProperty, + onerror: kEnumerableProperty, + onmessage: kEnumerableProperty, + onopen: kEnumerableProperty, + readyState: kEnumerableProperty, + url: kEnumerableProperty, + withCredentials: kEnumerableProperty }); - var __importStar = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function(o2) { - var ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - } - __setModuleDefault(result, mod); - return result; - }; - })(); - var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); + webidl.converters.EventSourceInitDict = webidl.dictionaryConverter([ + { + key: "withCredentials", + converter: webidl.converters.boolean, + defaultValue: () => false + }, + { + key: "dispatcher", + // undici only + converter: webidl.converters.any } - return new (P || (P = 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()); - }); + ]); + module2.exports = { + EventSource, + defaultReconnectionTime }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.exec = exec; - exports2.getExecOutput = getExecOutput; - var string_decoder_1 = require("string_decoder"); - var tr = __importStar(require_toolrunner()); - function exec(commandLine, args, options) { - return __awaiter(this, void 0, void 0, function* () { - const commandArgs = tr.argStringToArray(commandLine); - if (commandArgs.length === 0) { - throw new Error(`Parameter 'commandLine' cannot be null or empty.`); - } - const toolPath = commandArgs[0]; - args = commandArgs.slice(1).concat(args || []); - const runner = new tr.ToolRunner(toolPath, args, options); - return runner.exec(); - }); - } - function getExecOutput(commandLine, args, options) { - return __awaiter(this, void 0, void 0, function* () { - var _a, _b; - let stdout = ""; - let stderr = ""; - const stdoutDecoder = new string_decoder_1.StringDecoder("utf8"); - const stderrDecoder = new string_decoder_1.StringDecoder("utf8"); - const originalStdoutListener = (_a = options === null || options === void 0 ? void 0 : options.listeners) === null || _a === void 0 ? void 0 : _a.stdout; - const originalStdErrListener = (_b = options === null || options === void 0 ? void 0 : options.listeners) === null || _b === void 0 ? void 0 : _b.stderr; - const stdErrListener = (data) => { - stderr += stderrDecoder.write(data); - if (originalStdErrListener) { - originalStdErrListener(data); - } - }; - const stdOutListener = (data) => { - stdout += stdoutDecoder.write(data); - if (originalStdoutListener) { - originalStdoutListener(data); - } - }; - const listeners = Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.listeners), { stdout: stdOutListener, stderr: stdErrListener }); - const exitCode = yield exec(commandLine, args, Object.assign(Object.assign({}, options), { listeners })); - stdout += stdoutDecoder.end(); - stderr += stderrDecoder.end(); - return { - exitCode, - stdout, - stderr - }; - }); - } } }); -// node_modules/@actions/core/lib/platform.js -var require_platform = __commonJS({ - "node_modules/@actions/core/lib/platform.js"(exports2) { +// node_modules/undici/index.js +var require_undici = __commonJS({ + "node_modules/undici/index.js"(exports2, module2) { "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - 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 ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - } - __setModuleDefault(result, mod); - return result; - }; - })(); - var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); - } - return new (P || (P = 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 Client = require_client(); + var Dispatcher = require_dispatcher(); + var Pool = require_pool(); + var BalancedPool = require_balanced_pool(); + var Agent = require_agent(); + var ProxyAgent2 = require_proxy_agent(); + var EnvHttpProxyAgent = require_env_http_proxy_agent(); + var RetryAgent = require_retry_agent(); + var errors = require_errors(); + var util = require_util(); + var { InvalidArgumentError } = errors; + var api = require_api(); + var buildConnector = require_connect(); + var MockClient = require_mock_client(); + var MockAgent = require_mock_agent(); + var MockPool = require_mock_pool(); + var mockErrors = require_mock_errors(); + var RetryHandler = require_retry_handler(); + var { getGlobalDispatcher, setGlobalDispatcher } = require_global2(); + var DecoratorHandler = require_decorator_handler(); + var RedirectHandler = require_redirect_handler(); + var createRedirectInterceptor = require_redirect_interceptor(); + Object.assign(Dispatcher.prototype, api); + module2.exports.Dispatcher = Dispatcher; + module2.exports.Client = Client; + module2.exports.Pool = Pool; + module2.exports.BalancedPool = BalancedPool; + module2.exports.Agent = Agent; + module2.exports.ProxyAgent = ProxyAgent2; + module2.exports.EnvHttpProxyAgent = EnvHttpProxyAgent; + module2.exports.RetryAgent = RetryAgent; + module2.exports.RetryHandler = RetryHandler; + module2.exports.DecoratorHandler = DecoratorHandler; + module2.exports.RedirectHandler = RedirectHandler; + module2.exports.createRedirectInterceptor = createRedirectInterceptor; + module2.exports.interceptors = { + redirect: require_redirect(), + retry: require_retry(), + dump: require_dump(), + dns: require_dns() }; - var __importDefault = exports2 && exports2.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; + module2.exports.buildConnector = buildConnector; + module2.exports.errors = errors; + module2.exports.util = { + parseHeaders: util.parseHeaders, + headerNameToString: util.headerNameToString }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isLinux = exports2.isMacOS = exports2.isWindows = exports2.arch = exports2.platform = void 0; - exports2.getDetails = getDetails; - var os_1 = __importDefault(require("os")); - var exec = __importStar(require_exec()); - var getWindowsInfo = () => __awaiter(void 0, void 0, void 0, function* () { - const { stdout: version } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Version"', void 0, { - silent: true - }); - const { stdout: name } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Caption"', void 0, { - silent: true - }); - return { - name: name.trim(), - version: version.trim() - }; - }); - var getMacOsInfo = () => __awaiter(void 0, void 0, void 0, function* () { - var _a, _b, _c, _d; - const { stdout } = yield exec.getExecOutput("sw_vers", void 0, { - silent: true - }); - const version = (_b = (_a = stdout.match(/ProductVersion:\s*(.+)/)) === null || _a === void 0 ? void 0 : _a[1]) !== null && _b !== void 0 ? _b : ""; - const name = (_d = (_c = stdout.match(/ProductName:\s*(.+)/)) === null || _c === void 0 ? void 0 : _c[1]) !== null && _d !== void 0 ? _d : ""; - return { - name, - version - }; - }); - var getLinuxInfo = () => __awaiter(void 0, void 0, void 0, function* () { - const { stdout } = yield exec.getExecOutput("lsb_release", ["-i", "-r", "-s"], { - silent: true - }); - const [name, version] = stdout.trim().split("\n"); - return { - name, - version - }; - }); - exports2.platform = os_1.default.platform(); - exports2.arch = os_1.default.arch(); - exports2.isWindows = exports2.platform === "win32"; - exports2.isMacOS = exports2.platform === "darwin"; - exports2.isLinux = exports2.platform === "linux"; - function getDetails() { - return __awaiter(this, void 0, void 0, function* () { - return Object.assign(Object.assign({}, yield exports2.isWindows ? getWindowsInfo() : exports2.isMacOS ? getMacOsInfo() : getLinuxInfo()), { - platform: exports2.platform, - arch: exports2.arch, - isWindows: exports2.isWindows, - isMacOS: exports2.isMacOS, - isLinux: exports2.isLinux - }); - }); - } - } -}); - -// node_modules/@actions/core/lib/core.js -var require_core = __commonJS({ - "node_modules/@actions/core/lib/core.js"(exports2) { - "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - 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 ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + function makeDispatcher(fn) { + return (url, opts, handler) => { + if (typeof opts === "function") { + handler = opts; + opts = null; } - __setModuleDefault(result, mod); - return result; - }; - })(); - var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } + if (!url || typeof url !== "string" && typeof url !== "object" && !(url instanceof URL)) { + throw new InvalidArgumentError("invalid url"); } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + if (opts != null && typeof opts !== "object") { + throw new InvalidArgumentError("invalid opts"); + } + if (opts && opts.path != null) { + if (typeof opts.path !== "string") { + throw new InvalidArgumentError("invalid opts.path"); } + let path = opts.path; + if (!opts.path.startsWith("/")) { + path = `/${path}`; + } + url = new URL(util.parseOrigin(url).origin + path); + } else { + if (!opts) { + opts = typeof url === "object" ? url : {}; + } + url = util.parseURL(url); } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + const { agent, dispatcher = getGlobalDispatcher() } = opts; + if (agent) { + throw new InvalidArgumentError("unsupported opts.agent. Did you mean opts.client?"); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.platform = exports2.toPlatformPath = exports2.toWin32Path = exports2.toPosixPath = exports2.markdownSummary = exports2.summary = exports2.ExitCode = void 0; - exports2.exportVariable = exportVariable; - exports2.setSecret = setSecret; - exports2.addPath = addPath; - exports2.getInput = getInput; - exports2.getMultilineInput = getMultilineInput; - exports2.getBooleanInput = getBooleanInput; - exports2.setOutput = setOutput; - exports2.setCommandEcho = setCommandEcho; - exports2.setFailed = setFailed; - exports2.isDebug = isDebug; - exports2.debug = debug; - exports2.error = error2; - exports2.warning = warning; - exports2.notice = notice; - exports2.info = info2; - exports2.startGroup = startGroup; - exports2.endGroup = endGroup; - exports2.group = group; - exports2.saveState = saveState; - exports2.getState = getState; - exports2.getIDToken = getIDToken; - var command_1 = require_command(); - var file_command_1 = require_file_command(); - var utils_1 = require_utils(); - var os = __importStar(require("os")); - var path = __importStar(require("path")); - var oidc_utils_1 = require_oidc_utils(); - var ExitCode; - (function(ExitCode2) { - ExitCode2[ExitCode2["Success"] = 0] = "Success"; - ExitCode2[ExitCode2["Failure"] = 1] = "Failure"; - })(ExitCode || (exports2.ExitCode = ExitCode = {})); - function exportVariable(name, val) { - const convertedVal = (0, utils_1.toCommandValue)(val); - process.env[name] = convertedVal; - const filePath = process.env["GITHUB_ENV"] || ""; - if (filePath) { - return (0, file_command_1.issueFileCommand)("ENV", (0, file_command_1.prepareKeyValueMessage)(name, val)); - } - (0, command_1.issueCommand)("set-env", { name }, convertedVal); - } - function setSecret(secret) { - (0, command_1.issueCommand)("add-mask", {}, secret); - } - function addPath(inputPath) { - const filePath = process.env["GITHUB_PATH"] || ""; - if (filePath) { - (0, file_command_1.issueFileCommand)("PATH", inputPath); - } else { - (0, command_1.issueCommand)("add-path", {}, inputPath); - } - process.env["PATH"] = `${inputPath}${path.delimiter}${process.env["PATH"]}`; - } - function getInput(name, options) { - const val = process.env[`INPUT_${name.replace(/ /g, "_").toUpperCase()}`] || ""; - if (options && options.required && !val) { - throw new Error(`Input required and not supplied: ${name}`); - } - if (options && options.trimWhitespace === false) { - return val; - } - return val.trim(); - } - function getMultilineInput(name, options) { - const inputs = getInput(name, options).split("\n").filter((x) => x !== ""); - if (options && options.trimWhitespace === false) { - return inputs; - } - return inputs.map((input) => input.trim()); - } - function getBooleanInput(name, options) { - const trueValue = ["true", "True", "TRUE"]; - const falseValue = ["false", "False", "FALSE"]; - const val = getInput(name, options); - if (trueValue.includes(val)) - return true; - if (falseValue.includes(val)) - return false; - throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name} -Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); - } - function setOutput(name, value) { - const filePath = process.env["GITHUB_OUTPUT"] || ""; - if (filePath) { - return (0, file_command_1.issueFileCommand)("OUTPUT", (0, file_command_1.prepareKeyValueMessage)(name, value)); - } - process.stdout.write(os.EOL); - (0, command_1.issueCommand)("set-output", { name }, (0, utils_1.toCommandValue)(value)); - } - function setCommandEcho(enabled) { - (0, command_1.issue)("echo", enabled ? "on" : "off"); - } - function setFailed(message) { - process.exitCode = ExitCode.Failure; - error2(message); - } - function isDebug() { - return process.env["RUNNER_DEBUG"] === "1"; - } - function debug(message) { - (0, command_1.issueCommand)("debug", {}, message); - } - function error2(message, properties = {}) { - (0, command_1.issueCommand)("error", (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); - } - function warning(message, properties = {}) { - (0, command_1.issueCommand)("warning", (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); - } - function notice(message, properties = {}) { - (0, command_1.issueCommand)("notice", (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); - } - function info2(message) { - process.stdout.write(message + os.EOL); - } - function startGroup(name) { - (0, command_1.issue)("group", name); - } - function endGroup() { - (0, command_1.issue)("endgroup"); + return fn.call(dispatcher, { + ...opts, + origin: url.origin, + path: url.search ? `${url.pathname}${url.search}` : url.pathname, + method: opts.method || (opts.body ? "PUT" : "GET") + }, handler); + }; } - function group(name, fn) { - return __awaiter(this, void 0, void 0, function* () { - startGroup(name); - let result; - try { - result = yield fn(); - } finally { - endGroup(); + module2.exports.setGlobalDispatcher = setGlobalDispatcher; + module2.exports.getGlobalDispatcher = getGlobalDispatcher; + var fetchImpl = require_fetch().fetch; + module2.exports.fetch = async function fetch2(init, options = void 0) { + try { + return await fetchImpl(init, options); + } catch (err) { + if (err && typeof err === "object") { + Error.captureStackTrace(err); } - return result; - }); - } - function saveState(name, value) { - const filePath = process.env["GITHUB_STATE"] || ""; - if (filePath) { - return (0, file_command_1.issueFileCommand)("STATE", (0, file_command_1.prepareKeyValueMessage)(name, value)); + throw err; } - (0, command_1.issueCommand)("save-state", { name }, (0, utils_1.toCommandValue)(value)); - } - function getState(name) { - return process.env[`STATE_${name}`] || ""; - } - function getIDToken(aud) { - return __awaiter(this, void 0, void 0, function* () { - return yield oidc_utils_1.OidcClient.getIDToken(aud); - }); - } - var summary_1 = require_summary(); - Object.defineProperty(exports2, "summary", { enumerable: true, get: function() { - return summary_1.summary; - } }); - var summary_2 = require_summary(); - Object.defineProperty(exports2, "markdownSummary", { enumerable: true, get: function() { - return summary_2.markdownSummary; - } }); - var path_utils_1 = require_path_utils(); - Object.defineProperty(exports2, "toPosixPath", { enumerable: true, get: function() { - return path_utils_1.toPosixPath; - } }); - Object.defineProperty(exports2, "toWin32Path", { enumerable: true, get: function() { - return path_utils_1.toWin32Path; - } }); - Object.defineProperty(exports2, "toPlatformPath", { enumerable: true, get: function() { - return path_utils_1.toPlatformPath; - } }); - exports2.platform = __importStar(require_platform()); + }; + module2.exports.Headers = require_headers().Headers; + module2.exports.Response = require_response().Response; + module2.exports.Request = require_request2().Request; + module2.exports.FormData = require_formdata().FormData; + module2.exports.File = globalThis.File ?? require("node:buffer").File; + module2.exports.FileReader = require_filereader().FileReader; + var { setGlobalOrigin, getGlobalOrigin } = require_global(); + module2.exports.setGlobalOrigin = setGlobalOrigin; + module2.exports.getGlobalOrigin = getGlobalOrigin; + var { CacheStorage } = require_cachestorage(); + var { kConstruct } = require_symbols4(); + module2.exports.caches = new CacheStorage(kConstruct); + var { deleteCookie, getCookies, getSetCookies, setCookie } = require_cookies(); + module2.exports.deleteCookie = deleteCookie; + module2.exports.getCookies = getCookies; + module2.exports.getSetCookies = getSetCookies; + module2.exports.setCookie = setCookie; + var { parseMIMEType, serializeAMimeType } = require_data_url(); + module2.exports.parseMIMEType = parseMIMEType; + module2.exports.serializeAMimeType = serializeAMimeType; + var { CloseEvent, ErrorEvent, MessageEvent } = require_events(); + module2.exports.WebSocket = require_websocket().WebSocket; + module2.exports.CloseEvent = CloseEvent; + module2.exports.ErrorEvent = ErrorEvent; + module2.exports.MessageEvent = MessageEvent; + module2.exports.request = makeDispatcher(api.request); + module2.exports.stream = makeDispatcher(api.stream); + module2.exports.pipeline = makeDispatcher(api.pipeline); + module2.exports.connect = makeDispatcher(api.connect); + module2.exports.upgrade = makeDispatcher(api.upgrade); + module2.exports.MockClient = MockClient; + module2.exports.MockPool = MockPool; + module2.exports.MockAgent = MockAgent; + module2.exports.mockErrors = mockErrors; + var { EventSource } = require_eventsource(); + module2.exports.EventSource = EventSource; } }); // node_modules/docker-modem/lib/utils.js -var require_utils3 = __commonJS({ +var require_utils2 = __commonJS({ "node_modules/docker-modem/lib/utils.js"(exports2, module2) { var arr = []; var each = arr.forEach; @@ -21834,7 +18864,7 @@ var require_http = __commonJS({ var nativeHttps = require("https"); var nativeHttp = require("http"); var url = require("url"); - var utils = require_utils3(); + var utils = require_utils2(); var maxRedirects = module2.exports.maxRedirects = 5; var protocols = { https: nativeHttps, @@ -22457,7 +19487,7 @@ var require_ber = __commonJS({ }); // node_modules/asn1/lib/index.js -var require_lib2 = __commonJS({ +var require_lib = __commonJS({ "node_modules/asn1/lib/index.js"(exports2, module2) { var Ber = require_ber(); module2.exports = { @@ -25948,7 +22978,7 @@ var require_cpufeatures = __commonJS({ }); // node_modules/cpu-features/lib/index.js -var require_lib3 = __commonJS({ +var require_lib2 = __commonJS({ "node_modules/cpu-features/lib/index.js"(exports2, module2) { "use strict"; var binding = require_cpufeatures(); @@ -25963,7 +22993,7 @@ var require_constants6 = __commonJS({ var crypto = require("crypto"); var cpuInfo; try { - cpuInfo = require_lib3()(); + cpuInfo = require_lib2()(); } catch { } var { bindingAvailable, CIPHER_INFO, MAC_INFO } = require_crypto(); @@ -26349,10 +23379,10 @@ var require_constants6 = __commonJS({ }); // node_modules/ssh2/lib/protocol/utils.js -var require_utils4 = __commonJS({ +var require_utils3 = __commonJS({ "node_modules/ssh2/lib/protocol/utils.js"(exports2, module2) { "use strict"; - var Ber = require_lib2().Ber; + var Ber = require_lib().Ber; var DISCONNECT_REASON; var FastBuffer = Buffer[Symbol.species]; var TypedArrayFill = Object.getPrototypeOf(Uint8Array.prototype).fill; @@ -27110,7 +24140,7 @@ var require_crypto = __commonJS({ randomFillSync, timingSafeEqual } = require("crypto"); - var { readUInt32BE, writeUInt32BE } = require_utils4(); + var { readUInt32BE, writeUInt32BE } = require_utils3(); var FastBuffer = Buffer[Symbol.species]; var MAX_SEQNO = 2 ** 32 - 1; var EMPTY_BUFFER = Buffer.alloc(0); @@ -28439,7 +25469,7 @@ var require_keyParser = __commonJS({ verify: verify_ } = require("crypto"); var supportedOpenSSLCiphers = getCiphers(); - var { Ber } = require_lib2(); + var { Ber } = require_lib(); var bcrypt_pbkdf = require_bcrypt_pbkdf().pbkdf; var { CIPHER_INFO } = require_crypto(); var { eddsaSupported, SUPPORTED_CIPHER } = require_constants6(); @@ -28449,7 +25479,7 @@ var require_keyParser = __commonJS({ readString, readUInt32BE, writeUInt32BE - } = require_utils4(); + } = require_utils3(); var SYM_HASH_ALGO = /* @__PURE__ */ Symbol("Hash Algorithm"); var SYM_PRIV_PEM = /* @__PURE__ */ Symbol("Private key PEM"); var SYM_PUB_PEM = /* @__PURE__ */ Symbol("Public key PEM"); @@ -29679,7 +26709,7 @@ var require_agent2 = __commonJS({ readUInt32BE, writeUInt32BE, writeUInt32LE - } = require_utils4(); + } = require_utils3(); function once(cb) { let called = false; return (...args) => { @@ -30726,7 +27756,7 @@ var require_handlers_misc = __commonJS({ doFatalError, sigSSHToASN1, writeUInt32BE - } = require_utils4(); + } = require_utils3(); var { CHANNEL_OPEN_FAILURE, COMPAT, @@ -31656,7 +28686,7 @@ var require_kex = __commonJS({ generateKeyPairSync, randomFillSync } = require("crypto"); - var { Ber } = require_lib2(); + var { Ber } = require_lib(); var { COMPAT, curve25519Supported, @@ -31683,7 +28713,7 @@ var require_kex = __commonJS({ FastBuffer, sigSSHToASN1, writeUInt32BE - } = require_utils4(); + } = require_utils3(); var { PacketReader, PacketWriter, @@ -31790,10 +28820,10 @@ var require_kex = __commonJS({ let clientList; let serverList; let i; - const debug = self2._debug; - debug && debug("Inbound: Handshake in progress"); - debug && debug(`Handshake: (local) KEX method: ${localKex}`); - debug && debug(`Handshake: (remote) KEX method: ${remote.kex}`); + const debug2 = self2._debug; + debug2 && debug2("Inbound: Handshake in progress"); + debug2 && debug2(`Handshake: (local) KEX method: ${localKex}`); + debug2 && debug2(`Handshake: (remote) KEX method: ${remote.kex}`); let remoteExtInfoEnabled; if (self2._server) { serverList = localKex; @@ -31811,10 +28841,10 @@ var require_kex = __commonJS({ self2._strictMode = serverList.indexOf("kex-strict-s-v00@openssh.com") !== -1; } if (self2._strictMode) { - debug && debug("Handshake: strict KEX mode enabled"); + debug2 && debug2("Handshake: strict KEX mode enabled"); if (self2._decipher.inSeqno !== 1) { - if (debug) - debug("Handshake: KEXINIT not first packet in strict KEX mode"); + if (debug2) + debug2("Handshake: KEXINIT not first packet in strict KEX mode"); return doFatalError( self2, "Handshake failed: KEXINIT not first packet in strict KEX mode", @@ -31826,7 +28856,7 @@ var require_kex = __commonJS({ } for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i) ; if (i === clientList.length) { - debug && debug("Handshake: no matching key exchange algorithm"); + debug2 && debug2("Handshake: no matching key exchange algorithm"); return doFatalError( self2, "Handshake failed: no matching key exchange algorithm", @@ -31835,13 +28865,13 @@ var require_kex = __commonJS({ ); } init.kex = clientList[i]; - debug && debug(`Handshake: KEX algorithm: ${clientList[i]}`); + debug2 && debug2(`Handshake: KEX algorithm: ${clientList[i]}`); if (firstFollows && (!remote.kex.length || clientList[i] !== remote.kex[0])) { self2._skipNextInboundPacket = true; } const localSrvHostKey = local.lists.serverHostKey.array; - debug && debug(`Handshake: (local) Host key format: ${localSrvHostKey}`); - debug && debug( + debug2 && debug2(`Handshake: (local) Host key format: ${localSrvHostKey}`); + debug2 && debug2( `Handshake: (remote) Host key format: ${remote.serverHostKey}` ); if (self2._server) { @@ -31853,7 +28883,7 @@ var require_kex = __commonJS({ } for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i) ; if (i === clientList.length) { - debug && debug("Handshake: No matching host key format"); + debug2 && debug2("Handshake: No matching host key format"); return doFatalError( self2, "Handshake failed: no matching host key format", @@ -31862,10 +28892,10 @@ var require_kex = __commonJS({ ); } init.serverHostKey = clientList[i]; - debug && debug(`Handshake: Host key format: ${clientList[i]}`); + debug2 && debug2(`Handshake: Host key format: ${clientList[i]}`); const localCSCipher = local.lists.cs.cipher.array; - debug && debug(`Handshake: (local) C->S cipher: ${localCSCipher}`); - debug && debug(`Handshake: (remote) C->S cipher: ${remote.cs.cipher}`); + debug2 && debug2(`Handshake: (local) C->S cipher: ${localCSCipher}`); + debug2 && debug2(`Handshake: (remote) C->S cipher: ${remote.cs.cipher}`); if (self2._server) { serverList = localCSCipher; clientList = remote.cs.cipher; @@ -31875,7 +28905,7 @@ var require_kex = __commonJS({ } for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i) ; if (i === clientList.length) { - debug && debug("Handshake: No matching C->S cipher"); + debug2 && debug2("Handshake: No matching C->S cipher"); return doFatalError( self2, "Handshake failed: no matching C->S cipher", @@ -31884,10 +28914,10 @@ var require_kex = __commonJS({ ); } init.cs.cipher = clientList[i]; - debug && debug(`Handshake: C->S Cipher: ${clientList[i]}`); + debug2 && debug2(`Handshake: C->S Cipher: ${clientList[i]}`); const localSCCipher = local.lists.sc.cipher.array; - debug && debug(`Handshake: (local) S->C cipher: ${localSCCipher}`); - debug && debug(`Handshake: (remote) S->C cipher: ${remote.sc.cipher}`); + debug2 && debug2(`Handshake: (local) S->C cipher: ${localSCCipher}`); + debug2 && debug2(`Handshake: (remote) S->C cipher: ${remote.sc.cipher}`); if (self2._server) { serverList = localSCCipher; clientList = remote.sc.cipher; @@ -31897,7 +28927,7 @@ var require_kex = __commonJS({ } for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i) ; if (i === clientList.length) { - debug && debug("Handshake: No matching S->C cipher"); + debug2 && debug2("Handshake: No matching S->C cipher"); return doFatalError( self2, "Handshake failed: no matching S->C cipher", @@ -31906,13 +28936,13 @@ var require_kex = __commonJS({ ); } init.sc.cipher = clientList[i]; - debug && debug(`Handshake: S->C cipher: ${clientList[i]}`); + debug2 && debug2(`Handshake: S->C cipher: ${clientList[i]}`); const localCSMAC = local.lists.cs.mac.array; - debug && debug(`Handshake: (local) C->S MAC: ${localCSMAC}`); - debug && debug(`Handshake: (remote) C->S MAC: ${remote.cs.mac}`); + debug2 && debug2(`Handshake: (local) C->S MAC: ${localCSMAC}`); + debug2 && debug2(`Handshake: (remote) C->S MAC: ${remote.cs.mac}`); if (CIPHER_INFO[init.cs.cipher].authLen > 0) { init.cs.mac = ""; - debug && debug("Handshake: C->S MAC: "); + debug2 && debug2("Handshake: C->S MAC: "); } else { if (self2._server) { serverList = localCSMAC; @@ -31923,7 +28953,7 @@ var require_kex = __commonJS({ } for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i) ; if (i === clientList.length) { - debug && debug("Handshake: No matching C->S MAC"); + debug2 && debug2("Handshake: No matching C->S MAC"); return doFatalError( self2, "Handshake failed: no matching C->S MAC", @@ -31932,14 +28962,14 @@ var require_kex = __commonJS({ ); } init.cs.mac = clientList[i]; - debug && debug(`Handshake: C->S MAC: ${clientList[i]}`); + debug2 && debug2(`Handshake: C->S MAC: ${clientList[i]}`); } const localSCMAC = local.lists.sc.mac.array; - debug && debug(`Handshake: (local) S->C MAC: ${localSCMAC}`); - debug && debug(`Handshake: (remote) S->C MAC: ${remote.sc.mac}`); + debug2 && debug2(`Handshake: (local) S->C MAC: ${localSCMAC}`); + debug2 && debug2(`Handshake: (remote) S->C MAC: ${remote.sc.mac}`); if (CIPHER_INFO[init.sc.cipher].authLen > 0) { init.sc.mac = ""; - debug && debug("Handshake: S->C MAC: "); + debug2 && debug2("Handshake: S->C MAC: "); } else { if (self2._server) { serverList = localSCMAC; @@ -31950,7 +28980,7 @@ var require_kex = __commonJS({ } for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i) ; if (i === clientList.length) { - debug && debug("Handshake: No matching S->C MAC"); + debug2 && debug2("Handshake: No matching S->C MAC"); return doFatalError( self2, "Handshake failed: no matching S->C MAC", @@ -31959,11 +28989,11 @@ var require_kex = __commonJS({ ); } init.sc.mac = clientList[i]; - debug && debug(`Handshake: S->C MAC: ${clientList[i]}`); + debug2 && debug2(`Handshake: S->C MAC: ${clientList[i]}`); } const localCSCompress = local.lists.cs.compress.array; - debug && debug(`Handshake: (local) C->S compression: ${localCSCompress}`); - debug && debug(`Handshake: (remote) C->S compression: ${remote.cs.compress}`); + debug2 && debug2(`Handshake: (local) C->S compression: ${localCSCompress}`); + debug2 && debug2(`Handshake: (remote) C->S compression: ${remote.cs.compress}`); if (self2._server) { serverList = localCSCompress; clientList = remote.cs.compress; @@ -31973,7 +29003,7 @@ var require_kex = __commonJS({ } for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i) ; if (i === clientList.length) { - debug && debug("Handshake: No matching C->S compression"); + debug2 && debug2("Handshake: No matching C->S compression"); return doFatalError( self2, "Handshake failed: no matching C->S compression", @@ -31982,10 +29012,10 @@ var require_kex = __commonJS({ ); } init.cs.compress = clientList[i]; - debug && debug(`Handshake: C->S compression: ${clientList[i]}`); + debug2 && debug2(`Handshake: C->S compression: ${clientList[i]}`); const localSCCompress = local.lists.sc.compress.array; - debug && debug(`Handshake: (local) S->C compression: ${localSCCompress}`); - debug && debug(`Handshake: (remote) S->C compression: ${remote.sc.compress}`); + debug2 && debug2(`Handshake: (local) S->C compression: ${localSCCompress}`); + debug2 && debug2(`Handshake: (remote) S->C compression: ${remote.sc.compress}`); if (self2._server) { serverList = localSCCompress; clientList = remote.sc.compress; @@ -31995,7 +29025,7 @@ var require_kex = __commonJS({ } for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i) ; if (i === clientList.length) { - debug && debug("Handshake: No matching S->C compression"); + debug2 && debug2("Handshake: No matching S->C compression"); return doFatalError( self2, "Handshake failed: no matching S->C compression", @@ -32004,7 +29034,7 @@ var require_kex = __commonJS({ ); } init.sc.compress = clientList[i]; - debug && debug(`Handshake: S->C compression: ${clientList[i]}`); + debug2 && debug2(`Handshake: S->C compression: ${clientList[i]}`); init.cs.lang = ""; init.sc.lang = ""; if (self2._kex) { @@ -33316,7 +30346,7 @@ var require_Protocol = __commonJS({ convertSignature, sendPacket, writeUInt32BE - } = require_utils4(); + } = require_utils3(); var { PacketReader, PacketWriter, @@ -33380,9 +30410,9 @@ var require_Protocol = __commonJS({ this._onError = (err) => { onError(err); }; - const debug = config.debug; - this._debug = typeof debug === "function" ? (msg) => { - debug(msg); + const debug2 = config.debug; + this._debug = typeof debug2 === "function" ? (msg) => { + debug2(msg); } : void 0; const onHeader = config.onHeader; this._onHeader = typeof onHeader === "function" ? (...args) => { @@ -34951,8 +31981,8 @@ var require_SFTP = __commonJS({ "node_modules/ssh2/lib/protocol/SFTP.js"(exports2, module2) { "use strict"; var EventEmitter = require("events"); - var fs = require("fs"); - var { constants } = fs; + var fs2 = require("fs"); + var { constants: constants3 } = fs2; var { Readable: ReadableStream2, Writable: WritableStream @@ -34964,7 +31994,7 @@ var require_SFTP = __commonJS({ bufferSlice, makeBufferParser, writeUInt32BE - } = require_utils4(); + } = require_utils3(); var ATTR = { SIZE: 1, UIDGID: 2, @@ -35381,12 +32411,12 @@ var require_SFTP = __commonJS({ fastGet(remotePath, localPath, opts, cb) { if (this.server) throw new Error("Client-only method called in server mode"); - fastXfer(this, fs, remotePath, localPath, opts, cb); + fastXfer(this, fs2, remotePath, localPath, opts, cb); } fastPut(localPath, remotePath, opts, cb) { if (this.server) throw new Error("Client-only method called in server mode"); - fastXfer(fs, this, localPath, remotePath, opts, cb); + fastXfer(fs2, this, localPath, remotePath, opts, cb); } readFile(path, options, callback_) { if (this.server) @@ -36010,8 +33040,8 @@ var require_SFTP = __commonJS({ this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); if (this._debug) { - const which = isBuffered ? "Buffered" : "Sending"; - this._debug(`SFTP: Outbound: ${which} posix-rename@openssh.com`); + const which2 = isBuffered ? "Buffered" : "Sending"; + this._debug(`SFTP: Outbound: ${which2} posix-rename@openssh.com`); } } ext_openssh_statvfs(path, cb) { @@ -36034,8 +33064,8 @@ var require_SFTP = __commonJS({ this._requests[reqid] = { extended: "statvfs@openssh.com", cb }; const isBuffered = sendOrBuffer(this, buf); if (this._debug) { - const which = isBuffered ? "Buffered" : "Sending"; - this._debug(`SFTP: Outbound: ${which} statvfs@openssh.com`); + const which2 = isBuffered ? "Buffered" : "Sending"; + this._debug(`SFTP: Outbound: ${which2} statvfs@openssh.com`); } } ext_openssh_fstatvfs(handle, cb) { @@ -36060,8 +33090,8 @@ var require_SFTP = __commonJS({ this._requests[reqid] = { extended: "fstatvfs@openssh.com", cb }; const isBuffered = sendOrBuffer(this, buf); if (this._debug) { - const which = isBuffered ? "Buffered" : "Sending"; - this._debug(`SFTP: Outbound: ${which} fstatvfs@openssh.com`); + const which2 = isBuffered ? "Buffered" : "Sending"; + this._debug(`SFTP: Outbound: ${which2} fstatvfs@openssh.com`); } } ext_openssh_hardlink(oldPath, newPath, cb) { @@ -36087,8 +33117,8 @@ var require_SFTP = __commonJS({ this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); if (this._debug) { - const which = isBuffered ? "Buffered" : "Sending"; - this._debug(`SFTP: Outbound: ${which} hardlink@openssh.com`); + const which2 = isBuffered ? "Buffered" : "Sending"; + this._debug(`SFTP: Outbound: ${which2} hardlink@openssh.com`); } } ext_openssh_fsync(handle, cb) { @@ -36647,13 +33677,13 @@ var require_SFTP = __commonJS({ if (--left === 0) cb(err); }; - if (srcHandle && (src === fs || src.outgoing.state === "open")) + if (srcHandle && (src === fs2 || src.outgoing.state === "open")) ++left; - if (dstHandle && (dst === fs || dst.outgoing.state === "open")) + if (dstHandle && (dst === fs2 || dst.outgoing.state === "open")) ++left; - if (srcHandle && (src === fs || src.outgoing.state === "open")) + if (srcHandle && (src === fs2 || src.outgoing.state === "open")) src.close(srcHandle, cbfinal); - if (dstHandle && (dst === fs || dst.outgoing.state === "open")) + if (dstHandle && (dst === fs2 || dst.outgoing.state === "open")) dst.close(dstHandle, cbfinal); } else { cb(err); @@ -36669,7 +33699,7 @@ var require_SFTP = __commonJS({ tryStat(null, { size: fileSize }); function tryStat(err2, attrs) { if (err2) { - if (src !== fs) { + if (src !== fs2) { src.stat(srcPath, (err_, attrs_) => { if (err_) return onerror(err2); @@ -36807,25 +33837,25 @@ var require_SFTP = __commonJS({ this.extended = initial && initial.extended; } isDirectory() { - return (this.mode & constants.S_IFMT) === constants.S_IFDIR; + return (this.mode & constants3.S_IFMT) === constants3.S_IFDIR; } isFile() { - return (this.mode & constants.S_IFMT) === constants.S_IFREG; + return (this.mode & constants3.S_IFMT) === constants3.S_IFREG; } isBlockDevice() { - return (this.mode & constants.S_IFMT) === constants.S_IFBLK; + return (this.mode & constants3.S_IFMT) === constants3.S_IFBLK; } isCharacterDevice() { - return (this.mode & constants.S_IFMT) === constants.S_IFCHR; + return (this.mode & constants3.S_IFMT) === constants3.S_IFCHR; } isSymbolicLink() { - return (this.mode & constants.S_IFMT) === constants.S_IFLNK; + return (this.mode & constants3.S_IFMT) === constants3.S_IFLNK; } isFIFO() { - return (this.mode & constants.S_IFMT) === constants.S_IFIFO; + return (this.mode & constants3.S_IFMT) === constants3.S_IFIFO; } isSocket() { - return (this.mode & constants.S_IFMT) === constants.S_IFSOCK; + return (this.mode & constants3.S_IFMT) === constants3.S_IFSOCK; } }; function attrsToBytes(attrs) { @@ -37074,8 +34104,8 @@ var require_SFTP = __commonJS({ sftp._requests[reqid] = { extended: "limits@openssh.com", cb }; const isBuffered = sendOrBuffer(sftp, buf); if (sftp._debug) { - const which = isBuffered ? "Buffered" : "Sending"; - sftp._debug(`SFTP: Outbound: ${which} limits@openssh.com`); + const which2 = isBuffered ? "Buffered" : "Sending"; + sftp._debug(`SFTP: Outbound: ${which2} limits@openssh.com`); } } var CLIENT_HANDLERS = { @@ -38012,7 +35042,7 @@ var require_Channel = __commonJS({ var { CHANNEL_EXTENDED_DATATYPE: { STDERR } } = require_constants6(); - var { bufferSlice } = require_utils4(); + var { bufferSlice } = require_utils3(); var PACKET_SIZE = 32 * 1024; var MAX_WINDOW = 2 * 1024 * 1024; var WINDOW_THRESHOLD = MAX_WINDOW / 2; @@ -38237,7 +35267,7 @@ var require_Channel = __commonJS({ }); // node_modules/ssh2/lib/utils.js -var require_utils5 = __commonJS({ +var require_utils4 = __commonJS({ "node_modules/ssh2/lib/utils.js"(exports2, module2) { "use strict"; var { SFTP } = require_SFTP(); @@ -38557,7 +35587,7 @@ var require_client2 = __commonJS({ readUInt32BE, sigSSHToASN1, writeUInt32BE - } = require_utils4(); + } = require_utils3(); var { AgentContext, createAgent, isAgent } = require_agent2(); var { Channel, @@ -38572,7 +35602,7 @@ var require_client2 = __commonJS({ isWritable, onChannelOpenFailure, onCHANNEL_CLOSE - } = require_utils5(); + } = require_utils4(); var bufferParser = makeBufferParser(); var sigParser = makeBufferParser(); var RE_OPENSSH = /^OpenSSH_(?:(?![0-4])\d)|(?:\d{2,})/; @@ -38706,7 +35736,7 @@ var require_client2 = __commonJS({ this.config.allowAgentFwd = cfg.agentForward === true && this.config.agent !== void 0; let authHandler = this.config.authHandler = typeof cfg.authHandler === "function" || Array.isArray(cfg.authHandler) ? cfg.authHandler : void 0; this.config.strictVendor = typeof cfg.strictVendor === "boolean" ? cfg.strictVendor : true; - const debug = this.config.debug = typeof cfg.debug === "function" ? cfg.debug : void 0; + const debug2 = this.config.debug = typeof cfg.debug === "function" ? cfg.debug : void 0; if (cfg.agentForward === true && !this.config.allowAgentFwd) { throw new Error( "You must set a valid agent path to allow agent forwarding" @@ -38754,8 +35784,8 @@ var require_client2 = __commonJS({ let sawHeader = false; if (this._protocol) this._protocol.cleanup(); - const DEBUG_HANDLER = !debug ? void 0 : (p, display, msg) => { - debug(`Debug output from server: ${JSON.stringify(msg)}`); + const DEBUG_HANDLER = !debug2 ? void 0 : (p, display, msg) => { + debug2(`Debug output from server: ${JSON.stringify(msg)}`); }; let serverSigAlgs; const proto = this._protocol = new Protocol({ @@ -38789,7 +35819,7 @@ var require_client2 = __commonJS({ proto.service("ssh-userauth"); } }, - debug, + debug: debug2, hostVerifier, messageHandlers: { DEBUG: DEBUG_HANDLER, @@ -38832,8 +35862,8 @@ var require_client2 = __commonJS({ USERAUTH_FAILURE: (p, authMethods, partialSuccess) => { if (curAuth.keyAlgos) { const oldKeyAlgo = curAuth.keyAlgos[0][0]; - if (debug) - debug(`Client: ${curAuth.type} (${oldKeyAlgo}) auth failed`); + if (debug2) + debug2(`Client: ${curAuth.type} (${oldKeyAlgo}) auth failed`); curAuth.keyAlgos.shift(); if (curAuth.keyAlgos.length) { const [keyAlgo, hashAlgo] = curAuth.keyAlgos[0]; @@ -38874,10 +35904,10 @@ var require_client2 = __commonJS({ } if (curAuth.type === "agent") { const pos = curAuth.agentCtx.pos(); - debug && debug(`Client: Agent key #${pos + 1} failed`); + debug2 && debug2(`Client: Agent key #${pos + 1} failed`); return tryNextAgentKey(); } - debug && debug(`Client: ${curAuth.type} auth failed`); + debug2 && debug2(`Client: ${curAuth.type} auth failed`); curPartial = partialSuccess; curAuthsLeft = authMethods; tryNextAuth(); @@ -38929,7 +35959,7 @@ var require_client2 = __commonJS({ if (curAuth.type === "keyboard-interactive") { const nprompts = Array.isArray(prompts) ? prompts.length : 0; if (nprompts === 0) { - debug && debug( + debug2 && debug2( "Client: Sending automatic USERAUTH_INFO_RESPONSE" ); proto.authInfoRes(); @@ -38994,7 +36024,7 @@ var require_client2 = __commonJS({ state: "open" } }; - const instance = isSFTP ? new SFTP(this, chanInfo, { debug }) : new Channel(this, chanInfo); + const instance = isSFTP ? new SFTP(this, chanInfo, { debug: debug2 }) : new Channel(this, chanInfo); this._chanMgr.update(info2.recipient, instance); channel(void 0, instance); }, @@ -39165,7 +36195,7 @@ var require_client2 = __commonJS({ return; called = true; wasConnected = true; - debug && debug("Socket connected"); + debug2 && debug2("Socket connected"); this.emit("connect"); cryptoInit.then(() => { proto.start(); @@ -39198,19 +36228,19 @@ var require_client2 = __commonJS({ sock.on("connect", onConnect).on("timeout", () => { this.emit("timeout"); }).on("error", (err) => { - debug && debug(`Socket error: ${err.message}`); + debug2 && debug2(`Socket error: ${err.message}`); clearTimeout(this._readyTimeout); err.level = "client-socket"; this.emit("error", err); }).on("end", () => { - debug && debug("Socket ended"); + debug2 && debug2("Socket ended"); onDone(); proto.cleanup(); clearTimeout(this._readyTimeout); clearInterval(katimer); this.emit("end"); }).on("close", () => { - debug && debug("Socket closed"); + debug2 && debug2("Socket closed"); onDone(); proto.cleanup(); clearTimeout(this._readyTimeout); @@ -39444,7 +36474,7 @@ var require_client2 = __commonJS({ } }; function skipAuth(msg) { - debug && debug(msg); + debug2 && debug2(msg); process.nextTick(tryNextAuth); } function tryNextAuth() { @@ -39458,8 +36488,8 @@ var require_client2 = __commonJS({ if (curAuth.type === "agent") { const key = curAuth.agentCtx.nextKey(); if (key === false) { - debug && debug("Agent: No more keys left to try"); - debug && debug("Client: agent auth failed"); + debug2 && debug2("Agent: No more keys left to try"); + debug2 && debug2("Client: agent auth failed"); tryNextAuth(); } else { const pos = curAuth.agentCtx.pos(); @@ -39469,14 +36499,14 @@ var require_client2 = __commonJS({ if (curAuth.keyAlgos.length) { keyAlgo = curAuth.keyAlgos[0][0]; } else { - debug && debug( + debug2 && debug2( `Agent: Skipping key #${pos + 1} (no mutual hash algorithm)` ); tryNextAgentKey(); return; } } - debug && debug(`Agent: Trying key #${pos + 1}`); + debug2 && debug2(`Agent: Trying key #${pos + 1}`); proto.authPK(curAuth.username, key, keyAlgo); } } @@ -39495,7 +36525,7 @@ var require_client2 = __commonJS({ let host = this.config.host; const forceIPv4 = this.config.forceIPv4; const forceIPv6 = this.config.forceIPv6; - debug && debug(`Client: Trying ${host} on port ${this.config.port} ...`); + debug2 && debug2(`Client: Trying ${host} on port ${this.config.port} ...`); const doConnect = () => { startTimeout(); sock.connect({ @@ -40424,7 +37454,7 @@ var require_server = __commonJS({ var { parseKey } = require_keyParser(); var Protocol = require_Protocol(); var { SFTP } = require_SFTP(); - var { writeUInt32BE } = require_utils4(); + var { writeUInt32BE } = require_utils3(); var { Channel, MAX_WINDOW, @@ -40438,7 +37468,7 @@ var require_server = __commonJS({ isWritable, onChannelOpenFailure, onCHANNEL_CLOSE - } = require_utils5(); + } = require_utils4(); var MAX_PENDING_AUTHS = 10; var AuthContext = class extends EventEmitter { constructor(protocol, username, service, method, cb) { @@ -40681,14 +37711,14 @@ var require_server = __commonJS({ socket.once("close", () => { --this._connections; }); - let debug; + let debug2; if (origDebug) { const debugPrefix = `[${process.hrtime().join(".")}] `; - debug = (msg) => { + debug2 = (msg) => { origDebug(`${debugPrefix}${msg}`); }; } - new Client(socket, hostKeys, ident, offer, debug, this, cfg); + new Client(socket, hostKeys, ident, offer, debug2, this, cfg); }).on("error", (err) => { this.emit("error", err); }).on("listening", () => { @@ -40729,7 +37759,7 @@ var require_server = __commonJS({ Server.KEEPALIVE_CLIENT_INTERVAL = 15e3; Server.KEEPALIVE_CLIENT_COUNT_MAX = 3; var Client = class extends EventEmitter { - constructor(socket, hostKeys, ident, offer, debug, server, srvCfg) { + constructor(socket, hostKeys, ident, offer, debug2, server, srvCfg) { super(); let exchanges = 0; let acceptedAuthSvc = false; @@ -40740,14 +37770,14 @@ var require_server = __commonJS({ const unsentGlobalRequestsReplies = []; this._sock = socket; this._chanMgr = new ChannelManager(this); - this._debug = debug; + this._debug = debug2; this.noMoreSessions = false; this.authenticated = false; function onClientPreHeaderError(err) { } this.on("error", onClientPreHeaderError); - const DEBUG_HANDLER = !debug ? void 0 : (p, display, msg) => { - debug(`Debug output from client: ${JSON.stringify(msg)}`); + const DEBUG_HANDLER = !debug2 ? void 0 : (p, display, msg) => { + debug2(`Debug output from client: ${JSON.stringify(msg)}`); }; const kaIntvl = typeof srvCfg.keepaliveInterval === "number" && isFinite(srvCfg.keepaliveInterval) && srvCfg.keepaliveInterval > 0 ? srvCfg.keepaliveInterval : typeof Server.KEEPALIVE_CLIENT_INTERVAL === "number" && isFinite(Server.KEEPALIVE_CLIENT_INTERVAL) && Server.KEEPALIVE_CLIENT_INTERVAL > 0 ? Server.KEEPALIVE_CLIENT_INTERVAL : -1; const kaCountMax = typeof srvCfg.keepaliveCountMax === "number" && isFinite(srvCfg.keepaliveCountMax) && srvCfg.keepaliveCountMax >= 0 ? srvCfg.keepaliveCountMax : typeof Server.KEEPALIVE_CLIENT_COUNT_MAX === "number" && isFinite(Server.KEEPALIVE_CLIENT_COUNT_MAX) && Server.KEEPALIVE_CLIENT_COUNT_MAX >= 0 ? Server.KEEPALIVE_CLIENT_COUNT_MAX : -1; @@ -40817,7 +37847,7 @@ var require_server = __commonJS({ this.emit("rekey"); this.emit("handshake", negotiated); }, - debug, + debug: debug2, messageHandlers: { DEBUG: DEBUG_HANDLER, DISCONNECT: (p, reason, desc) => { @@ -40860,8 +37890,8 @@ var require_server = __commonJS({ localChan = this._chanMgr.add(); if (localChan === -1) { reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; - if (debug) { - debug("Automatic rejection of incoming channel open: no channels available"); + if (debug2) { + debug2("Automatic rejection of incoming channel open: no channels available"); } } return localChan !== -1; @@ -40960,14 +37990,14 @@ var require_server = __commonJS({ break; default: reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE; - if (debug) { - debug(`Automatic rejection of unsupported incoming channel open type: ${info2.type}`); + if (debug2) { + debug2(`Automatic rejection of unsupported incoming channel open type: ${info2.type}`); } } if (reason === void 0) { reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; - if (debug) { - debug(`Automatic rejection of unexpected incoming channel open for: ${info2.type}`); + if (debug2) { + debug2(`Automatic rejection of unexpected incoming channel open for: ${info2.type}`); } } reject(); @@ -41209,7 +38239,7 @@ var require_server = __commonJS({ if (useSFTP) { instance = new SFTP(this, session._chanInfo, { server: true, - debug + debug: debug2 }); } else { instance = new Channel( @@ -41238,7 +38268,7 @@ var require_server = __commonJS({ break; } } - debug && debug( + debug2 && debug2( `Automatic rejection of incoming channel request: ${type}` ); reject && reject(); @@ -41448,11 +38478,11 @@ var require_server = __commonJS({ err.level = "socket"; this.emit("error", err); }).once("end", () => { - debug && debug("Socket ended"); + debug2 && debug2("Socket ended"); proto.cleanup(); this.emit("end"); }).once("close", () => { - debug && debug("Socket closed"); + debug2 && debug2("Socket closed"); proto.cleanup(); this.emit("close"); const err = new Error("No response from server"); @@ -41584,7 +38614,7 @@ var require_keygen = __commonJS({ getCurves, randomBytes } = require("crypto"); - var { Ber } = require_lib2(); + var { Ber } = require_lib(); var bcrypt_pbkdf = require_bcrypt_pbkdf().pbkdf; var { CIPHER_INFO } = require_crypto(); var SALT_LEN = 16; @@ -41996,7 +39026,7 @@ var require_keygen = __commonJS({ }); // node_modules/ssh2/lib/index.js -var require_lib4 = __commonJS({ +var require_lib3 = __commonJS({ "node_modules/ssh2/lib/index.js"(exports2, module2) { "use strict"; var { @@ -42046,7 +39076,7 @@ var require_lib4 = __commonJS({ // node_modules/docker-modem/lib/ssh.js var require_ssh = __commonJS({ "node_modules/docker-modem/lib/ssh.js"(exports2, module2) { - var Client = require_lib4().Client; + var Client = require_lib3().Client; var http = require("http"); module2.exports = function(opt) { var conn = new Client(); @@ -43852,11 +40882,11 @@ var require_stream_readable = __commonJS({ return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array; } var debugUtil = require("util"); - var debug; + var debug2; if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog("stream"); + debug2 = debugUtil.debuglog("stream"); } else { - debug = function debug2() { + debug2 = function debug3() { }; } var BufferList = require_buffer_list(); @@ -43971,7 +41001,7 @@ var require_stream_readable = __commonJS({ return readableAddChunk(this, chunk, null, true, false); }; function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug("readableAddChunk", chunk); + debug2("readableAddChunk", chunk); var state = stream._readableState; if (chunk === null) { state.reading = false; @@ -44078,13 +41108,13 @@ var require_stream_readable = __commonJS({ return state.length; } Readable.prototype.read = function(n) { - debug("read", n); + debug2("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); + debug2("read: emitReadable", state.length, state.ended); if (state.length === 0 && state.ended) endReadable(this); else emitReadable(this); return null; @@ -44095,16 +41125,16 @@ var require_stream_readable = __commonJS({ return null; } var doRead = state.needReadable; - debug("need readable", doRead); + debug2("need readable", doRead); if (state.length === 0 || state.length - n < state.highWaterMark) { doRead = true; - debug("length less than watermark", doRead); + debug2("length less than watermark", doRead); } if (state.ended || state.reading) { doRead = false; - debug("reading or ended", doRead); + debug2("reading or ended", doRead); } else if (doRead) { - debug("do read"); + debug2("do read"); state.reading = true; state.sync = true; if (state.length === 0) state.needReadable = true; @@ -44130,7 +41160,7 @@ var require_stream_readable = __commonJS({ return ret; }; function onEofChunk(stream, state) { - debug("onEofChunk"); + debug2("onEofChunk"); if (state.ended) return; if (state.decoder) { var chunk = state.decoder.end(); @@ -44152,17 +41182,17 @@ var require_stream_readable = __commonJS({ } function emitReadable(stream) { var state = stream._readableState; - debug("emitReadable", state.needReadable, state.emittedReadable); + debug2("emitReadable", state.needReadable, state.emittedReadable); state.needReadable = false; if (!state.emittedReadable) { - debug("emitReadable", state.flowing); + debug2("emitReadable", state.flowing); state.emittedReadable = true; process.nextTick(emitReadable_, stream); } } function emitReadable_(stream) { var state = stream._readableState; - debug("emitReadable_", state.destroyed, state.length, state.ended); + debug2("emitReadable_", state.destroyed, state.length, state.ended); if (!state.destroyed && (state.length || state.ended)) { stream.emit("readable"); state.emittedReadable = false; @@ -44179,7 +41209,7 @@ var require_stream_readable = __commonJS({ function maybeReadMore_(stream, state) { while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { var len = state.length; - debug("maybeReadMore read 0"); + debug2("maybeReadMore read 0"); stream.read(0); if (len === state.length) break; @@ -44204,14 +41234,14 @@ var require_stream_readable = __commonJS({ break; } state.pipesCount += 1; - debug("pipe count=%d opts=%j", state.pipesCount, pipeOpts); + debug2("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"); + debug2("onunpipe"); if (readable === src) { if (unpipeInfo && unpipeInfo.hasUnpiped === false) { unpipeInfo.hasUnpiped = true; @@ -44220,14 +41250,14 @@ var require_stream_readable = __commonJS({ } } function onend() { - debug("onend"); + debug2("onend"); dest.end(); } var ondrain = pipeOnDrain(src); dest.on("drain", ondrain); var cleanedUp = false; function cleanup() { - debug("cleanup"); + debug2("cleanup"); dest.removeListener("close", onclose); dest.removeListener("finish", onfinish); dest.removeListener("drain", ondrain); @@ -44241,19 +41271,19 @@ var require_stream_readable = __commonJS({ } src.on("data", ondata); function ondata(chunk) { - debug("ondata"); + debug2("ondata"); var ret = dest.write(chunk); - debug("dest.write", ret); + debug2("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); + debug2("false write response, pause", state.awaitDrain); state.awaitDrain++; } src.pause(); } } function onerror(er) { - debug("onerror", er); + debug2("onerror", er); unpipe(); dest.removeListener("error", onerror); if (EElistenerCount(dest, "error") === 0) errorOrDestroy(dest, er); @@ -44265,18 +41295,18 @@ var require_stream_readable = __commonJS({ } dest.once("close", onclose); function onfinish() { - debug("onfinish"); + debug2("onfinish"); dest.removeListener("close", onclose); unpipe(); } dest.once("finish", onfinish); function unpipe() { - debug("unpipe"); + debug2("unpipe"); src.unpipe(dest); } dest.emit("pipe", src); if (!state.flowing) { - debug("pipe resume"); + debug2("pipe resume"); src.resume(); } return dest; @@ -44284,7 +41314,7 @@ var require_stream_readable = __commonJS({ function pipeOnDrain(src) { return function pipeOnDrainFunctionResult() { var state = src._readableState; - debug("pipeOnDrain", state.awaitDrain); + debug2("pipeOnDrain", state.awaitDrain); if (state.awaitDrain) state.awaitDrain--; if (state.awaitDrain === 0 && EElistenerCount(src, "data")) { state.flowing = true; @@ -44339,7 +41369,7 @@ var require_stream_readable = __commonJS({ state.readableListening = state.needReadable = true; state.flowing = false; state.emittedReadable = false; - debug("on readable", state.length, state.reading); + debug2("on readable", state.length, state.reading); if (state.length) { emitReadable(this); } else if (!state.reading) { @@ -44374,13 +41404,13 @@ var require_stream_readable = __commonJS({ } } function nReadingNextTick(self2) { - debug("readable nexttick read 0"); + debug2("readable nexttick read 0"); self2.read(0); } Readable.prototype.resume = function() { var state = this._readableState; if (!state.flowing) { - debug("resume"); + debug2("resume"); state.flowing = !state.readableListening; resume(this, state); } @@ -44394,7 +41424,7 @@ var require_stream_readable = __commonJS({ } } function resume_(stream, state) { - debug("resume", state.reading); + debug2("resume", state.reading); if (!state.reading) { stream.read(0); } @@ -44404,9 +41434,9 @@ var require_stream_readable = __commonJS({ if (state.flowing && !state.reading) stream.read(0); } Readable.prototype.pause = function() { - debug("call pause flowing=%j", this._readableState.flowing); + debug2("call pause flowing=%j", this._readableState.flowing); if (this._readableState.flowing !== false) { - debug("pause"); + debug2("pause"); this._readableState.flowing = false; this.emit("pause"); } @@ -44415,7 +41445,7 @@ var require_stream_readable = __commonJS({ }; function flow(stream) { var state = stream._readableState; - debug("flow", state.flowing); + debug2("flow", state.flowing); while (state.flowing && stream.read() !== null) { ; } @@ -44425,7 +41455,7 @@ var require_stream_readable = __commonJS({ var state = this._readableState; var paused = false; stream.on("end", function() { - debug("wrapped end"); + debug2("wrapped end"); if (state.decoder && !state.ended) { var chunk = state.decoder.end(); if (chunk && chunk.length) _this.push(chunk); @@ -44433,7 +41463,7 @@ var require_stream_readable = __commonJS({ _this.push(null); }); stream.on("data", function(chunk) { - debug("wrapped data"); + debug2("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; @@ -44456,7 +41486,7 @@ var require_stream_readable = __commonJS({ stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); } this._read = function(n2) { - debug("wrapped _read", n2); + debug2("wrapped _read", n2); if (paused) { paused = false; stream.resume(); @@ -44530,14 +41560,14 @@ var require_stream_readable = __commonJS({ } function endReadable(stream) { var state = stream._readableState; - debug("endReadable", state.endEmitted); + debug2("endReadable", state.endEmitted); if (!state.endEmitted) { state.ended = true; process.nextTick(endReadableNT, state, stream); } } function endReadableNT(state, stream) { - debug("endReadableNT", state.endEmitted, state.length); + debug2("endReadableNT", state.endEmitted, state.length); if (!state.endEmitted && state.length === 0) { state.endEmitted = true; stream.readable = false; @@ -44988,11 +42018,11 @@ var require_common = __commonJS({ let enableOverride = null; let namespacesCache; let enabledCache; - function debug(...args) { - if (!debug.enabled) { + function debug2(...args) { + if (!debug2.enabled) { return; } - const self2 = debug; + const self2 = debug2; const curr = Number(/* @__PURE__ */ new Date()); const ms = curr - (prevTime || curr); self2.diff = ms; @@ -45022,12 +42052,12 @@ var require_common = __commonJS({ const logFn = self2.log || createDebug.log; logFn.apply(self2, args); } - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend; - debug.destroy = createDebug.destroy; - Object.defineProperty(debug, "enabled", { + debug2.namespace = namespace; + debug2.useColors = createDebug.useColors(); + debug2.color = createDebug.selectColor(namespace); + debug2.extend = extend; + debug2.destroy = createDebug.destroy; + Object.defineProperty(debug2, "enabled", { enumerable: true, configurable: false, get: () => { @@ -45045,9 +42075,9 @@ var require_common = __commonJS({ } }); if (typeof createDebug.init === "function") { - createDebug.init(debug); + createDebug.init(debug2); } - return debug; + return debug2; } function extend(namespace, delimiter) { const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); @@ -45320,7 +42350,7 @@ var require_has_flag = __commonJS({ var require_supports_color = __commonJS({ "node_modules/supports-color/index.js"(exports2, module2) { "use strict"; - var os = require("os"); + var os4 = require("os"); var tty = require("tty"); var hasFlag = require_has_flag(); var { env } = process; @@ -45368,7 +42398,7 @@ var require_supports_color = __commonJS({ return min; } if (process.platform === "win32") { - const osRelease = os.release().split("."); + const osRelease = os4.release().split("."); if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { return Number(osRelease[2]) >= 14931 ? 3 : 2; } @@ -45572,11 +42602,11 @@ var require_node2 = __commonJS({ function load() { return process.env.DEBUG; } - function init(debug) { - debug.inspectOpts = {}; + function init(debug2) { + debug2.inspectOpts = {}; const keys = Object.keys(exports2.inspectOpts); for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]]; + debug2.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]]; } } module2.exports = require_common()(exports2); @@ -45606,12 +42636,12 @@ var require_src = __commonJS({ // node_modules/split-ca/index.js var require_split_ca = __commonJS({ "node_modules/split-ca/index.js"(exports2, module2) { - var fs = require("fs"); + var fs2 = require("fs"); module2.exports = function(filepath, split, encoding) { split = typeof split !== "undefined" ? split : "\n"; encoding = typeof encoding !== "undefined" ? encoding : "utf8"; var ca = []; - var chain = fs.readFileSync(filepath, encoding); + var chain = fs2.readFileSync(filepath, encoding); if (chain.indexOf("-END CERTIFICATE-") < 0 || chain.indexOf("-BEGIN CERTIFICATE-") < 0) { throw Error("File does not contain 'BEGIN CERTIFICATE' or 'END CERTIFICATE'"); } @@ -45639,17 +42669,17 @@ var require_modem = __commonJS({ "node_modules/docker-modem/lib/modem.js"(exports2, module2) { var querystring = require("querystring"); var http = require_http(); - var fs = require("fs"); + var fs2 = require("fs"); var path = require("path"); var url = require("url"); var ssh = require_ssh(); var HttpDuplex = require_http_duplex(); - var debug = require_src()("modem"); - var utils = require_utils3(); + var debug2 = require_src()("modem"); + var utils = require_utils2(); var util = require("util"); var splitca = require_split_ca(); - var os = require("os"); - var isWin = os.type() === "Windows_NT"; + var os4 = require("os"); + var isWin = os4.type() === "Windows_NT"; var stream = require("stream"); var defaultOpts = function() { var host; @@ -45690,8 +42720,8 @@ var require_modem = __commonJS({ opts.host = host.hostname; if (process.env.DOCKER_CERT_PATH) { opts.ca = splitca(path.join(process.env.DOCKER_CERT_PATH, "ca.pem")); - opts.cert = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, "cert.pem")); - opts.key = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, "key.pem")); + opts.cert = fs2.readFileSync(path.join(process.env.DOCKER_CERT_PATH, "cert.pem")); + opts.key = fs2.readFileSync(path.join(process.env.DOCKER_CERT_PATH, "key.pem")); } if (process.env.DOCKER_CLIENT_TIMEOUT) { opts.timeout = parseInt(process.env.DOCKER_CLIENT_TIMEOUT, 10); @@ -45701,8 +42731,8 @@ var require_modem = __commonJS({ }; var findDefaultUnixSocket = function() { return new Promise(function(resolve) { - var userDockerSocket = path.join(os.homedir(), ".docker", "run", "docker.sock"); - fs.access(userDockerSocket, function(err) { + var userDockerSocket = path.join(os4.homedir(), ".docker", "run", "docker.sock"); + fs2.access(userDockerSocket, function(err) { if (err) resolve("/var/run/docker.sock"); else resolve(userDockerSocket); }); @@ -45795,7 +42825,7 @@ var require_modem = __commonJS({ } if (options.file) { if (typeof options.file === "string") { - data = fs.createReadStream(path.resolve(options.file)); + data = fs2.createReadStream(path.resolve(options.file)); } else { data = options.file; } @@ -45864,20 +42894,20 @@ var require_modem = __commonJS({ callback(e); return; } - debug("Sending: %s", util.inspect(options, { + debug2("Sending: %s", util.inspect(options, { showHidden: true, depth: null })); if (self2.connectionTimeout) { connectionTimeoutTimer = setTimeout(function() { - debug("Connection Timeout of %s ms exceeded", self2.connectionTimeout); + debug2("Connection Timeout of %s ms exceeded", self2.connectionTimeout); req.destroy(); }, self2.connectionTimeout); } if (self2.timeout) { req.setTimeout(self2.timeout); req.on("timeout", function() { - debug("Timeout of %s ms exceeded", self2.timeout); + debug2("Timeout of %s ms exceeded", self2.timeout); req.destroy(); }); } @@ -45917,7 +42947,7 @@ var require_modem = __commonJS({ res.on("end", function() { var buffer = Buffer.concat(chunks); var result = buffer.toString(); - debug("Received: %s", result); + debug2("Received: %s", result); var json = utils.parseJSON(result) || buffer; if (finished === false) { finished = true; @@ -46327,14 +43357,14 @@ var require_ignore = __commonJS({ var require_chownr = __commonJS({ "node_modules/chownr/chownr.js"(exports2, module2) { "use strict"; - var fs = require("fs"); + var fs2 = require("fs"); var path = require("path"); - var LCHOWN = fs.lchown ? "lchown" : "chown"; - var LCHOWNSYNC = fs.lchownSync ? "lchownSync" : "chownSync"; - var needEISDIRHandled = fs.lchown && !process.version.match(/v1[1-9]+\./) && !process.version.match(/v10\.[6-9]/); + var LCHOWN = fs2.lchown ? "lchown" : "chown"; + var LCHOWNSYNC = fs2.lchownSync ? "lchownSync" : "chownSync"; + var needEISDIRHandled = fs2.lchown && !process.version.match(/v1[1-9]+\./) && !process.version.match(/v10\.[6-9]/); var lchownSync = (path2, uid, gid) => { try { - return fs[LCHOWNSYNC](path2, uid, gid); + return fs2[LCHOWNSYNC](path2, uid, gid); } catch (er) { if (er.code !== "ENOENT") throw er; @@ -46342,7 +43372,7 @@ var require_chownr = __commonJS({ }; var chownSync = (path2, uid, gid) => { try { - return fs.chownSync(path2, uid, gid); + return fs2.chownSync(path2, uid, gid); } catch (er) { if (er.code !== "ENOENT") throw er; @@ -46352,7 +43382,7 @@ var require_chownr = __commonJS({ if (!er || er.code !== "EISDIR") cb(er); else - fs.chown(path2, uid, gid, cb); + fs2.chown(path2, uid, gid, cb); } : (_, __, ___, cb) => cb; var handleEISDirSync = needEISDIRHandled ? (path2, uid, gid) => { try { @@ -46364,18 +43394,18 @@ var require_chownr = __commonJS({ } } : (path2, uid, gid) => lchownSync(path2, uid, gid); var nodeVersion = process.version; - var readdir = (path2, options, cb) => fs.readdir(path2, options, cb); - var readdirSync = (path2, options) => fs.readdirSync(path2, options); + var readdir2 = (path2, options, cb) => fs2.readdir(path2, options, cb); + var readdirSync = (path2, options) => fs2.readdirSync(path2, options); if (/^v4\./.test(nodeVersion)) - readdir = (path2, options, cb) => fs.readdir(path2, cb); + readdir2 = (path2, options, cb) => fs2.readdir(path2, cb); var chown = (cpath, uid, gid, cb) => { - fs[LCHOWN](cpath, uid, gid, handleEISDIR(cpath, uid, gid, (er) => { + fs2[LCHOWN](cpath, uid, gid, handleEISDIR(cpath, uid, gid, (er) => { cb(er && er.code !== "ENOENT" ? er : null); })); }; var chownrKid = (p, child, uid, gid, cb) => { if (typeof child === "string") - return fs.lstat(path.resolve(p, child), (er, stats) => { + return fs2.lstat(path.resolve(p, child), (er, stats) => { if (er) return cb(er.code !== "ENOENT" ? er : null); stats.name = child; @@ -46394,7 +43424,7 @@ var require_chownr = __commonJS({ } }; var chownr = (p, uid, gid, cb) => { - readdir(p, { withFileTypes: true }, (er, children) => { + readdir2(p, { withFileTypes: true }, (er, children) => { if (er) { if (er.code === "ENOENT") return cb(); @@ -46419,7 +43449,7 @@ var require_chownr = __commonJS({ var chownrKidSync = (p, child, uid, gid) => { if (typeof child === "string") { try { - const stats = fs.lstatSync(path.resolve(p, child)); + const stats = fs2.lstatSync(path.resolve(p, child)); stats.name = child; child = stats; } catch (er) { @@ -47449,7 +44479,7 @@ var require_end_of_stream2 = __commonJS({ // node_modules/tar-fs/node_modules/tar-stream/pack.js var require_pack = __commonJS({ "node_modules/tar-fs/node_modules/tar-stream/pack.js"(exports2, module2) { - var constants = require_fs_constants(); + var constants3 = require_fs_constants(); var eos = require_end_of_stream2(); var inherits = require_inherits(); var alloc = Buffer.alloc; @@ -47467,16 +44497,16 @@ var require_pack = __commonJS({ if (size) self2.push(END_OF_TAR.slice(0, 512 - size)); }; function modeToType(mode) { - switch (mode & constants.S_IFMT) { - case constants.S_IFBLK: + switch (mode & constants3.S_IFMT) { + case constants3.S_IFBLK: return "block-device"; - case constants.S_IFCHR: + case constants3.S_IFCHR: return "character-device"; - case constants.S_IFDIR: + case constants3.S_IFDIR: return "directory"; - case constants.S_IFIFO: + case constants3.S_IFIFO: return "fifo"; - case constants.S_IFLNK: + case constants3.S_IFLNK: return "symlink"; } return "file"; @@ -47674,9 +44704,9 @@ var require_pump = __commonJS({ "node_modules/pump/index.js"(exports2, module2) { var once = require_once(); var eos = require_end_of_stream2(); - var fs; + var fs2; try { - fs = require("fs"); + fs2 = require("fs"); } catch (e) { } var noop = function() { @@ -47687,8 +44717,8 @@ var require_pump = __commonJS({ }; var isFS = function(stream) { if (!ancient) return false; - if (!fs) return false; - return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close); + if (!fs2) return false; + return (stream instanceof (fs2.ReadStream || noop) || stream instanceof (fs2.WriteStream || noop)) && isFn(stream.close); }; var isRequest = function(stream) { return stream.setHeader && isFn(stream.abort); @@ -47748,7 +44778,7 @@ var require_pump = __commonJS({ var require_mkdirp_classic = __commonJS({ "node_modules/mkdirp-classic/index.js"(exports2, module2) { var path = require("path"); - var fs = require("fs"); + var fs2 = require("fs"); var _0777 = parseInt("0777", 8); module2.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; function mkdirP(p, opts, f, made) { @@ -47759,7 +44789,7 @@ var require_mkdirp_classic = __commonJS({ opts = { mode: opts }; } var mode = opts.mode; - var xfs = opts.fs || fs; + var xfs = opts.fs || fs2; if (mode === void 0) { mode = _0777 & ~process.umask(); } @@ -47783,8 +44813,8 @@ var require_mkdirp_classic = __commonJS({ // there already. If so, then hooray! If not, then something // is borked. default: - xfs.stat(p, function(er2, stat) { - if (er2 || !stat.isDirectory()) cb(er, made); + xfs.stat(p, function(er2, stat2) { + if (er2 || !stat2.isDirectory()) cb(er, made); else cb(null, made); }); break; @@ -47796,7 +44826,7 @@ var require_mkdirp_classic = __commonJS({ opts = { mode: opts }; } var mode = opts.mode; - var xfs = opts.fs || fs; + var xfs = opts.fs || fs2; if (mode === void 0) { mode = _0777 & ~process.umask(); } @@ -47815,13 +44845,13 @@ var require_mkdirp_classic = __commonJS({ // there already. If so, then hooray! If not, then something // is borked. default: - var stat; + var stat2; try { - stat = xfs.statSync(p); + stat2 = xfs.statSync(p); } catch (err1) { throw err0; } - if (!stat.isDirectory()) throw err0; + if (!stat2.isDirectory()) throw err0; break; } } @@ -47837,10 +44867,10 @@ var require_tar_fs = __commonJS({ var tar = require_tar_stream(); var pump = require_pump(); var mkdirp = require_mkdirp_classic(); - var fs = require("fs"); + var fs2 = require("fs"); var path = require("path"); - var os = require("os"); - var win32 = os.platform() === "win32"; + var os4 = require("os"); + var win32 = os4.platform() === "win32"; var noop = function() { }; var echo = function(name) { @@ -47849,22 +44879,22 @@ var require_tar_fs = __commonJS({ var normalize = !win32 ? echo : function(name) { return name.replace(/\\/g, "/").replace(/[:?<>|]/g, "_"); }; - var statAll = function(fs2, stat, cwd, ignore, entries, sort) { + var statAll = function(fs3, stat2, cwd, ignore, entries, sort) { var queue = entries || ["."]; return function loop(callback) { if (!queue.length) return callback(); var next = queue.shift(); var nextAbs = path.join(cwd, next); - stat.call(fs2, nextAbs, function(err, stat2) { + stat2.call(fs3, nextAbs, function(err, stat3) { if (err) return callback(err); - if (!stat2.isDirectory()) return callback(null, next, stat2); - fs2.readdir(nextAbs, function(err2, files) { + if (!stat3.isDirectory()) return callback(null, next, stat3); + fs3.readdir(nextAbs, function(err2, files) { if (err2) return callback(err2); if (sort) files.sort(); for (var i = 0; i < files.length; i++) { if (!ignore(path.join(cwd, next, files[i]))) queue.push(path.join(next, files[i])); } - callback(null, next, stat2); + callback(null, next, stat3); }); }); }; @@ -47882,7 +44912,7 @@ var require_tar_fs = __commonJS({ exports2.pack = function(cwd, opts) { if (!cwd) cwd = "."; if (!opts) opts = {}; - var xfs = opts.fs || fs; + var xfs = opts.fs || fs2; var ignore = opts.ignore || opts.filter || noop; var map = opts.map || noop; var mapStream = opts.mapStream || echo; @@ -47909,36 +44939,36 @@ var require_tar_fs = __commonJS({ pack.entry(header, onnextentry); }); }; - var onstat = function(err, filename, stat) { + var onstat = function(err, filename, stat2) { if (err) return pack.destroy(err); if (!filename) { if (opts.finalize !== false) pack.finalize(); return finish(pack); } - if (stat.isSocket()) return onnextentry(); + if (stat2.isSocket()) return onnextentry(); var header = { name: normalize(filename), - mode: (stat.mode | (stat.isDirectory() ? dmode : fmode)) & umask, - mtime: stat.mtime, - size: stat.size, + mode: (stat2.mode | (stat2.isDirectory() ? dmode : fmode)) & umask, + mtime: stat2.mtime, + size: stat2.size, type: "file", - uid: stat.uid, - gid: stat.gid + uid: stat2.uid, + gid: stat2.gid }; - if (stat.isDirectory()) { + if (stat2.isDirectory()) { header.size = 0; header.type = "directory"; header = map(header) || header; return pack.entry(header, onnextentry); } - if (stat.isSymbolicLink()) { + if (stat2.isSymbolicLink()) { header.size = 0; header.type = "symlink"; header = map(header) || header; return onsymlink(filename, header); } header = map(header) || header; - if (!stat.isFile()) { + if (!stat2.isFile()) { if (strict) return pack.destroy(new Error("unsupported type for " + filename)); return onnextentry(); } @@ -47969,7 +44999,7 @@ var require_tar_fs = __commonJS({ exports2.extract = function(cwd, opts) { if (!cwd) cwd = "."; if (!opts) opts = {}; - var xfs = opts.fs || fs; + var xfs = opts.fs || fs2; var ignore = opts.ignore || opts.filter || noop; var map = opts.map || noop; var mapStream = opts.mapStream || echo; @@ -48007,16 +45037,16 @@ var require_tar_fs = __commonJS({ }; var chperm = function(name, header, cb) { var link = header.type === "symlink"; - var chmod = link ? xfs.lchmod : xfs.chmod; + var chmod2 = link ? xfs.lchmod : xfs.chmod; var chown = link ? xfs.lchown : xfs.chown; - if (!chmod) return cb(); + if (!chmod2) return cb(); var mode = (header.mode | (header.type === "directory" ? dmode : fmode)) & umask; if (chown && own) chown.call(xfs, name, header.uid, header.gid, onchown); else onchown(null); function onchown(err) { if (err) return cb(err); - if (!chmod) return cb(); - chmod.call(xfs, name, mode, cb); + if (!chmod2) return cb(); + chmod2.call(xfs, name, mode, cb); } }; extract.on("entry", function(header, stream, next) { @@ -48027,7 +45057,7 @@ var require_tar_fs = __commonJS({ stream.resume(); return next(); } - var stat = function(err) { + var stat2 = function(err) { if (err) return next(err); utimes(name, header, function(err2) { if (err2) return next(err2); @@ -48040,7 +45070,7 @@ var require_tar_fs = __commonJS({ xfs.unlink(name, function() { var dst = path.resolve(path.dirname(name), header.linkname); if (!inCwd(dst, cwd)) return next(new Error(name + " is not a valid symlink")); - xfs.symlink(header.linkname, name, stat); + xfs.symlink(header.linkname, name, stat2); }); }; var onlink = function() { @@ -48054,7 +45084,7 @@ var require_tar_fs = __commonJS({ stream = xfs.createReadStream(srcpath); return onfile(); } - stat(err2); + stat2(err2); }); }); }); @@ -48067,7 +45097,7 @@ var require_tar_fs = __commonJS({ }); pump(rs, ws, function(err) { if (err) return next(err); - ws.on("close", stat); + ws.on("close", stat2); }); }; if (header.type === "directory") { @@ -48077,7 +45107,7 @@ var require_tar_fs = __commonJS({ own, uid: header.uid, gid: header.gid - }, stat); + }, stat2); } var dir = path.dirname(name); validate(xfs, dir, path.join(cwd, "."), function(err, valid) { @@ -48107,11 +45137,11 @@ var require_tar_fs = __commonJS({ if (opts.finish) extract.on("finish", opts.finish); return extract; }; - function validate(fs2, name, root, cb) { + function validate(fs3, name, root, cb) { if (name === root) return cb(null, true); - fs2.lstat(name, function(err, st) { + fs3.lstat(name, function(err, st) { if (err && err.code !== "ENOENT") return cb(err); - if (err || st.isDirectory()) return validate(fs2, path.join(name, ".."), root, cb); + if (err || st.isDirectory()) return validate(fs3, path.join(name, ".."), root, cb); cb(null, false); }); } @@ -48135,7 +45165,7 @@ var require_tar_fs = __commonJS({ var require_util9 = __commonJS({ "node_modules/dockerode/lib/util.js"(exports2, module2) { var DockerIgnore = require_ignore(); - var fs = require("fs"); + var fs2 = require("fs"); var path = require("path"); var tar = require_tar_fs(); var zlib = require("zlib"); @@ -48188,7 +45218,7 @@ var require_util9 = __commonJS({ }; module2.exports.prepareBuildContext = function(file, next) { if (file && file.context) { - fs.readFile(path.join(file.context, ".dockerignore"), (err, data) => { + fs2.readFile(path.join(file.context, ".dockerignore"), (err, data) => { let ignoreFn; let filterFn; if (!err) { @@ -48214,7 +45244,7 @@ var require_util9 = __commonJS({ }); // node_modules/dockerode/lib/exec.js -var require_exec2 = __commonJS({ +var require_exec = __commonJS({ "node_modules/dockerode/lib/exec.js"(exports2, module2) { var util = require_util9(); var Exec = function(modem, id) { @@ -48327,7 +45357,7 @@ var require_exec2 = __commonJS({ var require_container = __commonJS({ "node_modules/dockerode/lib/container.js"(exports2, module2) { var extend = require_util9().extend; - var Exec = require_exec2(); + var Exec = require_exec(); var util = require_util9(); var Container = function(modem, id) { this.modem = modem; @@ -51105,14 +48135,14 @@ var require_tls_helpers = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.CIPHER_SUITES = void 0; exports2.getDefaultRootsData = getDefaultRootsData; - var fs = require("fs"); + var fs2 = require("fs"); exports2.CIPHER_SUITES = process.env.GRPC_SSL_CIPHER_SUITES; var DEFAULT_ROOTS_FILE_PATH = process.env.GRPC_DEFAULT_SSL_ROOTS_FILE_PATH; var defaultRootsData = null; function getDefaultRootsData() { if (DEFAULT_ROOTS_FILE_PATH) { if (defaultRootsData === null) { - defaultRootsData = fs.readFileSync(DEFAULT_ROOTS_FILE_PATH); + defaultRootsData = fs2.readFileSync(DEFAULT_ROOTS_FILE_PATH); } return defaultRootsData; } @@ -51762,7 +48792,7 @@ var require_service_config = __commonJS({ exports2.validateRetryThrottling = validateRetryThrottling; exports2.validateServiceConfig = validateServiceConfig; exports2.extractAndSelectServiceConfig = extractAndSelectServiceConfig; - var os = require("os"); + var os4 = require("os"); var constants_1 = require_constants7(); var DURATION_REGEX = /^\d+(\.\d{1,9})?s$/; var CLIENT_LANGUAGE_STRING = "node"; @@ -52061,7 +49091,7 @@ var require_service_config = __commonJS({ if (Array.isArray(validatedConfig.clientHostname)) { let hostnameMatched = false; for (const hostname of validatedConfig.clientHostname) { - if (hostname === os.hostname()) { + if (hostname === os4.hostname()) { hostnameMatched = true; } } @@ -56647,7 +53677,7 @@ var require_fetch2 = __commonJS({ module2.exports = fetch2; var asPromise = require_aspromise(); var inquire = require_inquire(); - var fs = inquire("fs"); + var fs2 = inquire("fs"); function fetch2(filename, options, callback) { if (typeof options === "function") { callback = options; @@ -56656,8 +53686,8 @@ var require_fetch2 = __commonJS({ options = {}; if (!callback) return asPromise(fetch2, this, filename, options); - if (!options.xhr && fs && fs.readFile) - return fs.readFile(filename, function fetchReadFileCallback(err, contents) { + if (!options.xhr && fs2 && fs2.readFile) + return fs2.readFile(filename, function fetchReadFileCallback(err, contents) { return err && typeof XMLHttpRequest !== "undefined" ? fetch2.xhr(filename, options, callback) : err ? callback(err) : callback(null, options.binary ? contents : contents.toString("utf8")); }); return fetch2.xhr(filename, options, callback); @@ -62991,7 +60021,7 @@ var require_util11 = __commonJS({ "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.addCommonProtos = exports2.loadProtosWithOptionsSync = exports2.loadProtosWithOptions = void 0; - var fs = require("fs"); + var fs2 = require("fs"); var path = require("path"); var Protobuf = require_protobufjs(); function addIncludePathResolver(root, includePaths) { @@ -63003,7 +60033,7 @@ var require_util11 = __commonJS({ for (const directory of includePaths) { const fullPath = path.join(directory, target); try { - fs.accessSync(fullPath, fs.constants.R_OK); + fs2.accessSync(fullPath, fs2.constants.R_OK); return fullPath; } catch (err) { continue; @@ -66461,7 +63491,7 @@ var require_subchannel_call = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.Http2SubchannelCall = void 0; var http2 = require("http2"); - var os = require("os"); + var os4 = require("os"); var constants_1 = require_constants7(); var metadata_1 = require_metadata(); var stream_decoder_1 = require_stream_decoder(); @@ -66469,7 +63499,7 @@ var require_subchannel_call = __commonJS({ var constants_2 = require_constants7(); var TRACER_NAME = "subchannel_call"; function getSystemErrorName(errno) { - for (const [name, num] of Object.entries(os.constants.errno)) { + for (const [name, num] of Object.entries(os4.constants.errno)) { if (num === errno) { return name; } @@ -72845,7 +69875,7 @@ var require_certificate_provider = __commonJS({ "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.FileWatcherCertificateProvider = void 0; - var fs = require("fs"); + var fs2 = require("fs"); var logging = require_logging(); var constants_1 = require_constants7(); var util_1 = require("util"); @@ -72853,7 +69883,7 @@ var require_certificate_provider = __commonJS({ function trace(text) { logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); } - var readFilePromise = (0, util_1.promisify)(fs.readFile); + var readFilePromise = (0, util_1.promisify)(fs2.readFile); var FileWatcherCertificateProvider = class { constructor(config) { this.config = config; @@ -74542,7 +71572,7 @@ var require_util12 = __commonJS({ "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.addCommonProtos = exports2.loadProtosWithOptionsSync = exports2.loadProtosWithOptions = void 0; - var fs = require("fs"); + var fs2 = require("fs"); var path = require("path"); var Protobuf = require_protobufjs(); function addIncludePathResolver(root, includePaths) { @@ -74554,7 +71584,7 @@ var require_util12 = __commonJS({ for (const directory of includePaths) { const fullPath = path.join(directory, target); try { - fs.accessSync(fullPath, fs.constants.R_OK); + fs2.accessSync(fullPath, fs2.constants.R_OK); return fullPath; } catch (err) { continue; @@ -75043,7 +72073,7 @@ var require_docker = __commonJS({ var Config = require_config(); var Task = require_task(); var Node = require_node3(); - var Exec = require_exec2(); + var Exec = require_exec(); var util = require_util9(); var withSession = require_session(); var extend = util.extend; @@ -76477,7 +73507,450 @@ __export(cleanup_exports, { run: () => run }); module.exports = __toCommonJS(cleanup_exports); -var core = __toESM(require_core()); + +// node_modules/@actions/core/lib/command.js +var os = __toESM(require("os"), 1); + +// node_modules/@actions/core/lib/utils.js +function toCommandValue(input) { + if (input === null || input === void 0) { + return ""; + } else if (typeof input === "string" || input instanceof String) { + return input; + } + return JSON.stringify(input); +} +function toCommandProperties(annotationProperties) { + if (!Object.keys(annotationProperties).length) { + return {}; + } + return { + title: annotationProperties.title, + file: annotationProperties.file, + line: annotationProperties.startLine, + endLine: annotationProperties.endLine, + col: annotationProperties.startColumn, + endColumn: annotationProperties.endColumn + }; +} + +// node_modules/@actions/core/lib/command.js +function issueCommand(command, properties, message) { + const cmd = new Command(command, properties, message); + process.stdout.write(cmd.toString() + os.EOL); +} +var CMD_STRING = "::"; +var Command = class { + constructor(command, properties, message) { + if (!command) { + command = "missing.command"; + } + this.command = command; + this.properties = properties; + this.message = message; + } + toString() { + let cmdStr = CMD_STRING + this.command; + if (this.properties && Object.keys(this.properties).length > 0) { + cmdStr += " "; + let first = true; + for (const key in this.properties) { + if (this.properties.hasOwnProperty(key)) { + const val = this.properties[key]; + if (val) { + if (first) { + first = false; + } else { + cmdStr += ","; + } + cmdStr += `${key}=${escapeProperty(val)}`; + } + } + } + } + cmdStr += `${CMD_STRING}${escapeData(this.message)}`; + return cmdStr; + } +}; +function escapeData(s) { + return toCommandValue(s).replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A"); +} +function escapeProperty(s) { + return toCommandValue(s).replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A").replace(/:/g, "%3A").replace(/,/g, "%2C"); +} + +// node_modules/@actions/core/lib/core.js +var os3 = __toESM(require("os"), 1); + +// node_modules/@actions/http-client/lib/index.js +var tunnel = __toESM(require_tunnel2(), 1); +var import_undici = __toESM(require_undici(), 1); +var HttpCodes; +(function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; +})(HttpCodes || (HttpCodes = {})); +var Headers; +(function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; +})(Headers || (Headers = {})); +var MediaTypes; +(function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; +})(MediaTypes || (MediaTypes = {})); +var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect +]; +var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout +]; + +// node_modules/@actions/core/lib/summary.js +var import_os = require("os"); +var import_fs = require("fs"); +var __awaiter = function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = 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 { access, appendFile, writeFile } = import_fs.promises; +var SUMMARY_ENV_VAR = "GITHUB_STEP_SUMMARY"; +var Summary = class { + constructor() { + this._buffer = ""; + } + /** + * Finds the summary file path from the environment, rejects if env var is not found or file does not exist + * Also checks r/w permissions. + * + * @returns step summary file path + */ + filePath() { + return __awaiter(this, void 0, void 0, function* () { + if (this._filePath) { + return this._filePath; + } + const pathFromEnv = process.env[SUMMARY_ENV_VAR]; + if (!pathFromEnv) { + throw new Error(`Unable to find environment variable for $${SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); + } + try { + yield access(pathFromEnv, import_fs.constants.R_OK | import_fs.constants.W_OK); + } catch (_a) { + throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); + } + this._filePath = pathFromEnv; + return this._filePath; + }); + } + /** + * Wraps content in an HTML tag, adding any HTML attributes + * + * @param {string} tag HTML tag to wrap + * @param {string | null} content content within the tag + * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add + * + * @returns {string} content wrapped in HTML element + */ + wrap(tag, content, attrs = {}) { + const htmlAttrs = Object.entries(attrs).map(([key, value]) => ` ${key}="${value}"`).join(""); + if (!content) { + return `<${tag}${htmlAttrs}>`; + } + return `<${tag}${htmlAttrs}>${content}`; + } + /** + * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default. + * + * @param {SummaryWriteOptions} [options] (optional) options for write operation + * + * @returns {Promise} summary instance + */ + write(options) { + return __awaiter(this, void 0, void 0, function* () { + const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); + const filePath = yield this.filePath(); + const writeFunc = overwrite ? writeFile : appendFile; + yield writeFunc(filePath, this._buffer, { encoding: "utf8" }); + return this.emptyBuffer(); + }); + } + /** + * Clears the summary buffer and wipes the summary file + * + * @returns {Summary} summary instance + */ + clear() { + return __awaiter(this, void 0, void 0, function* () { + return this.emptyBuffer().write({ overwrite: true }); + }); + } + /** + * Returns the current summary buffer as a string + * + * @returns {string} string of summary buffer + */ + stringify() { + return this._buffer; + } + /** + * If the summary buffer is empty + * + * @returns {boolen} true if the buffer is empty + */ + isEmptyBuffer() { + return this._buffer.length === 0; + } + /** + * Resets the summary buffer without writing to summary file + * + * @returns {Summary} summary instance + */ + emptyBuffer() { + this._buffer = ""; + return this; + } + /** + * Adds raw text to the summary buffer + * + * @param {string} text content to add + * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false) + * + * @returns {Summary} summary instance + */ + addRaw(text, addEOL = false) { + this._buffer += text; + return addEOL ? this.addEOL() : this; + } + /** + * Adds the operating system-specific end-of-line marker to the buffer + * + * @returns {Summary} summary instance + */ + addEOL() { + return this.addRaw(import_os.EOL); + } + /** + * Adds an HTML codeblock to the summary buffer + * + * @param {string} code content to render within fenced code block + * @param {string} lang (optional) language to syntax highlight code + * + * @returns {Summary} summary instance + */ + addCodeBlock(code, lang) { + const attrs = Object.assign({}, lang && { lang }); + const element = this.wrap("pre", this.wrap("code", code), attrs); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML list to the summary buffer + * + * @param {string[]} items list of items to render + * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false) + * + * @returns {Summary} summary instance + */ + addList(items, ordered = false) { + const tag = ordered ? "ol" : "ul"; + const listItems = items.map((item) => this.wrap("li", item)).join(""); + const element = this.wrap(tag, listItems); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML table to the summary buffer + * + * @param {SummaryTableCell[]} rows table rows + * + * @returns {Summary} summary instance + */ + addTable(rows) { + const tableBody = rows.map((row) => { + const cells = row.map((cell) => { + if (typeof cell === "string") { + return this.wrap("td", cell); + } + const { header, data, colspan, rowspan } = cell; + const tag = header ? "th" : "td"; + const attrs = Object.assign(Object.assign({}, colspan && { colspan }), rowspan && { rowspan }); + return this.wrap(tag, data, attrs); + }).join(""); + return this.wrap("tr", cells); + }).join(""); + const element = this.wrap("table", tableBody); + return this.addRaw(element).addEOL(); + } + /** + * Adds a collapsable HTML details element to the summary buffer + * + * @param {string} label text for the closed state + * @param {string} content collapsable content + * + * @returns {Summary} summary instance + */ + addDetails(label, content) { + const element = this.wrap("details", this.wrap("summary", label) + content); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML image tag to the summary buffer + * + * @param {string} src path to the image you to embed + * @param {string} alt text description of the image + * @param {SummaryImageOptions} options (optional) addition image attributes + * + * @returns {Summary} summary instance + */ + addImage(src, alt, options) { + const { width, height } = options || {}; + const attrs = Object.assign(Object.assign({}, width && { width }), height && { height }); + const element = this.wrap("img", null, Object.assign({ src, alt }, attrs)); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML section heading element + * + * @param {string} text heading text + * @param {number | string} [level=1] (optional) the heading level, default: 1 + * + * @returns {Summary} summary instance + */ + addHeading(text, level) { + const tag = `h${level}`; + const allowedTag = ["h1", "h2", "h3", "h4", "h5", "h6"].includes(tag) ? tag : "h1"; + const element = this.wrap(allowedTag, text); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML thematic break (
) to the summary buffer + * + * @returns {Summary} summary instance + */ + addSeparator() { + const element = this.wrap("hr", null); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML line break (
) to the summary buffer + * + * @returns {Summary} summary instance + */ + addBreak() { + const element = this.wrap("br", null); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML blockquote to the summary buffer + * + * @param {string} text quote text + * @param {string} cite (optional) citation url + * + * @returns {Summary} summary instance + */ + addQuote(text, cite) { + const attrs = Object.assign({}, cite && { cite }); + const element = this.wrap("blockquote", text, attrs); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML anchor tag to the summary buffer + * + * @param {string} text link text/content + * @param {string} href hyperlink + * + * @returns {Summary} summary instance + */ + addLink(text, href) { + const element = this.wrap("a", text, { href }); + return this.addRaw(element).addEOL(); + } +}; +var _summary = new Summary(); + +// node_modules/@actions/core/lib/platform.js +var import_os2 = __toESM(require("os"), 1); + +// node_modules/@actions/io/lib/io-util.js +var fs = __toESM(require("fs"), 1); +var { chmod, copyFile, lstat, mkdir, open, readdir, rename, rm, rmdir, stat, symlink, unlink } = fs.promises; +var IS_WINDOWS = process.platform === "win32"; +var READONLY = fs.constants.O_RDONLY; + +// node_modules/@actions/exec/lib/toolrunner.js +var IS_WINDOWS2 = process.platform === "win32"; + +// node_modules/@actions/core/lib/platform.js +var platform = import_os2.default.platform(); +var arch = import_os2.default.arch(); + +// node_modules/@actions/core/lib/core.js +var ExitCode; +(function(ExitCode2) { + ExitCode2[ExitCode2["Success"] = 0] = "Success"; + ExitCode2[ExitCode2["Failure"] = 1] = "Failure"; +})(ExitCode || (ExitCode = {})); +function error(message, properties = {}) { + issueCommand("error", toCommandProperties(properties), message instanceof Error ? message.toString() : message); +} +function info(message) { + process.stdout.write(message + os3.EOL); +} + +// src/cleanup.ts var import_dockerode = __toESM(require_docker()); // docker/containers.json @@ -76563,12 +74036,12 @@ async function run(cutoff = "24h") { try { const docker = new import_dockerode.default(); const untilFilter = { until: [cutoff] }; - core.info(`Pruning networks older than ${cutoff}`); + info(`Pruning networks older than ${cutoff}`); await attemptCleanup( "pruning networks", async () => docker.pruneNetworks({ filters: untilFilter }) ); - core.info(`Pruning containers older than ${cutoff}`); + info(`Pruning containers older than ${cutoff}`); await attemptCleanup( "pruning containers", async () => docker.pruneContainers({ filters: untilFilter }) @@ -76585,7 +74058,7 @@ async function run(cutoff = "24h") { ); } catch (error2) { const message = error2 instanceof Error ? error2.message : String(error2); - core.error(`Error cleaning up: ${message}`); + error(`Error cleaning up: ${message}`); } } async function attemptCleanup(description, cleanup) { @@ -76593,7 +74066,7 @@ async function attemptCleanup(description, cleanup) { await cleanup(); } catch (error2) { const message = error2 instanceof Error ? error2.message : String(error2); - core.error(`Error ${description}: ${message}`); + error(`Error ${description}: ${message}`); } } async function cleanupOldImageVersions(docker, imageName) { @@ -76601,19 +74074,19 @@ async function cleanupOldImageVersions(docker, imageName) { const options = { filters: `{"reference":["${repo}"]}` }; - core.info(`Cleaning up images for ${repo}`); + info(`Cleaning up images for ${repo}`); const imageInfoList = await docker.listImages(options); for (const imageInfo of imageInfoList) { if (imageMatches(imageInfo, imageName)) { - core.info(`Skipping current image ${imageInfo.Id}`); + info(`Skipping current image ${imageInfo.Id}`); continue; } - core.info(`Removing image ${imageInfo.Id}`); + info(`Removing image ${imageInfo.Id}`); try { await docker.getImage(imageInfo.Id).remove(); } catch (error2) { const message = error2 instanceof Error ? error2.message : String(error2); - core.info(`Unable to remove ${imageInfo.Id} -- ${message}`); + info(`Unable to remove ${imageInfo.Id} -- ${message}`); } } } diff --git a/dist/main.js b/dist/main.js index 64c7a779c..b0e3fec87 100644 --- a/dist/main.js +++ b/dist/main.js @@ -34,287 +34,6 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// node_modules/@actions/core/lib/utils.js -var require_utils = __commonJS({ - "node_modules/@actions/core/lib/utils.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.toCommandValue = toCommandValue; - exports2.toCommandProperties = toCommandProperties; - function toCommandValue(input) { - if (input === null || input === void 0) { - return ""; - } else if (typeof input === "string" || input instanceof String) { - return input; - } - return JSON.stringify(input); - } - function toCommandProperties(annotationProperties) { - if (!Object.keys(annotationProperties).length) { - return {}; - } - return { - title: annotationProperties.title, - file: annotationProperties.file, - line: annotationProperties.startLine, - endLine: annotationProperties.endLine, - col: annotationProperties.startColumn, - endColumn: annotationProperties.endColumn - }; - } - } -}); - -// node_modules/@actions/core/lib/command.js -var require_command = __commonJS({ - "node_modules/@actions/core/lib/command.js"(exports2) { - "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - 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 ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - } - __setModuleDefault(result, mod); - return result; - }; - })(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.issueCommand = issueCommand; - exports2.issue = issue; - var os = __importStar(require("os")); - var utils_1 = require_utils(); - function issueCommand(command, properties, message) { - const cmd = new Command(command, properties, message); - process.stdout.write(cmd.toString() + os.EOL); - } - function issue(name, message = "") { - issueCommand(name, {}, message); - } - var CMD_STRING = "::"; - var Command = class { - constructor(command, properties, message) { - if (!command) { - command = "missing.command"; - } - this.command = command; - this.properties = properties; - this.message = message; - } - toString() { - let cmdStr = CMD_STRING + this.command; - if (this.properties && Object.keys(this.properties).length > 0) { - cmdStr += " "; - let first = true; - for (const key in this.properties) { - if (this.properties.hasOwnProperty(key)) { - const val = this.properties[key]; - if (val) { - if (first) { - first = false; - } else { - cmdStr += ","; - } - cmdStr += `${key}=${escapeProperty(val)}`; - } - } - } - } - cmdStr += `${CMD_STRING}${escapeData(this.message)}`; - return cmdStr; - } - }; - function escapeData(s) { - return (0, utils_1.toCommandValue)(s).replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A"); - } - function escapeProperty(s) { - return (0, utils_1.toCommandValue)(s).replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A").replace(/:/g, "%3A").replace(/,/g, "%2C"); - } - } -}); - -// node_modules/@actions/core/lib/file-command.js -var require_file_command = __commonJS({ - "node_modules/@actions/core/lib/file-command.js"(exports2) { - "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - 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 ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - } - __setModuleDefault(result, mod); - return result; - }; - })(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.issueFileCommand = issueFileCommand; - exports2.prepareKeyValueMessage = prepareKeyValueMessage; - var crypto = __importStar(require("crypto")); - var fs3 = __importStar(require("fs")); - var os = __importStar(require("os")); - var utils_1 = require_utils(); - function issueFileCommand(command, message) { - const filePath = process.env[`GITHUB_${command}`]; - if (!filePath) { - throw new Error(`Unable to find environment variable for file command ${command}`); - } - if (!fs3.existsSync(filePath)) { - throw new Error(`Missing file at path: ${filePath}`); - } - fs3.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os.EOL}`, { - encoding: "utf8" - }); - } - function prepareKeyValueMessage(key, value) { - const delimiter = `ghadelimiter_${crypto.randomUUID()}`; - const convertedValue = (0, utils_1.toCommandValue)(value); - if (key.includes(delimiter)) { - throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); - } - if (convertedValue.includes(delimiter)) { - throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); - } - return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`; - } - } -}); - -// node_modules/@actions/core/node_modules/@actions/http-client/lib/proxy.js -var require_proxy = __commonJS({ - "node_modules/@actions/core/node_modules/@actions/http-client/lib/proxy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getProxyUrl = getProxyUrl2; - exports2.checkBypass = checkBypass2; - function getProxyUrl2(reqUrl) { - const usingSsl = reqUrl.protocol === "https:"; - if (checkBypass2(reqUrl)) { - return void 0; - } - const proxyVar = (() => { - if (usingSsl) { - return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; - } else { - return process.env["http_proxy"] || process.env["HTTP_PROXY"]; - } - })(); - if (proxyVar) { - try { - return new DecodedURL2(proxyVar); - } catch (_a) { - if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) - return new DecodedURL2(`http://${proxyVar}`); - } - } else { - return void 0; - } - } - function checkBypass2(reqUrl) { - if (!reqUrl.hostname) { - return false; - } - const reqHost = reqUrl.hostname; - if (isLoopbackAddress2(reqHost)) { - return true; - } - const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; - if (!noProxy) { - return false; - } - let reqPort; - if (reqUrl.port) { - reqPort = Number(reqUrl.port); - } else if (reqUrl.protocol === "http:") { - reqPort = 80; - } else if (reqUrl.protocol === "https:") { - reqPort = 443; - } - const upperReqHosts = [reqUrl.hostname.toUpperCase()]; - if (typeof reqPort === "number") { - upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); - } - for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { - if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { - return true; - } - } - return false; - } - function isLoopbackAddress2(host) { - const hostLower = host.toLowerCase(); - return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); - } - var DecodedURL2 = class extends URL { - constructor(url, base) { - super(url, base); - this._decodedUsername = decodeURIComponent(super.username); - this._decodedPassword = decodeURIComponent(super.password); - } - get username() { - return this._decodedUsername; - } - get password() { - return this._decodedPassword; - } - }; - } -}); - // node_modules/tunnel/lib/tunnel.js var require_tunnel = __commonJS({ "node_modules/tunnel/lib/tunnel.js"(exports2) { @@ -443,18 +162,18 @@ var require_tunnel = __commonJS({ res.statusCode ); socket.destroy(); - var error3 = new Error("tunneling socket could not be established, statusCode=" + res.statusCode); - error3.code = "ECONNRESET"; - options.request.emit("error", error3); + var error2 = new Error("tunneling socket could not be established, statusCode=" + res.statusCode); + error2.code = "ECONNRESET"; + options.request.emit("error", error2); self2.removeSocket(placeholder); return; } if (head.length > 0) { debug2("got illegal response body from proxy"); socket.destroy(); - var error3 = new Error("got illegal response body from proxy"); - error3.code = "ECONNRESET"; - options.request.emit("error", error3); + var error2 = new Error("got illegal response body from proxy"); + error2.code = "ECONNRESET"; + options.request.emit("error", error2); self2.removeSocket(placeholder); return; } @@ -469,9 +188,9 @@ var require_tunnel = __commonJS({ cause.message, cause.stack ); - var error3 = new Error("tunneling socket could not be established, cause=" + cause.message); - error3.code = "ECONNRESET"; - options.request.emit("error", error3); + var error2 = new Error("tunneling socket could not be established, cause=" + cause.message); + error2.code = "ECONNRESET"; + options.request.emit("error", error2); self2.removeSocket(placeholder); } }; @@ -1800,14 +1519,14 @@ var require_diagnostics = __commonJS({ diagnosticsChannel.channel("undici:client:connectError").subscribe((evt) => { const { connectParams: { version, protocol, port, host }, - error: error3 + error: error2 } = evt; debuglog( "connection to %s using %s%s errored - %s", `${host}${port ? `:${port}` : ""}`, protocol, version, - error3.message + error2.message ); }); diagnosticsChannel.channel("undici:client:sendHeaders").subscribe((evt) => { @@ -1838,14 +1557,14 @@ var require_diagnostics = __commonJS({ diagnosticsChannel.channel("undici:request:error").subscribe((evt) => { const { request: { method, path, origin }, - error: error3 + error: error2 } = evt; debuglog( "request to %s %s/%s errored - %s", method, origin, path, - error3.message + error2.message ); }); isClientSet = true; @@ -1880,7 +1599,7 @@ var require_diagnostics = __commonJS({ diagnosticsChannel.channel("undici:client:connectError").subscribe((evt) => { const { connectParams: { version, protocol, port, host }, - error: error3 + error: error2 } = evt; debuglog( "connection to %s%s using %s%s errored - %s", @@ -1888,7 +1607,7 @@ var require_diagnostics = __commonJS({ port ? `:${port}` : "", protocol, version, - error3.message + error2.message ); }); diagnosticsChannel.channel("undici:client:sendHeaders").subscribe((evt) => { @@ -2158,16 +1877,16 @@ var require_request = __commonJS({ this.onError(err); } } - onError(error3) { + onError(error2) { this.onFinally(); if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error3 }); + channels.error.publish({ request: this, error: error2 }); } if (this.aborted) { return; } this.aborted = true; - return this[kHandler].onError(error3); + return this[kHandler].onError(error2); } onFinally() { if (this.errorHandler) { @@ -2905,7 +2624,7 @@ var require_connect = __commonJS({ }); // node_modules/undici/lib/llhttp/utils.js -var require_utils2 = __commonJS({ +var require_utils = __commonJS({ "node_modules/undici/lib/llhttp/utils.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); @@ -2930,7 +2649,7 @@ var require_constants2 = __commonJS({ "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.SPECIAL_HEADERS = exports2.HEADER_STATE = exports2.MINOR = exports2.MAJOR = exports2.CONNECTION_TOKEN_CHARS = exports2.HEADER_CHARS = exports2.TOKEN = exports2.STRICT_TOKEN = exports2.HEX = exports2.URL_CHAR = exports2.STRICT_URL_CHAR = exports2.USERINFO_CHARS = exports2.MARK = exports2.ALPHANUM = exports2.NUM = exports2.HEX_MAP = exports2.NUM_MAP = exports2.ALPHA = exports2.FINISH = exports2.H_METHOD_MAP = exports2.METHOD_MAP = exports2.METHODS_RTSP = exports2.METHODS_ICE = exports2.METHODS_HTTP = exports2.METHODS = exports2.LENIENT_FLAGS = exports2.FLAGS = exports2.TYPE = exports2.ERROR = void 0; - var utils_1 = require_utils2(); + var utils_1 = require_utils(); var ERROR; (function(ERROR2) { ERROR2[ERROR2["OK"] = 0] = "OK"; @@ -5905,7 +5624,7 @@ Content-Type: ${value.type || "application/octet-stream"}\r } throwIfAborted(object[kState]); const promise = createDeferredPromise(); - const errorSteps = (error3) => promise.reject(error3); + const errorSteps = (error2) => promise.reject(error2); const successSteps = (data) => { try { promise.resolve(convertBytesToJSValue(data)); @@ -6001,7 +5720,7 @@ var require_client_h1 = __commonJS({ kResume, kHTTPContext } = require_symbols(); - var constants = require_constants2(); + var constants3 = require_constants2(); var EMPTY_BUF = Buffer.alloc(0); var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; @@ -6076,7 +5795,7 @@ var require_client_h1 = __commonJS({ constructor(client, socket, { exports: exports3 }) { assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0); this.llhttp = exports3; - this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE); + this.ptr = this.llhttp.llhttp_alloc(constants3.TYPE.RESPONSE); this.client = client; this.socket = socket; this.timeout = null; @@ -6171,11 +5890,11 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants.ERROR.OK) { + if (ret !== constants3.ERROR.OK) { const body = data.subarray(offset); - if (ret === constants.ERROR.PAUSED_UPGRADE) { + if (ret === constants3.ERROR.PAUSED_UPGRADE) { this.onUpgrade(body); - } else if (ret === constants.ERROR.PAUSED) { + } else if (ret === constants3.ERROR.PAUSED) { this.paused = true; socket.unshift(body); } else { @@ -6198,10 +5917,10 @@ var require_client_h1 = __commonJS({ } finally { currentParser = null; } - if (ret === constants.ERROR.OK) { + if (ret === constants3.ERROR.OK) { return null; } - if (ret === constants.ERROR.PAUSED || ret === constants.ERROR.PAUSED_UPGRADE) { + if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { this.paused = true; return null; } @@ -6218,7 +5937,7 @@ var require_client_h1 = __commonJS({ const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } - return new HTTPParserError(message, constants.ERROR[ret], data); + return new HTTPParserError(message, constants3.ERROR[ret], data); } destroy() { assert(this.ptr != null); @@ -6397,7 +6116,7 @@ var require_client_h1 = __commonJS({ socket[kBlocking] = false; client[kResume](); } - return pause ? constants.ERROR.PAUSED : 0; + return pause ? constants3.ERROR.PAUSED : 0; } onBody(buf) { const { client, socket, statusCode, maxResponseSize } = this; @@ -6419,7 +6138,7 @@ var require_client_h1 = __commonJS({ } this.bytesRead += buf.length; if (request2.onData(buf) === false) { - return constants.ERROR.PAUSED; + return constants3.ERROR.PAUSED; } } onMessageComplete() { @@ -6455,13 +6174,13 @@ var require_client_h1 = __commonJS({ if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); - return constants.ERROR.PAUSED; + return constants3.ERROR.PAUSED; } else if (!shouldKeepAlive) { util.destroy(socket, new InformationalError("reset")); - return constants.ERROR.PAUSED; + return constants3.ERROR.PAUSED; } else if (socket[kReset] && client[kRunning] === 0) { util.destroy(socket, new InformationalError("reset")); - return constants.ERROR.PAUSED; + return constants3.ERROR.PAUSED; } else if (client[kPipelining] == null || client[kPipelining] === 1) { setImmediate(() => client[kResume]()); } else { @@ -7518,8 +7237,8 @@ var require_client_h2 = __commonJS({ } request2.onRequestSent(); client[kResume](); - } catch (error3) { - abort(error3); + } catch (error2) { + abort(error2); } } function writeStream(abort, socket, expectsPayload, h2stream, body, client, request2, contentLength) { @@ -7674,8 +7393,8 @@ var require_redirect_handler = __commonJS({ onUpgrade(statusCode, headers, socket) { this.handler.onUpgrade(statusCode, headers, socket); } - onError(error3) { - this.handler.onError(error3); + onError(error2) { + this.handler.onError(error2); } onHeaders(statusCode, headers, resume, statusText) { this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body) ? null : parseLocation(statusCode, headers); @@ -8604,7 +8323,7 @@ var require_pool = __commonJS({ this[kOptions] = { ...util.deepClone(options), connect, allowH2 }; this[kOptions].interceptors = options.interceptors ? { ...options.interceptors } : void 0; this[kFactory] = factory; - this.on("connectionError", (origin2, targets, error3) => { + this.on("connectionError", (origin2, targets, error2) => { for (const target of targets) { const idx = this[kClients].indexOf(target); if (idx !== -1) { @@ -10999,13 +10718,13 @@ var require_mock_utils = __commonJS({ if (mockDispatch2.data.callback) { mockDispatch2.data = { ...mockDispatch2.data, ...mockDispatch2.data.callback(opts) }; } - const { data: { statusCode, data, headers, trailers, error: error3 }, delay, persist } = mockDispatch2; + const { data: { statusCode, data, headers, trailers, error: error2 }, delay, persist } = mockDispatch2; const { timesInvoked, times } = mockDispatch2; mockDispatch2.consumed = !persist && timesInvoked >= times; mockDispatch2.pending = timesInvoked < times; - if (error3 !== null) { + if (error2 !== null) { deleteMockDispatch(this[kDispatches], key); - handler2.onError(error3); + handler2.onError(error2); return true; } if (typeof delay === "number" && delay > 0) { @@ -11043,19 +10762,19 @@ var require_mock_utils = __commonJS({ if (agent.isMockActive) { try { mockDispatch.call(this, opts, handler2); - } catch (error3) { - if (error3 instanceof MockNotMatchedError) { + } catch (error2) { + if (error2 instanceof MockNotMatchedError) { const netConnect = agent[kGetNetConnect](); if (netConnect === false) { - throw new MockNotMatchedError(`${error3.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`); + throw new MockNotMatchedError(`${error2.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`); } if (checkNetConnect(netConnect, origin)) { originalDispatch.call(this, opts, handler2); } else { - throw new MockNotMatchedError(`${error3.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`); + throw new MockNotMatchedError(`${error2.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`); } } else { - throw error3; + throw error2; } } } else { @@ -11220,11 +10939,11 @@ var require_mock_interceptor = __commonJS({ /** * Mock an undici request with a defined error. */ - replyWithError(error3) { - if (typeof error3 === "undefined") { + replyWithError(error2) { + if (typeof error2 === "undefined") { throw new InvalidArgumentError("error must be defined"); } - const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error: error3 }); + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error: error2 }); return new MockScope(newMockDispatch); } /** @@ -12185,12 +11904,12 @@ var require_headers = __commonJS({ append(name, value, isLowerCase) { this[kHeadersSortedMap] = null; const lowercaseName = isLowerCase ? name : name.toLowerCase(); - const exists = this[kHeadersMap].get(lowercaseName); - if (exists) { + const exists2 = this[kHeadersMap].get(lowercaseName); + if (exists2) { const delimiter = lowercaseName === "cookie" ? "; " : ", "; this[kHeadersMap].set(lowercaseName, { - name: exists.name, - value: `${exists.value}${delimiter}${value}` + name: exists2.name, + value: `${exists2.value}${delimiter}${value}` }); } else { this[kHeadersMap].set(lowercaseName, { name, value }); @@ -13742,17 +13461,17 @@ var require_fetch = __commonJS({ this.emit("terminated", reason); } // https://fetch.spec.whatwg.org/#fetch-controller-abort - abort(error3) { + abort(error2) { if (this.state !== "ongoing") { return; } this.state = "aborted"; - if (!error3) { - error3 = new DOMException("The operation was aborted.", "AbortError"); + if (!error2) { + error2 = new DOMException("The operation was aborted.", "AbortError"); } - this.serializedAbortReason = error3; - this.connection?.destroy(error3); - this.emit("terminated", error3); + this.serializedAbortReason = error2; + this.connection?.destroy(error2); + this.emit("terminated", error2); } }; function handleFetchDone(response) { @@ -13848,12 +13567,12 @@ var require_fetch = __commonJS({ ); } var markResourceTiming = performance.markResourceTiming; - function abortFetch(p, request2, responseObject, error3) { + function abortFetch(p, request2, responseObject, error2) { if (p) { - p.reject(error3); + p.reject(error2); } if (request2.body != null && isReadable(request2.body?.stream)) { - request2.body.stream.cancel(error3).catch((err) => { + request2.body.stream.cancel(error2).catch((err) => { if (err.code === "ERR_INVALID_STATE") { return; } @@ -13865,7 +13584,7 @@ var require_fetch = __commonJS({ } const response = responseObject[kState]; if (response.body != null && isReadable(response.body?.stream)) { - response.body.stream.cancel(error3).catch((err) => { + response.body.stream.cancel(error2).catch((err) => { if (err.code === "ERR_INVALID_STATE") { return; } @@ -14686,13 +14405,13 @@ var require_fetch = __commonJS({ fetchParams.controller.ended = true; this.body.push(null); }, - onError(error3) { + onError(error2) { if (this.abort) { fetchParams.controller.off("terminated", this.abort); } - this.body?.destroy(error3); - fetchParams.controller.terminate(error3); - reject(error3); + this.body?.destroy(error2); + fetchParams.controller.terminate(error2); + reject(error2); }, onUpgrade(status, rawHeaders, socket) { if (status !== 101) { @@ -15155,8 +14874,8 @@ var require_util4 = __commonJS({ } fr[kResult] = result; fireAProgressEvent("load", fr); - } catch (error3) { - fr[kError] = error3; + } catch (error2) { + fr[kError] = error2; fireAProgressEvent("error", fr); } if (fr[kState] !== "loading") { @@ -15165,13 +14884,13 @@ var require_util4 = __commonJS({ }); break; } - } catch (error3) { + } catch (error2) { if (fr[kAborted]) { return; } queueMicrotask(() => { fr[kState] = "done"; - fr[kError] = error3; + fr[kError] = error2; fireAProgressEvent("error", fr); if (fr[kState] !== "loading") { fireAProgressEvent("loadend", fr); @@ -17477,11 +17196,11 @@ var require_connection = __commonJS({ }); } } - function onSocketError(error3) { + function onSocketError(error2) { const { ws } = this; ws[kReadyState] = states.CLOSING; if (channels.socketError.hasSubscribers) { - channels.socketError.publish(error3); + channels.socketError.publish(error2); } this.destroy(); } @@ -17772,10 +17491,10 @@ var require_receiver = __commonJS({ this.#extensions.get("permessage-deflate").decompress( body, this.#info.fin, - (error3, data) => { - if (error3) { - const code = error3 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error3.message); + (error2, data) => { + if (error2) { + const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; + failWebsocketConnectionWithCode(this.ws, code, error2.message); return; } if (!this.writeFragments(data)) { @@ -18839,8 +18558,8 @@ var require_eventsource = __commonJS({ pipeline( response.body.stream, eventSourceStream, - (error3) => { - if (error3?.aborted === false) { + (error2) => { + if (error2?.aborted === false) { this.close(); this.dispatchEvent(new Event("error")); } @@ -19113,9 +18832,90 @@ var require_undici = __commonJS({ } }); -// node_modules/@actions/core/node_modules/@actions/http-client/lib/index.js +// node_modules/@actions/github/node_modules/@actions/http-client/lib/proxy.js +var require_proxy = __commonJS({ + "node_modules/@actions/github/node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getProxyUrl = getProxyUrl2; + exports2.checkBypass = checkBypass2; + function getProxyUrl2(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass2(reqUrl)) { + return void 0; + } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; + } + })(); + if (proxyVar) { + try { + return new DecodedURL2(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL2(`http://${proxyVar}`); + } + } else { + return void 0; + } + } + function checkBypass2(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress2(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; + } + } + return false; + } + function isLoopbackAddress2(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL2 = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; + } + }; + } +}); + +// node_modules/@actions/github/node_modules/@actions/http-client/lib/index.js var require_lib = __commonJS({ - "node_modules/@actions/core/node_modules/@actions/http-client/lib/index.js"(exports2) { + "node_modules/@actions/github/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -19154,7 +18954,7 @@ var require_lib = __commonJS({ return result; }; })(); - var __awaiter3 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve) { resolve(value); @@ -19262,8 +19062,8 @@ var require_lib = __commonJS({ this.message = message; } readBody() { - return __awaiter3(this, void 0, void 0, function* () { - return new Promise((resolve) => __awaiter3(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve) => __awaiter4(this, void 0, void 0, function* () { let output = Buffer.alloc(0); this.message.on("data", (chunk) => { output = Buffer.concat([output, chunk]); @@ -19275,8 +19075,8 @@ var require_lib = __commonJS({ }); } readBodyBuffer() { - return __awaiter3(this, void 0, void 0, function* () { - return new Promise((resolve) => __awaiter3(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve) => __awaiter4(this, void 0, void 0, function* () { const chunks = []; this.message.on("data", (chunk) => { chunks.push(chunk); @@ -19332,42 +19132,42 @@ var require_lib = __commonJS({ } } options(requestUrl, additionalHeaders) { - return __awaiter3(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); }); } get(requestUrl, additionalHeaders) { - return __awaiter3(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { return this.request("GET", requestUrl, null, additionalHeaders || {}); }); } del(requestUrl, additionalHeaders) { - return __awaiter3(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { return this.request("DELETE", requestUrl, null, additionalHeaders || {}); }); } post(requestUrl, data, additionalHeaders) { - return __awaiter3(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { return this.request("POST", requestUrl, data, additionalHeaders || {}); }); } patch(requestUrl, data, additionalHeaders) { - return __awaiter3(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { return this.request("PATCH", requestUrl, data, additionalHeaders || {}); }); } put(requestUrl, data, additionalHeaders) { - return __awaiter3(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { return this.request("PUT", requestUrl, data, additionalHeaders || {}); }); } head(requestUrl, additionalHeaders) { - return __awaiter3(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { return this.request("HEAD", requestUrl, null, additionalHeaders || {}); }); } sendStream(verb, requestUrl, stream2, additionalHeaders) { - return __awaiter3(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { return this.request(verb, requestUrl, stream2, additionalHeaders); }); } @@ -19376,14 +19176,14 @@ var require_lib = __commonJS({ * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise */ getJson(requestUrl_1) { - return __awaiter3(this, arguments, void 0, function* (requestUrl, additionalHeaders = {}) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, additionalHeaders = {}) { additionalHeaders[Headers2.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers2.Accept, MediaTypes2.ApplicationJson); const res = yield this.get(requestUrl, additionalHeaders); return this._processResponse(res, this.requestOptions); }); } postJson(requestUrl_1, obj_1) { - return __awaiter3(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { const data = JSON.stringify(obj, null, 2); additionalHeaders[Headers2.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers2.Accept, MediaTypes2.ApplicationJson); additionalHeaders[Headers2.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes2.ApplicationJson); @@ -19392,7 +19192,7 @@ var require_lib = __commonJS({ }); } putJson(requestUrl_1, obj_1) { - return __awaiter3(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { const data = JSON.stringify(obj, null, 2); additionalHeaders[Headers2.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers2.Accept, MediaTypes2.ApplicationJson); additionalHeaders[Headers2.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes2.ApplicationJson); @@ -19401,7 +19201,7 @@ var require_lib = __commonJS({ }); } patchJson(requestUrl_1, obj_1) { - return __awaiter3(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { const data = JSON.stringify(obj, null, 2); additionalHeaders[Headers2.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers2.Accept, MediaTypes2.ApplicationJson); additionalHeaders[Headers2.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes2.ApplicationJson); @@ -19415,17 +19215,17 @@ var require_lib = __commonJS({ * Prefer get, del, post and patch */ request(verb, requestUrl, data, headers) { - return __awaiter3(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { if (this._disposed) { throw new Error("Client has already been disposed."); } const parsedUrl = new URL(requestUrl); - let info8 = this._prepareRequest(verb, parsedUrl, headers); + let info2 = this._prepareRequest(verb, parsedUrl, headers); const maxTries = this._allowRetries && RetryableHttpVerbs2.includes(verb) ? this._maxRetries + 1 : 1; let numTries = 0; let response; do { - response = yield this.requestRaw(info8, data); + response = yield this.requestRaw(info2, data); if (response && response.message && response.message.statusCode === HttpCodes2.Unauthorized) { let authenticationHandler; for (const handler2 of this.handlers) { @@ -19435,7 +19235,7 @@ var require_lib = __commonJS({ } } if (authenticationHandler) { - return authenticationHandler.handleAuthentication(this, info8, data); + return authenticationHandler.handleAuthentication(this, info2, data); } else { return response; } @@ -19458,8 +19258,8 @@ var require_lib = __commonJS({ } } } - info8 = this._prepareRequest(verb, parsedRedirectUrl, headers); - response = yield this.requestRaw(info8, data); + info2 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info2, data); redirectsRemaining--; } if (!response.message.statusCode || !HttpResponseRetryCodes2.includes(response.message.statusCode)) { @@ -19488,8 +19288,8 @@ var require_lib = __commonJS({ * @param info * @param data */ - requestRaw(info8, data) { - return __awaiter3(this, void 0, void 0, function* () { + requestRaw(info2, data) { + return __awaiter4(this, void 0, void 0, function* () { return new Promise((resolve, reject) => { function callbackForResult(err, res) { if (err) { @@ -19500,7 +19300,7 @@ var require_lib = __commonJS({ resolve(res); } } - this.requestRawWithCallback(info8, data, callbackForResult); + this.requestRawWithCallback(info2, data, callbackForResult); }); }); } @@ -19510,12 +19310,12 @@ var require_lib = __commonJS({ * @param data * @param onResult */ - requestRawWithCallback(info8, data, onResult) { + requestRawWithCallback(info2, data, onResult) { if (typeof data === "string") { - if (!info8.options.headers) { - info8.options.headers = {}; + if (!info2.options.headers) { + info2.options.headers = {}; } - info8.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); + info2.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } let callbackCalled = false; function handleResult(err, res) { @@ -19524,7 +19324,7 @@ var require_lib = __commonJS({ onResult(err, res); } } - const req = info8.httpModule.request(info8.options, (msg) => { + const req = info2.httpModule.request(info2.options, (msg) => { const res = new HttpClientResponse2(msg); handleResult(void 0, res); }); @@ -19536,7 +19336,7 @@ var require_lib = __commonJS({ if (socket) { socket.end(); } - handleResult(new Error(`Request timeout: ${info8.options.path}`)); + handleResult(new Error(`Request timeout: ${info2.options.path}`)); }); req.on("error", function(err) { handleResult(err); @@ -19572,27 +19372,27 @@ var require_lib = __commonJS({ return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } _prepareRequest(method, requestUrl, headers) { - const info8 = {}; - info8.parsedUrl = requestUrl; - const usingSsl = info8.parsedUrl.protocol === "https:"; - info8.httpModule = usingSsl ? https2 : http2; + const info2 = {}; + info2.parsedUrl = requestUrl; + const usingSsl = info2.parsedUrl.protocol === "https:"; + info2.httpModule = usingSsl ? https2 : http2; const defaultPort = usingSsl ? 443 : 80; - info8.options = {}; - info8.options.host = info8.parsedUrl.hostname; - info8.options.port = info8.parsedUrl.port ? parseInt(info8.parsedUrl.port) : defaultPort; - info8.options.path = (info8.parsedUrl.pathname || "") + (info8.parsedUrl.search || ""); - info8.options.method = method; - info8.options.headers = this._mergeHeaders(headers); + info2.options = {}; + info2.options.host = info2.parsedUrl.hostname; + info2.options.port = info2.parsedUrl.port ? parseInt(info2.parsedUrl.port) : defaultPort; + info2.options.path = (info2.parsedUrl.pathname || "") + (info2.parsedUrl.search || ""); + info2.options.method = method; + info2.options.headers = this._mergeHeaders(headers); if (this.userAgent != null) { - info8.options.headers["user-agent"] = this.userAgent; + info2.options.headers["user-agent"] = this.userAgent; } - info8.options.agent = this._getAgent(info8.parsedUrl); + info2.options.agent = this._getAgent(info2.parsedUrl); if (this.handlers) { for (const handler2 of this.handlers) { - handler2.prepareRequest(info8.options); + handler2.prepareRequest(info2.options); } } - return info8; + return info2; } _mergeHeaders(headers) { if (this.requestOptions && this.requestOptions.headers) { @@ -19738,15 +19538,15 @@ var require_lib = __commonJS({ return baseUserAgent; } _performExponentialBackoff(retryNumber) { - return __awaiter3(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { retryNumber = Math.min(ExponentialBackoffCeiling2, retryNumber); const ms = ExponentialBackoffTimeSlice2 * Math.pow(2, retryNumber); return new Promise((resolve) => setTimeout(() => resolve(), ms)); }); } _processResponse(res, options) { - return __awaiter3(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => __awaiter3(this, void 0, void 0, function* () { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => __awaiter4(this, void 0, void 0, function* () { const statusCode = res.message.statusCode || 0; const response = { statusCode, @@ -19804,82314 +19604,79951 @@ var require_lib = __commonJS({ } }); -// node_modules/@actions/core/node_modules/@actions/http-client/lib/auth.js -var require_auth = __commonJS({ - "node_modules/@actions/core/node_modules/@actions/http-client/lib/auth.js"(exports2) { - "use strict"; - var __awaiter3 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); - } - return new (P || (P = 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); +// node_modules/docker-modem/lib/utils.js +var require_utils2 = __commonJS({ + "node_modules/docker-modem/lib/utils.js"(exports2, module2) { + var arr = []; + var each = arr.forEach; + var slice = arr.slice; + module2.exports.extend = function(obj) { + each.call(slice.call(arguments, 1), function(source) { + if (source) { + for (var prop in source) { + obj[prop] = source[prop]; } } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); }); + return obj; }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.PersonalAccessTokenCredentialHandler = exports2.BearerCredentialHandler = exports2.BasicCredentialHandler = void 0; - var BasicCredentialHandler = class { - constructor(username, password) { - this.username = username; - this.password = password; - } - prepareRequest(options) { - if (!options.headers) { - throw Error("The request has no headers"); - } - options.headers["Authorization"] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter3(this, void 0, void 0, function* () { - throw new Error("not implemented"); - }); - } - }; - exports2.BasicCredentialHandler = BasicCredentialHandler; - var BearerCredentialHandler = class { - constructor(token) { - this.token = token; - } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - if (!options.headers) { - throw Error("The request has no headers"); - } - options.headers["Authorization"] = `Bearer ${this.token}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter3(this, void 0, void 0, function* () { - throw new Error("not implemented"); - }); - } - }; - exports2.BearerCredentialHandler = BearerCredentialHandler; - var PersonalAccessTokenCredentialHandler = class { - constructor(token) { - this.token = token; - } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - if (!options.headers) { - throw Error("The request has no headers"); - } - options.headers["Authorization"] = `Basic ${Buffer.from(`PAT:${this.token}`).toString("base64")}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter3(this, void 0, void 0, function* () { - throw new Error("not implemented"); - }); + module2.exports.parseJSON = function(s) { + try { + return JSON.parse(s); + } catch (e) { + return null; } }; - exports2.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; } }); -// node_modules/@actions/core/lib/oidc-utils.js -var require_oidc_utils = __commonJS({ - "node_modules/@actions/core/lib/oidc-utils.js"(exports2) { - "use strict"; - var __awaiter3 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); - } - return new (P || (P = 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()); - }); +// node_modules/docker-modem/lib/http.js +var require_http = __commonJS({ + "node_modules/docker-modem/lib/http.js"(exports2, module2) { + var nativeHttps = require("https"); + var nativeHttp = require("http"); + var url = require("url"); + var utils = require_utils2(); + var maxRedirects = module2.exports.maxRedirects = 5; + var protocols = { + https: nativeHttps, + http: nativeHttp }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.OidcClient = void 0; - var http_client_1 = require_lib(); - var auth_1 = require_auth(); - var core_1 = require_core(); - var OidcClient = class _OidcClient { - static createHttpClient(allowRetry = true, maxRetry = 10) { - const requestOptions = { - allowRetries: allowRetry, - maxRetries: maxRetry - }; - return new http_client_1.HttpClient("actions/oidc-client", [new auth_1.BearerCredentialHandler(_OidcClient.getRequestToken())], requestOptions); - } - static getRequestToken() { - const token = process.env["ACTIONS_ID_TOKEN_REQUEST_TOKEN"]; - if (!token) { - throw new Error("Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable"); - } - return token; - } - static getIDTokenUrl() { - const runtimeUrl = process.env["ACTIONS_ID_TOKEN_REQUEST_URL"]; - if (!runtimeUrl) { - throw new Error("Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable"); - } - return runtimeUrl; - } - static getCall(id_token_url) { - return __awaiter3(this, void 0, void 0, function* () { - var _a; - const httpclient = _OidcClient.createHttpClient(); - const res = yield httpclient.getJson(id_token_url).catch((error3) => { - throw new Error(`Failed to get ID Token. - - Error Code : ${error3.statusCode} - - Error Message: ${error3.message}`); - }); - const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; - if (!id_token) { - throw new Error("Response json body do not have ID Token field"); + for (protocol in protocols) { + h = function() { + }; + h.prototype = protocols[protocol]; + h = new h(); + h.request = /* @__PURE__ */ (function(h2) { + return function(options, callback, redirectOptions) { + redirectOptions = redirectOptions || {}; + var max = typeof options === "object" && "maxRedirects" in options ? options.maxRedirects : exports2.maxRedirects; + var redirect = utils.extend({ + count: 0, + max, + clientRequest: null, + userCallback: callback + }, redirectOptions); + if (redirect.count > redirect.max) { + var err = new Error("Max redirects exceeded. To allow more redirects, pass options.maxRedirects property."); + redirect.clientRequest.emit("error", err); + return redirect.clientRequest; } - return id_token; - }); - } - static getIDToken(audience) { - return __awaiter3(this, void 0, void 0, function* () { - try { - let id_token_url = _OidcClient.getIDTokenUrl(); - if (audience) { - const encodedAudience = encodeURIComponent(audience); - id_token_url = `${id_token_url}&audience=${encodedAudience}`; - } - (0, core_1.debug)(`ID token url is ${id_token_url}`); - const id_token = yield _OidcClient.getCall(id_token_url); - (0, core_1.setSecret)(id_token); - return id_token; - } catch (error3) { - throw new Error(`Error message: ${error3.message}`); + redirect.count++; + var reqUrl; + if (typeof options === "string") { + reqUrl = options; + } else { + reqUrl = url.format(utils.extend({ + protocol + }, options)); } - }); - } - }; - exports2.OidcClient = OidcClient; + var clientRequest = Object.getPrototypeOf(h2).request(options, redirectCallback(reqUrl, redirect)); + if (!redirect.clientRequest) redirect.clientRequest = clientRequest; + function redirectCallback(reqUrl2, redirect2) { + return function(res) { + if (res.statusCode < 300 || res.statusCode > 399) { + return redirect2.userCallback(res); + } + if (!("location" in res.headers)) { + return redirect2.userCallback(res); + } + var redirectUrl = url.resolve(reqUrl2, res.headers.location); + var proto = url.parse(redirectUrl).protocol; + proto = proto.substr(0, proto.length - 1); + return module2.exports[proto].get(redirectUrl, redirectCallback(reqUrl2, redirect2), redirect2); + }; + } + return clientRequest; + }; + })(h); + h.get = /* @__PURE__ */ (function(h2) { + return function(options, cb, redirectOptions) { + var req = h2.request(options, cb, redirectOptions); + req.end(); + return req; + }; + })(h); + module2.exports[protocol] = h; + } + var h; + var protocol; } }); -// node_modules/@actions/core/lib/summary.js -var require_summary = __commonJS({ - "node_modules/@actions/core/lib/summary.js"(exports2) { - "use strict"; - var __awaiter3 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); +// node_modules/asn1/lib/ber/errors.js +var require_errors2 = __commonJS({ + "node_modules/asn1/lib/ber/errors.js"(exports2, module2) { + module2.exports = { + newInvalidAsn1Error: function(msg) { + var e = new Error(); + e.name = "InvalidAsn1Error"; + e.message = msg || ""; + return e; } - return new (P || (P = 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.summary = exports2.markdownSummary = exports2.SUMMARY_DOCS_URL = exports2.SUMMARY_ENV_VAR = void 0; - var os_1 = require("os"); - var fs_1 = require("fs"); - var { access, appendFile, writeFile } = fs_1.promises; - exports2.SUMMARY_ENV_VAR = "GITHUB_STEP_SUMMARY"; - exports2.SUMMARY_DOCS_URL = "https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary"; - var Summary = class { - constructor() { - this._buffer = ""; - } - /** - * Finds the summary file path from the environment, rejects if env var is not found or file does not exist - * Also checks r/w permissions. - * - * @returns step summary file path - */ - filePath() { - return __awaiter3(this, void 0, void 0, function* () { - if (this._filePath) { - return this._filePath; - } - const pathFromEnv = process.env[exports2.SUMMARY_ENV_VAR]; - if (!pathFromEnv) { - throw new Error(`Unable to find environment variable for $${exports2.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); - } - try { - yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK); - } catch (_a) { - throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); - } - this._filePath = pathFromEnv; - return this._filePath; - }); - } - /** - * Wraps content in an HTML tag, adding any HTML attributes - * - * @param {string} tag HTML tag to wrap - * @param {string | null} content content within the tag - * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add - * - * @returns {string} content wrapped in HTML element - */ - wrap(tag, content, attrs = {}) { - const htmlAttrs = Object.entries(attrs).map(([key, value]) => ` ${key}="${value}"`).join(""); - if (!content) { - return `<${tag}${htmlAttrs}>`; - } - return `<${tag}${htmlAttrs}>${content}`; - } - /** - * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default. - * - * @param {SummaryWriteOptions} [options] (optional) options for write operation - * - * @returns {Promise} summary instance - */ - write(options) { - return __awaiter3(this, void 0, void 0, function* () { - const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); - const filePath = yield this.filePath(); - const writeFunc = overwrite ? writeFile : appendFile; - yield writeFunc(filePath, this._buffer, { encoding: "utf8" }); - return this.emptyBuffer(); - }); - } - /** - * Clears the summary buffer and wipes the summary file - * - * @returns {Summary} summary instance - */ - clear() { - return __awaiter3(this, void 0, void 0, function* () { - return this.emptyBuffer().write({ overwrite: true }); - }); - } - /** - * Returns the current summary buffer as a string - * - * @returns {string} string of summary buffer - */ - stringify() { - return this._buffer; - } - /** - * If the summary buffer is empty - * - * @returns {boolen} true if the buffer is empty - */ - isEmptyBuffer() { - return this._buffer.length === 0; - } - /** - * Resets the summary buffer without writing to summary file - * - * @returns {Summary} summary instance - */ - emptyBuffer() { - this._buffer = ""; - return this; - } - /** - * Adds raw text to the summary buffer - * - * @param {string} text content to add - * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false) - * - * @returns {Summary} summary instance - */ - addRaw(text, addEOL = false) { - this._buffer += text; - return addEOL ? this.addEOL() : this; - } - /** - * Adds the operating system-specific end-of-line marker to the buffer - * - * @returns {Summary} summary instance - */ - addEOL() { - return this.addRaw(os_1.EOL); - } - /** - * Adds an HTML codeblock to the summary buffer - * - * @param {string} code content to render within fenced code block - * @param {string} lang (optional) language to syntax highlight code - * - * @returns {Summary} summary instance - */ - addCodeBlock(code, lang) { - const attrs = Object.assign({}, lang && { lang }); - const element = this.wrap("pre", this.wrap("code", code), attrs); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML list to the summary buffer - * - * @param {string[]} items list of items to render - * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false) - * - * @returns {Summary} summary instance - */ - addList(items, ordered = false) { - const tag = ordered ? "ol" : "ul"; - const listItems = items.map((item) => this.wrap("li", item)).join(""); - const element = this.wrap(tag, listItems); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML table to the summary buffer - * - * @param {SummaryTableCell[]} rows table rows - * - * @returns {Summary} summary instance - */ - addTable(rows) { - const tableBody = rows.map((row) => { - const cells = row.map((cell) => { - if (typeof cell === "string") { - return this.wrap("td", cell); - } - const { header, data, colspan, rowspan } = cell; - const tag = header ? "th" : "td"; - const attrs = Object.assign(Object.assign({}, colspan && { colspan }), rowspan && { rowspan }); - return this.wrap(tag, data, attrs); - }).join(""); - return this.wrap("tr", cells); - }).join(""); - const element = this.wrap("table", tableBody); - return this.addRaw(element).addEOL(); - } - /** - * Adds a collapsable HTML details element to the summary buffer - * - * @param {string} label text for the closed state - * @param {string} content collapsable content - * - * @returns {Summary} summary instance - */ - addDetails(label, content) { - const element = this.wrap("details", this.wrap("summary", label) + content); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML image tag to the summary buffer - * - * @param {string} src path to the image you to embed - * @param {string} alt text description of the image - * @param {SummaryImageOptions} options (optional) addition image attributes - * - * @returns {Summary} summary instance - */ - addImage(src, alt, options) { - const { width, height } = options || {}; - const attrs = Object.assign(Object.assign({}, width && { width }), height && { height }); - const element = this.wrap("img", null, Object.assign({ src, alt }, attrs)); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML section heading element - * - * @param {string} text heading text - * @param {number | string} [level=1] (optional) the heading level, default: 1 - * - * @returns {Summary} summary instance - */ - addHeading(text, level) { - const tag = `h${level}`; - const allowedTag = ["h1", "h2", "h3", "h4", "h5", "h6"].includes(tag) ? tag : "h1"; - const element = this.wrap(allowedTag, text); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML thematic break (
) to the summary buffer - * - * @returns {Summary} summary instance - */ - addSeparator() { - const element = this.wrap("hr", null); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML line break (
) to the summary buffer - * - * @returns {Summary} summary instance - */ - addBreak() { - const element = this.wrap("br", null); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML blockquote to the summary buffer - * - * @param {string} text quote text - * @param {string} cite (optional) citation url - * - * @returns {Summary} summary instance - */ - addQuote(text, cite) { - const attrs = Object.assign({}, cite && { cite }); - const element = this.wrap("blockquote", text, attrs); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML anchor tag to the summary buffer - * - * @param {string} text link text/content - * @param {string} href hyperlink - * - * @returns {Summary} summary instance - */ - addLink(text, href) { - const element = this.wrap("a", text, { href }); - return this.addRaw(element).addEOL(); - } + } +}); + +// node_modules/asn1/lib/ber/types.js +var require_types = __commonJS({ + "node_modules/asn1/lib/ber/types.js"(exports2, module2) { + module2.exports = { + EOC: 0, + Boolean: 1, + Integer: 2, + BitString: 3, + OctetString: 4, + Null: 5, + OID: 6, + ObjectDescriptor: 7, + External: 8, + Real: 9, + // float + Enumeration: 10, + PDV: 11, + Utf8String: 12, + RelativeOID: 13, + Sequence: 16, + Set: 17, + NumericString: 18, + PrintableString: 19, + T61String: 20, + VideotexString: 21, + IA5String: 22, + UTCTime: 23, + GeneralizedTime: 24, + GraphicString: 25, + VisibleString: 26, + GeneralString: 28, + UniversalString: 29, + CharacterString: 30, + BMPString: 31, + Constructor: 32, + Context: 128 }; - var _summary = new Summary(); - exports2.markdownSummary = _summary; - exports2.summary = _summary; } }); -// node_modules/@actions/core/lib/path-utils.js -var require_path_utils = __commonJS({ - "node_modules/@actions/core/lib/path-utils.js"(exports2) { +// node_modules/safer-buffer/safer.js +var require_safer = __commonJS({ + "node_modules/safer-buffer/safer.js"(exports2, module2) { "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - 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 ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); + var buffer = require("buffer"); + var Buffer2 = buffer.Buffer; + var safer = {}; + var key; + for (key in buffer) { + if (!buffer.hasOwnProperty(key)) continue; + if (key === "SlowBuffer" || key === "Buffer") continue; + safer[key] = buffer[key]; + } + var Safer = safer.Buffer = {}; + for (key in Buffer2) { + if (!Buffer2.hasOwnProperty(key)) continue; + if (key === "allocUnsafe" || key === "allocUnsafeSlow") continue; + Safer[key] = Buffer2[key]; + } + safer.Buffer.prototype = Buffer2.prototype; + if (!Safer.from || Safer.from === Uint8Array.from) { + Safer.from = function(value, encodingOrOffset, length) { + if (typeof value === "number") { + throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value); + } + if (value && typeof value.length === "undefined") { + throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value); + } + return Buffer2(value, encodingOrOffset, length); }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + } + if (!Safer.alloc) { + Safer.alloc = function(size, fill, encoding) { + if (typeof size !== "number") { + throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size); } - __setModuleDefault(result, mod); - return result; + if (size < 0 || size >= 2 * (1 << 30)) { + throw new RangeError('The value "' + size + '" is invalid for option "size"'); + } + var buf = Buffer2(size); + if (!fill || fill.length === 0) { + buf.fill(0); + } else if (typeof encoding === "string") { + buf.fill(fill, encoding); + } else { + buf.fill(fill); + } + return buf; }; - })(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.toPosixPath = toPosixPath; - exports2.toWin32Path = toWin32Path; - exports2.toPlatformPath = toPlatformPath; - var path = __importStar(require("path")); - function toPosixPath(pth) { - return pth.replace(/[\\]/g, "/"); } - function toWin32Path(pth) { - return pth.replace(/[/]/g, "\\"); + if (!safer.kStringMaxLength) { + try { + safer.kStringMaxLength = process.binding("buffer").kStringMaxLength; + } catch (e) { + } } - function toPlatformPath(pth) { - return pth.replace(/[/\\]/g, path.sep); + if (!safer.constants) { + safer.constants = { + MAX_LENGTH: safer.kMaxLength + }; + if (safer.kStringMaxLength) { + safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength; + } } + module2.exports = safer; } }); -// node_modules/@actions/io/lib/io-util.js -var require_io_util = __commonJS({ - "node_modules/@actions/io/lib/io-util.js"(exports2) { - "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; +// node_modules/asn1/lib/ber/reader.js +var require_reader = __commonJS({ + "node_modules/asn1/lib/ber/reader.js"(exports2, module2) { + var assert = require("assert"); + var Buffer2 = require_safer().Buffer; + var ASN1 = require_types(); + var errors = require_errors2(); + var newInvalidAsn1Error = errors.newInvalidAsn1Error; + function Reader(data) { + if (!data || !Buffer2.isBuffer(data)) + throw new TypeError("data must be a node Buffer"); + this._buf = data; + this._size = data.length; + this._len = 0; + this._offset = 0; + } + Object.defineProperty(Reader.prototype, "length", { + enumerable: true, + get: function() { + return this._len; } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - 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 ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - } - __setModuleDefault(result, mod); - return result; - }; - })(); - var __awaiter3 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); + Object.defineProperty(Reader.prototype, "offset", { + enumerable: true, + get: function() { + return this._offset; } - return new (P || (P = 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 _a; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.READONLY = exports2.UV_FS_O_EXLOCK = exports2.IS_WINDOWS = exports2.unlink = exports2.symlink = exports2.stat = exports2.rmdir = exports2.rm = exports2.rename = exports2.readdir = exports2.open = exports2.mkdir = exports2.lstat = exports2.copyFile = exports2.chmod = void 0; - exports2.readlink = readlink; - exports2.exists = exists; - exports2.isDirectory = isDirectory; - exports2.isRooted = isRooted; - exports2.tryGetExecutablePath = tryGetExecutablePath; - exports2.getCmdPath = getCmdPath; - var fs3 = __importStar(require("fs")); - var path = __importStar(require("path")); - _a = fs3.promises, exports2.chmod = _a.chmod, exports2.copyFile = _a.copyFile, exports2.lstat = _a.lstat, exports2.mkdir = _a.mkdir, exports2.open = _a.open, exports2.readdir = _a.readdir, exports2.rename = _a.rename, exports2.rm = _a.rm, exports2.rmdir = _a.rmdir, exports2.stat = _a.stat, exports2.symlink = _a.symlink, exports2.unlink = _a.unlink; - exports2.IS_WINDOWS = process.platform === "win32"; - function readlink(fsPath) { - return __awaiter3(this, void 0, void 0, function* () { - const result = yield fs3.promises.readlink(fsPath); - if (exports2.IS_WINDOWS && !result.endsWith("\\")) { - return `${result}\\`; - } - return result; - }); - } - exports2.UV_FS_O_EXLOCK = 268435456; - exports2.READONLY = fs3.constants.O_RDONLY; - function exists(fsPath) { - return __awaiter3(this, void 0, void 0, function* () { - try { - yield (0, exports2.stat)(fsPath); - } catch (err) { - if (err.code === "ENOENT") { - return false; - } - throw err; - } - return true; - }); - } - function isDirectory(fsPath_1) { - return __awaiter3(this, arguments, void 0, function* (fsPath, useStat = false) { - const stats = useStat ? yield (0, exports2.stat)(fsPath) : yield (0, exports2.lstat)(fsPath); - return stats.isDirectory(); - }); - } - function isRooted(p) { - p = normalizeSeparators(p); - if (!p) { - throw new Error('isRooted() parameter "p" cannot be empty'); + }); + Object.defineProperty(Reader.prototype, "remain", { + get: function() { + return this._size - this._offset; } - if (exports2.IS_WINDOWS) { - return p.startsWith("\\") || /^[A-Z]:/i.test(p); + }); + Object.defineProperty(Reader.prototype, "buffer", { + get: function() { + return this._buf.slice(this._offset); } - return p.startsWith("/"); - } - function tryGetExecutablePath(filePath, extensions) { - return __awaiter3(this, void 0, void 0, function* () { - let stats = void 0; - try { - stats = yield (0, exports2.stat)(filePath); - } catch (err) { - if (err.code !== "ENOENT") { - console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); - } - } - if (stats && stats.isFile()) { - if (exports2.IS_WINDOWS) { - const upperExt = path.extname(filePath).toUpperCase(); - if (extensions.some((validExt) => validExt.toUpperCase() === upperExt)) { - return filePath; - } - } else { - if (isUnixExecutable(stats)) { - return filePath; - } - } - } - const originalFilePath = filePath; - for (const extension of extensions) { - filePath = originalFilePath + extension; - stats = void 0; - try { - stats = yield (0, exports2.stat)(filePath); - } catch (err) { - if (err.code !== "ENOENT") { - console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); - } - } - if (stats && stats.isFile()) { - if (exports2.IS_WINDOWS) { - try { - const directory = path.dirname(filePath); - const upperName = path.basename(filePath).toUpperCase(); - for (const actualName of yield (0, exports2.readdir)(directory)) { - if (upperName === actualName.toUpperCase()) { - filePath = path.join(directory, actualName); - break; - } - } - } catch (err) { - console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`); - } - return filePath; - } else { - if (isUnixExecutable(stats)) { - return filePath; - } - } - } + }); + Reader.prototype.readByte = function(peek) { + if (this._size - this._offset < 1) + return null; + var b = this._buf[this._offset] & 255; + if (!peek) + this._offset += 1; + return b; + }; + Reader.prototype.peek = function() { + return this.readByte(true); + }; + Reader.prototype.readLength = function(offset) { + if (offset === void 0) + offset = this._offset; + if (offset >= this._size) + return null; + var lenB = this._buf[offset++] & 255; + if (lenB === null) + return null; + if ((lenB & 128) === 128) { + lenB &= 127; + if (lenB === 0) + throw newInvalidAsn1Error("Indefinite length not supported"); + if (lenB > 4) + throw newInvalidAsn1Error("encoding too long"); + if (this._size - offset < lenB) + return null; + this._len = 0; + for (var i = 0; i < lenB; i++) + this._len = (this._len << 8) + (this._buf[offset++] & 255); + } else { + this._len = lenB; + } + return offset; + }; + Reader.prototype.readSequence = function(tag) { + var seq = this.peek(); + if (seq === null) + return null; + if (tag !== void 0 && tag !== seq) + throw newInvalidAsn1Error("Expected 0x" + tag.toString(16) + ": got 0x" + seq.toString(16)); + var o = this.readLength(this._offset + 1); + if (o === null) + return null; + this._offset = o; + return seq; + }; + Reader.prototype.readInt = function() { + return this._readTag(ASN1.Integer); + }; + Reader.prototype.readBoolean = function() { + return this._readTag(ASN1.Boolean) === 0 ? false : true; + }; + Reader.prototype.readEnumeration = function() { + return this._readTag(ASN1.Enumeration); + }; + Reader.prototype.readString = function(tag, retbuf) { + if (!tag) + tag = ASN1.OctetString; + var b = this.peek(); + if (b === null) + return null; + if (b !== tag) + throw newInvalidAsn1Error("Expected 0x" + tag.toString(16) + ": got 0x" + b.toString(16)); + var o = this.readLength(this._offset + 1); + if (o === null) + return null; + if (this.length > this._size - o) + return null; + this._offset = o; + if (this.length === 0) + return retbuf ? Buffer2.alloc(0) : ""; + var str = this._buf.slice(this._offset, this._offset + this.length); + this._offset += this.length; + return retbuf ? str : str.toString("utf8"); + }; + Reader.prototype.readOID = function(tag) { + if (!tag) + tag = ASN1.OID; + var b = this.readString(tag, true); + if (b === null) + return null; + var values = []; + var value = 0; + for (var i = 0; i < b.length; i++) { + var byte = b[i] & 255; + value <<= 7; + value += byte & 127; + if ((byte & 128) === 0) { + values.push(value); + value = 0; } - return ""; - }); - } - function normalizeSeparators(p) { - p = p || ""; - if (exports2.IS_WINDOWS) { - p = p.replace(/\//g, "\\"); - return p.replace(/\\\\+/g, "\\"); } - return p.replace(/\/\/+/g, "/"); - } - function isUnixExecutable(stats) { - return (stats.mode & 1) > 0 || (stats.mode & 8) > 0 && process.getgid !== void 0 && stats.gid === process.getgid() || (stats.mode & 64) > 0 && process.getuid !== void 0 && stats.uid === process.getuid(); - } - function getCmdPath() { - var _a2; - return (_a2 = process.env["COMSPEC"]) !== null && _a2 !== void 0 ? _a2 : `cmd.exe`; - } + value = values.shift(); + values.unshift(value % 40); + values.unshift(value / 40 >> 0); + return values.join("."); + }; + Reader.prototype._readTag = function(tag) { + assert.ok(tag !== void 0); + var b = this.peek(); + if (b === null) + return null; + if (b !== tag) + throw newInvalidAsn1Error("Expected 0x" + tag.toString(16) + ": got 0x" + b.toString(16)); + var o = this.readLength(this._offset + 1); + if (o === null) + return null; + if (this.length > 4) + throw newInvalidAsn1Error("Integer too long: " + this.length); + if (this.length > this._size - o) + return null; + this._offset = o; + var fb = this._buf[this._offset]; + var value = 0; + for (var i = 0; i < this.length; i++) { + value <<= 8; + value |= this._buf[this._offset++] & 255; + } + if ((fb & 128) === 128 && i !== 4) + value -= 1 << i * 8; + return value >> 0; + }; + module2.exports = Reader; } }); -// node_modules/@actions/io/lib/io.js -var require_io = __commonJS({ - "node_modules/@actions/io/lib/io.js"(exports2) { - "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - 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 ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - } - __setModuleDefault(result, mod); - return result; - }; - })(); - var __awaiter3 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); - } - return new (P || (P = 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()); - }); +// node_modules/asn1/lib/ber/writer.js +var require_writer = __commonJS({ + "node_modules/asn1/lib/ber/writer.js"(exports2, module2) { + var assert = require("assert"); + var Buffer2 = require_safer().Buffer; + var ASN1 = require_types(); + var errors = require_errors2(); + var newInvalidAsn1Error = errors.newInvalidAsn1Error; + var DEFAULT_OPTS = { + size: 1024, + growthFactor: 8 }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.cp = cp; - exports2.mv = mv; - exports2.rmRF = rmRF; - exports2.mkdirP = mkdirP; - exports2.which = which; - exports2.findInPath = findInPath; - var assert_1 = require("assert"); - var path = __importStar(require("path")); - var ioUtil = __importStar(require_io_util()); - function cp(source_1, dest_1) { - return __awaiter3(this, arguments, void 0, function* (source, dest, options = {}) { - const { force, recursive, copySourceDirectory } = readCopyOptions(options); - const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null; - if (destStat && destStat.isFile() && !force) { - return; - } - const newDest = destStat && destStat.isDirectory() && copySourceDirectory ? path.join(dest, path.basename(source)) : dest; - if (!(yield ioUtil.exists(source))) { - throw new Error(`no such file or directory: ${source}`); - } - const sourceStat = yield ioUtil.stat(source); - if (sourceStat.isDirectory()) { - if (!recursive) { - throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`); - } else { - yield cpDirRecursive(source, newDest, 0, force); - } - } else { - if (path.relative(source, newDest) === "") { - throw new Error(`'${newDest}' and '${source}' are the same file`); - } - yield copyFile(source, newDest, force); - } - }); - } - function mv(source_1, dest_1) { - return __awaiter3(this, arguments, void 0, function* (source, dest, options = {}) { - if (yield ioUtil.exists(dest)) { - let destExists = true; - if (yield ioUtil.isDirectory(dest)) { - dest = path.join(dest, path.basename(source)); - destExists = yield ioUtil.exists(dest); - } - if (destExists) { - if (options.force == null || options.force) { - yield rmRF(dest); - } else { - throw new Error("Destination already exists"); - } - } - } - yield mkdirP(path.dirname(dest)); - yield ioUtil.rename(source, dest); - }); - } - function rmRF(inputPath) { - return __awaiter3(this, void 0, void 0, function* () { - if (ioUtil.IS_WINDOWS) { - if (/[*"<>|]/.test(inputPath)) { - throw new Error('File path must not contain `*`, `"`, `<`, `>` or `|` on Windows'); - } - } - try { - yield ioUtil.rm(inputPath, { - force: true, - maxRetries: 3, - recursive: true, - retryDelay: 300 - }); - } catch (err) { - throw new Error(`File was unable to be removed ${err}`); - } - }); - } - function mkdirP(fsPath) { - return __awaiter3(this, void 0, void 0, function* () { - (0, assert_1.ok)(fsPath, "a path argument must be provided"); - yield ioUtil.mkdir(fsPath, { recursive: true }); - }); - } - function which(tool, check) { - return __awaiter3(this, void 0, void 0, function* () { - if (!tool) { - throw new Error("parameter 'tool' is required"); - } - if (check) { - const result = yield which(tool, false); - if (!result) { - if (ioUtil.IS_WINDOWS) { - throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`); - } else { - throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`); - } - } - return result; - } - const matches = yield findInPath(tool); - if (matches && matches.length > 0) { - return matches[0]; - } - return ""; - }); - } - function findInPath(tool) { - return __awaiter3(this, void 0, void 0, function* () { - if (!tool) { - throw new Error("parameter 'tool' is required"); - } - const extensions = []; - if (ioUtil.IS_WINDOWS && process.env["PATHEXT"]) { - for (const extension of process.env["PATHEXT"].split(path.delimiter)) { - if (extension) { - extensions.push(extension); - } - } - } - if (ioUtil.isRooted(tool)) { - const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions); - if (filePath) { - return [filePath]; - } - return []; - } - if (tool.includes(path.sep)) { - return []; - } - const directories = []; - if (process.env.PATH) { - for (const p of process.env.PATH.split(path.delimiter)) { - if (p) { - directories.push(p); - } - } - } - const matches = []; - for (const directory of directories) { - const filePath = yield ioUtil.tryGetExecutablePath(path.join(directory, tool), extensions); - if (filePath) { - matches.push(filePath); - } - } - return matches; - }); - } - function readCopyOptions(options) { - const force = options.force == null ? true : options.force; - const recursive = Boolean(options.recursive); - const copySourceDirectory = options.copySourceDirectory == null ? true : Boolean(options.copySourceDirectory); - return { force, recursive, copySourceDirectory }; - } - function cpDirRecursive(sourceDir, destDir, currentDepth, force) { - return __awaiter3(this, void 0, void 0, function* () { - if (currentDepth >= 255) + function merge2(from, to) { + assert.ok(from); + assert.equal(typeof from, "object"); + assert.ok(to); + assert.equal(typeof to, "object"); + var keys = Object.getOwnPropertyNames(from); + keys.forEach(function(key) { + if (to[key]) return; - currentDepth++; - yield mkdirP(destDir); - const files = yield ioUtil.readdir(sourceDir); - for (const fileName of files) { - const srcFile = `${sourceDir}/${fileName}`; - const destFile = `${destDir}/${fileName}`; - const srcFileStat = yield ioUtil.lstat(srcFile); - if (srcFileStat.isDirectory()) { - yield cpDirRecursive(srcFile, destFile, currentDepth, force); - } else { - yield copyFile(srcFile, destFile, force); - } - } - yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode); + var value = Object.getOwnPropertyDescriptor(from, key); + Object.defineProperty(to, key, value); }); + return to; } - function copyFile(srcFile, destFile, force) { - return __awaiter3(this, void 0, void 0, function* () { - if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) { - try { - yield ioUtil.lstat(destFile); - yield ioUtil.unlink(destFile); - } catch (e) { - if (e.code === "EPERM") { - yield ioUtil.chmod(destFile, "0666"); - yield ioUtil.unlink(destFile); - } - } - const symlinkFull = yield ioUtil.readlink(srcFile); - yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? "junction" : null); - } else if (!(yield ioUtil.exists(destFile)) || force) { - yield ioUtil.copyFile(srcFile, destFile); - } - }); + function Writer(options) { + options = merge2(DEFAULT_OPTS, options || {}); + this._buf = Buffer2.alloc(options.size || 1024); + this._size = this._buf.length; + this._offset = 0; + this._options = options; + this._seq = []; } - } -}); - -// node_modules/@actions/exec/lib/toolrunner.js -var require_toolrunner = __commonJS({ - "node_modules/@actions/exec/lib/toolrunner.js"(exports2) { - "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; + Object.defineProperty(Writer.prototype, "buffer", { + get: function() { + if (this._seq.length) + throw newInvalidAsn1Error(this._seq.length + " unended sequence(s)"); + return this._buf.slice(0, this._offset); } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - 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 ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - } - __setModuleDefault(result, mod); - return result; - }; - })(); - var __awaiter3 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); - } - return new (P || (P = 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()); - }); + Writer.prototype.writeByte = function(b) { + if (typeof b !== "number") + throw new TypeError("argument must be a Number"); + this._ensure(1); + this._buf[this._offset++] = b; }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ToolRunner = void 0; - exports2.argStringToArray = argStringToArray; - var os = __importStar(require("os")); - var events = __importStar(require("events")); - var child = __importStar(require("child_process")); - var path = __importStar(require("path")); - var io = __importStar(require_io()); - var ioUtil = __importStar(require_io_util()); - var timers_1 = require("timers"); - var IS_WINDOWS = process.platform === "win32"; - var ToolRunner = class extends events.EventEmitter { - constructor(toolPath, args, options) { - super(); - if (!toolPath) { - throw new Error("Parameter 'toolPath' cannot be null or empty."); - } - this.toolPath = toolPath; - this.args = args || []; - this.options = options || {}; - } - _debug(message) { - if (this.options.listeners && this.options.listeners.debug) { - this.options.listeners.debug(message); - } - } - _getCommandString(options, noPrefix) { - const toolPath = this._getSpawnFileName(); - const args = this._getSpawnArgs(options); - let cmd = noPrefix ? "" : "[command]"; - if (IS_WINDOWS) { - if (this._isCmdFile()) { - cmd += toolPath; - for (const a of args) { - cmd += ` ${a}`; - } - } else if (options.windowsVerbatimArguments) { - cmd += `"${toolPath}"`; - for (const a of args) { - cmd += ` ${a}`; - } - } else { - cmd += this._windowsQuoteCmdArg(toolPath); - for (const a of args) { - cmd += ` ${this._windowsQuoteCmdArg(a)}`; - } - } - } else { - cmd += toolPath; - for (const a of args) { - cmd += ` ${a}`; - } - } - return cmd; - } - _processLineBuffer(data, strBuffer, onLine) { - try { - let s = strBuffer + data.toString(); - let n = s.indexOf(os.EOL); - while (n > -1) { - const line = s.substring(0, n); - onLine(line); - s = s.substring(n + os.EOL.length); - n = s.indexOf(os.EOL); - } - return s; - } catch (err) { - this._debug(`error processing line. Failed with error ${err}`); - return ""; - } - } - _getSpawnFileName() { - if (IS_WINDOWS) { - if (this._isCmdFile()) { - return process.env["COMSPEC"] || "cmd.exe"; - } - } - return this.toolPath; - } - _getSpawnArgs(options) { - if (IS_WINDOWS) { - if (this._isCmdFile()) { - let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`; - for (const a of this.args) { - argline += " "; - argline += options.windowsVerbatimArguments ? a : this._windowsQuoteCmdArg(a); - } - argline += '"'; - return [argline]; - } - } - return this.args; + Writer.prototype.writeInt = function(i, tag) { + if (typeof i !== "number") + throw new TypeError("argument must be a Number"); + if (typeof tag !== "number") + tag = ASN1.Integer; + var sz = 4; + while (((i & 4286578688) === 0 || (i & 4286578688) === 4286578688 >> 0) && sz > 1) { + sz--; + i <<= 8; } - _endsWith(str, end) { - return str.endsWith(end); + if (sz > 4) + throw newInvalidAsn1Error("BER ints cannot be > 0xffffffff"); + this._ensure(2 + sz); + this._buf[this._offset++] = tag; + this._buf[this._offset++] = sz; + while (sz-- > 0) { + this._buf[this._offset++] = (i & 4278190080) >>> 24; + i <<= 8; } - _isCmdFile() { - const upperToolPath = this.toolPath.toUpperCase(); - return this._endsWith(upperToolPath, ".CMD") || this._endsWith(upperToolPath, ".BAT"); - } - _windowsQuoteCmdArg(arg) { - if (!this._isCmdFile()) { - return this._uvQuoteCmdArg(arg); - } - if (!arg) { - return '""'; - } - const cmdSpecialChars = [ - " ", - " ", - "&", - "(", - ")", - "[", - "]", - "{", - "}", - "^", - "=", - ";", - "!", - "'", - "+", - ",", - "`", - "~", - "|", - "<", - ">", - '"' - ]; - let needsQuotes = false; - for (const char of arg) { - if (cmdSpecialChars.some((x) => x === char)) { - needsQuotes = true; - break; - } - } - if (!needsQuotes) { - return arg; - } - let reverse = '"'; - let quoteHit = true; - for (let i = arg.length; i > 0; i--) { - reverse += arg[i - 1]; - if (quoteHit && arg[i - 1] === "\\") { - reverse += "\\"; - } else if (arg[i - 1] === '"') { - quoteHit = true; - reverse += '"'; - } else { - quoteHit = false; - } - } - reverse += '"'; - return reverse.split("").reverse().join(""); - } - _uvQuoteCmdArg(arg) { - if (!arg) { - return '""'; - } - if (!arg.includes(" ") && !arg.includes(" ") && !arg.includes('"')) { - return arg; - } - if (!arg.includes('"') && !arg.includes("\\")) { - return `"${arg}"`; - } - let reverse = '"'; - let quoteHit = true; - for (let i = arg.length; i > 0; i--) { - reverse += arg[i - 1]; - if (quoteHit && arg[i - 1] === "\\") { - reverse += "\\"; - } else if (arg[i - 1] === '"') { - quoteHit = true; - reverse += "\\"; - } else { - quoteHit = false; - } - } - reverse += '"'; - return reverse.split("").reverse().join(""); - } - _cloneExecOptions(options) { - options = options || {}; - const result = { - cwd: options.cwd || process.cwd(), - env: options.env || process.env, - silent: options.silent || false, - windowsVerbatimArguments: options.windowsVerbatimArguments || false, - failOnStdErr: options.failOnStdErr || false, - ignoreReturnCode: options.ignoreReturnCode || false, - delay: options.delay || 1e4 - }; - result.outStream = options.outStream || process.stdout; - result.errStream = options.errStream || process.stderr; - return result; - } - _getSpawnOptions(options, toolPath) { - options = options || {}; - const result = {}; - result.cwd = options.cwd; - result.env = options.env; - result["windowsVerbatimArguments"] = options.windowsVerbatimArguments || this._isCmdFile(); - if (options.windowsVerbatimArguments) { - result.argv0 = `"${toolPath}"`; - } - return result; - } - /** - * Exec a tool. - * Output will be streamed to the live console. - * Returns promise with return code - * - * @param tool path to tool to exec - * @param options optional exec options. See ExecOptions - * @returns number - */ - exec() { - return __awaiter3(this, void 0, void 0, function* () { - if (!ioUtil.isRooted(this.toolPath) && (this.toolPath.includes("/") || IS_WINDOWS && this.toolPath.includes("\\"))) { - this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); - } - this.toolPath = yield io.which(this.toolPath, true); - return new Promise((resolve, reject) => __awaiter3(this, void 0, void 0, function* () { - this._debug(`exec tool: ${this.toolPath}`); - this._debug("arguments:"); - for (const arg of this.args) { - this._debug(` ${arg}`); - } - const optionsNonNull = this._cloneExecOptions(this.options); - if (!optionsNonNull.silent && optionsNonNull.outStream) { - optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL); - } - const state = new ExecState(optionsNonNull, this.toolPath); - state.on("debug", (message) => { - this._debug(message); - }); - if (this.options.cwd && !(yield ioUtil.exists(this.options.cwd))) { - return reject(new Error(`The cwd: ${this.options.cwd} does not exist!`)); - } - const fileName = this._getSpawnFileName(); - const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName)); - let stdbuffer = ""; - if (cp.stdout) { - cp.stdout.on("data", (data) => { - if (this.options.listeners && this.options.listeners.stdout) { - this.options.listeners.stdout(data); - } - if (!optionsNonNull.silent && optionsNonNull.outStream) { - optionsNonNull.outStream.write(data); - } - stdbuffer = this._processLineBuffer(data, stdbuffer, (line) => { - if (this.options.listeners && this.options.listeners.stdline) { - this.options.listeners.stdline(line); - } - }); - }); - } - let errbuffer = ""; - if (cp.stderr) { - cp.stderr.on("data", (data) => { - state.processStderr = true; - if (this.options.listeners && this.options.listeners.stderr) { - this.options.listeners.stderr(data); - } - if (!optionsNonNull.silent && optionsNonNull.errStream && optionsNonNull.outStream) { - const s = optionsNonNull.failOnStdErr ? optionsNonNull.errStream : optionsNonNull.outStream; - s.write(data); - } - errbuffer = this._processLineBuffer(data, errbuffer, (line) => { - if (this.options.listeners && this.options.listeners.errline) { - this.options.listeners.errline(line); - } - }); - }); - } - cp.on("error", (err) => { - state.processError = err.message; - state.processExited = true; - state.processClosed = true; - state.CheckComplete(); - }); - cp.on("exit", (code) => { - state.processExitCode = code; - state.processExited = true; - this._debug(`Exit code ${code} received from tool '${this.toolPath}'`); - state.CheckComplete(); - }); - cp.on("close", (code) => { - state.processExitCode = code; - state.processExited = true; - state.processClosed = true; - this._debug(`STDIO streams have closed for tool '${this.toolPath}'`); - state.CheckComplete(); - }); - state.on("done", (error3, exitCode) => { - if (stdbuffer.length > 0) { - this.emit("stdline", stdbuffer); - } - if (errbuffer.length > 0) { - this.emit("errline", errbuffer); - } - cp.removeAllListeners(); - if (error3) { - reject(error3); - } else { - resolve(exitCode); - } - }); - if (this.options.input) { - if (!cp.stdin) { - throw new Error("child process missing stdin"); - } - cp.stdin.end(this.options.input); - } - })); - }); + }; + Writer.prototype.writeNull = function() { + this.writeByte(ASN1.Null); + this.writeByte(0); + }; + Writer.prototype.writeEnumeration = function(i, tag) { + if (typeof i !== "number") + throw new TypeError("argument must be a Number"); + if (typeof tag !== "number") + tag = ASN1.Enumeration; + return this.writeInt(i, tag); + }; + Writer.prototype.writeBoolean = function(b, tag) { + if (typeof b !== "boolean") + throw new TypeError("argument must be a Boolean"); + if (typeof tag !== "number") + tag = ASN1.Boolean; + this._ensure(3); + this._buf[this._offset++] = tag; + this._buf[this._offset++] = 1; + this._buf[this._offset++] = b ? 255 : 0; + }; + Writer.prototype.writeString = function(s, tag) { + if (typeof s !== "string") + throw new TypeError("argument must be a string (was: " + typeof s + ")"); + if (typeof tag !== "number") + tag = ASN1.OctetString; + var len = Buffer2.byteLength(s); + this.writeByte(tag); + this.writeLength(len); + if (len) { + this._ensure(len); + this._buf.write(s, this._offset); + this._offset += len; } }; - exports2.ToolRunner = ToolRunner; - function argStringToArray(argString) { - const args = []; - let inQuotes = false; - let escaped = false; - let arg = ""; - function append(c) { - if (escaped && c !== '"') { - arg += "\\"; - } - arg += c; - escaped = false; - } - for (let i = 0; i < argString.length; i++) { - const c = argString.charAt(i); - if (c === '"') { - if (!escaped) { - inQuotes = !inQuotes; - } else { - append(c); - } - continue; - } - if (c === "\\" && escaped) { - append(c); - continue; - } - if (c === "\\" && inQuotes) { - escaped = true; - continue; - } - if (c === " " && !inQuotes) { - if (arg.length > 0) { - args.push(arg); - arg = ""; - } - continue; - } - append(c); - } - if (arg.length > 0) { - args.push(arg.trim()); - } - return args; - } - var ExecState = class _ExecState extends events.EventEmitter { - constructor(options, toolPath) { - super(); - this.processClosed = false; - this.processError = ""; - this.processExitCode = 0; - this.processExited = false; - this.processStderr = false; - this.delay = 1e4; - this.done = false; - this.timeout = null; - if (!toolPath) { - throw new Error("toolPath must not be empty"); - } - this.options = options; - this.toolPath = toolPath; - if (options.delay) { - this.delay = options.delay; - } - } - CheckComplete() { - if (this.done) { - return; - } - if (this.processClosed) { - this._setResult(); - } else if (this.processExited) { - this.timeout = (0, timers_1.setTimeout)(_ExecState.HandleTimeout, this.delay, this); + Writer.prototype.writeBuffer = function(buf, tag) { + if (typeof tag !== "number") + throw new TypeError("tag must be a number"); + if (!Buffer2.isBuffer(buf)) + throw new TypeError("argument must be a buffer"); + this.writeByte(tag); + this.writeLength(buf.length); + this._ensure(buf.length); + buf.copy(this._buf, this._offset, 0, buf.length); + this._offset += buf.length; + }; + Writer.prototype.writeStringArray = function(strings) { + if (!strings instanceof Array) + throw new TypeError("argument must be an Array[String]"); + var self2 = this; + strings.forEach(function(s) { + self2.writeString(s); + }); + }; + Writer.prototype.writeOID = function(s, tag) { + if (typeof s !== "string") + throw new TypeError("argument must be a string"); + if (typeof tag !== "number") + tag = ASN1.OID; + if (!/^([0-9]+\.){3,}[0-9]+$/.test(s)) + throw new Error("argument is not a valid OID string"); + function encodeOctet(bytes2, octet) { + if (octet < 128) { + bytes2.push(octet); + } else if (octet < 16384) { + bytes2.push(octet >>> 7 | 128); + bytes2.push(octet & 127); + } else if (octet < 2097152) { + bytes2.push(octet >>> 14 | 128); + bytes2.push((octet >>> 7 | 128) & 255); + bytes2.push(octet & 127); + } else if (octet < 268435456) { + bytes2.push(octet >>> 21 | 128); + bytes2.push((octet >>> 14 | 128) & 255); + bytes2.push((octet >>> 7 | 128) & 255); + bytes2.push(octet & 127); + } else { + bytes2.push((octet >>> 28 | 128) & 255); + bytes2.push((octet >>> 21 | 128) & 255); + bytes2.push((octet >>> 14 | 128) & 255); + bytes2.push((octet >>> 7 | 128) & 255); + bytes2.push(octet & 127); } } - _debug(message) { - this.emit("debug", message); + var tmp = s.split("."); + var bytes = []; + bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10)); + tmp.slice(2).forEach(function(b) { + encodeOctet(bytes, parseInt(b, 10)); + }); + var self2 = this; + this._ensure(2 + bytes.length); + this.writeByte(tag); + this.writeLength(bytes.length); + bytes.forEach(function(b) { + self2.writeByte(b); + }); + }; + Writer.prototype.writeLength = function(len) { + if (typeof len !== "number") + throw new TypeError("argument must be a Number"); + this._ensure(4); + if (len <= 127) { + this._buf[this._offset++] = len; + } else if (len <= 255) { + this._buf[this._offset++] = 129; + this._buf[this._offset++] = len; + } else if (len <= 65535) { + this._buf[this._offset++] = 130; + this._buf[this._offset++] = len >> 8; + this._buf[this._offset++] = len; + } else if (len <= 16777215) { + this._buf[this._offset++] = 131; + this._buf[this._offset++] = len >> 16; + this._buf[this._offset++] = len >> 8; + this._buf[this._offset++] = len; + } else { + throw newInvalidAsn1Error("Length too long (> 4 bytes)"); } - _setResult() { - let error3; - if (this.processExited) { - if (this.processError) { - error3 = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`); - } else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) { - error3 = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`); - } else if (this.processStderr && this.options.failOnStdErr) { - error3 = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`); - } - } - if (this.timeout) { - clearTimeout(this.timeout); - this.timeout = null; - } - this.done = true; - this.emit("done", error3, this.processExitCode); + }; + Writer.prototype.startSequence = function(tag) { + if (typeof tag !== "number") + tag = ASN1.Sequence | ASN1.Constructor; + this.writeByte(tag); + this._seq.push(this._offset); + this._ensure(3); + this._offset += 3; + }; + Writer.prototype.endSequence = function() { + var seq = this._seq.pop(); + var start = seq + 3; + var len = this._offset - start; + if (len <= 127) { + this._shift(start, len, -2); + this._buf[seq] = len; + } else if (len <= 255) { + this._shift(start, len, -1); + this._buf[seq] = 129; + this._buf[seq + 1] = len; + } else if (len <= 65535) { + this._buf[seq] = 130; + this._buf[seq + 1] = len >> 8; + this._buf[seq + 2] = len; + } else if (len <= 16777215) { + this._shift(start, len, 1); + this._buf[seq] = 131; + this._buf[seq + 1] = len >> 16; + this._buf[seq + 2] = len >> 8; + this._buf[seq + 3] = len; + } else { + throw newInvalidAsn1Error("Sequence too long"); } - static HandleTimeout(state) { - if (state.done) { - return; - } - if (!state.processClosed && state.processExited) { - const message = `The STDIO streams did not close within ${state.delay / 1e3} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`; - state._debug(message); - } - state._setResult(); + }; + Writer.prototype._shift = function(start, len, shift) { + assert.ok(start !== void 0); + assert.ok(len !== void 0); + assert.ok(shift); + this._buf.copy(this._buf, start + shift, start, start + len); + this._offset += shift; + }; + Writer.prototype._ensure = function(len) { + assert.ok(len); + if (this._size - this._offset < len) { + var sz = this._size * this._options.growthFactor; + if (sz - this._offset < len) + sz += len; + var buf = Buffer2.alloc(sz); + this._buf.copy(buf, 0, 0, this._offset); + this._buf = buf; + this._size = sz; } }; + module2.exports = Writer; } }); -// node_modules/@actions/exec/lib/exec.js -var require_exec = __commonJS({ - "node_modules/@actions/exec/lib/exec.js"(exports2) { - "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - 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 ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - } - __setModuleDefault(result, mod); - return result; - }; - })(); - var __awaiter3 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); - } - return new (P || (P = 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()); - }); +// node_modules/asn1/lib/ber/index.js +var require_ber = __commonJS({ + "node_modules/asn1/lib/ber/index.js"(exports2, module2) { + var errors = require_errors2(); + var types = require_types(); + var Reader = require_reader(); + var Writer = require_writer(); + module2.exports = { + Reader, + Writer }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.exec = exec; - exports2.getExecOutput = getExecOutput; - var string_decoder_1 = require("string_decoder"); - var tr = __importStar(require_toolrunner()); - function exec(commandLine, args, options) { - return __awaiter3(this, void 0, void 0, function* () { - const commandArgs = tr.argStringToArray(commandLine); - if (commandArgs.length === 0) { - throw new Error(`Parameter 'commandLine' cannot be null or empty.`); - } - const toolPath = commandArgs[0]; - args = commandArgs.slice(1).concat(args || []); - const runner = new tr.ToolRunner(toolPath, args, options); - return runner.exec(); - }); + for (t in types) { + if (types.hasOwnProperty(t)) + module2.exports[t] = types[t]; } - function getExecOutput(commandLine, args, options) { - return __awaiter3(this, void 0, void 0, function* () { - var _a, _b; - let stdout = ""; - let stderr = ""; - const stdoutDecoder = new string_decoder_1.StringDecoder("utf8"); - const stderrDecoder = new string_decoder_1.StringDecoder("utf8"); - const originalStdoutListener = (_a = options === null || options === void 0 ? void 0 : options.listeners) === null || _a === void 0 ? void 0 : _a.stdout; - const originalStdErrListener = (_b = options === null || options === void 0 ? void 0 : options.listeners) === null || _b === void 0 ? void 0 : _b.stderr; - const stdErrListener = (data) => { - stderr += stderrDecoder.write(data); - if (originalStdErrListener) { - originalStdErrListener(data); - } - }; - const stdOutListener = (data) => { - stdout += stdoutDecoder.write(data); - if (originalStdoutListener) { - originalStdoutListener(data); - } - }; - const listeners = Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.listeners), { stdout: stdOutListener, stderr: stdErrListener }); - const exitCode = yield exec(commandLine, args, Object.assign(Object.assign({}, options), { listeners })); - stdout += stdoutDecoder.end(); - stderr += stderrDecoder.end(); - return { - exitCode, - stdout, - stderr - }; - }); + var t; + for (e in errors) { + if (errors.hasOwnProperty(e)) + module2.exports[e] = errors[e]; } + var e; } }); -// node_modules/@actions/core/lib/platform.js -var require_platform = __commonJS({ - "node_modules/@actions/core/lib/platform.js"(exports2) { - "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - 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 ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - } - __setModuleDefault(result, mod); - return result; - }; - })(); - var __awaiter3 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); - } - return new (P || (P = 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 __importDefault = exports2 && exports2.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; +// node_modules/asn1/lib/index.js +var require_lib2 = __commonJS({ + "node_modules/asn1/lib/index.js"(exports2, module2) { + var Ber = require_ber(); + module2.exports = { + Ber, + BerReader: Ber.Reader, + BerWriter: Ber.Writer }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isLinux = exports2.isMacOS = exports2.isWindows = exports2.arch = exports2.platform = void 0; - exports2.getDetails = getDetails; - var os_1 = __importDefault(require("os")); - var exec = __importStar(require_exec()); - var getWindowsInfo = () => __awaiter3(void 0, void 0, void 0, function* () { - const { stdout: version } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Version"', void 0, { - silent: true - }); - const { stdout: name } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Caption"', void 0, { - silent: true - }); - return { - name: name.trim(), - version: version.trim() - }; - }); - var getMacOsInfo = () => __awaiter3(void 0, void 0, void 0, function* () { - var _a, _b, _c, _d; - const { stdout } = yield exec.getExecOutput("sw_vers", void 0, { - silent: true - }); - const version = (_b = (_a = stdout.match(/ProductVersion:\s*(.+)/)) === null || _a === void 0 ? void 0 : _a[1]) !== null && _b !== void 0 ? _b : ""; - const name = (_d = (_c = stdout.match(/ProductName:\s*(.+)/)) === null || _c === void 0 ? void 0 : _c[1]) !== null && _d !== void 0 ? _d : ""; - return { - name, - version - }; - }); - var getLinuxInfo = () => __awaiter3(void 0, void 0, void 0, function* () { - const { stdout } = yield exec.getExecOutput("lsb_release", ["-i", "-r", "-s"], { - silent: true - }); - const [name, version] = stdout.trim().split("\n"); - return { - name, - version - }; - }); - exports2.platform = os_1.default.platform(); - exports2.arch = os_1.default.arch(); - exports2.isWindows = exports2.platform === "win32"; - exports2.isMacOS = exports2.platform === "darwin"; - exports2.isLinux = exports2.platform === "linux"; - function getDetails() { - return __awaiter3(this, void 0, void 0, function* () { - return Object.assign(Object.assign({}, yield exports2.isWindows ? getWindowsInfo() : exports2.isMacOS ? getMacOsInfo() : getLinuxInfo()), { - platform: exports2.platform, - arch: exports2.arch, - isWindows: exports2.isWindows, - isMacOS: exports2.isMacOS, - isLinux: exports2.isLinux - }); - }); - } } }); -// node_modules/@actions/core/lib/core.js -var require_core = __commonJS({ - "node_modules/@actions/core/lib/core.js"(exports2) { - "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - 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 ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); +// node_modules/tweetnacl/nacl-fast.js +var require_nacl_fast = __commonJS({ + "node_modules/tweetnacl/nacl-fast.js"(exports2, module2) { + (function(nacl) { + "use strict"; + var gf = function(init) { + var i, r = new Float64Array(16); + if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; + return r; }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - } - __setModuleDefault(result, mod); - return result; + var randombytes = function() { + throw new Error("no PRNG"); }; - })(); - var __awaiter3 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); - } - return new (P || (P = 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.platform = exports2.toPlatformPath = exports2.toWin32Path = exports2.toPosixPath = exports2.markdownSummary = exports2.summary = exports2.ExitCode = void 0; - exports2.exportVariable = exportVariable; - exports2.setSecret = setSecret3; - exports2.addPath = addPath; - exports2.getInput = getInput; - exports2.getMultilineInput = getMultilineInput; - exports2.getBooleanInput = getBooleanInput; - exports2.setOutput = setOutput; - exports2.setCommandEcho = setCommandEcho; - exports2.setFailed = setFailed3; - exports2.isDebug = isDebug; - exports2.debug = debug2; - exports2.error = error3; - exports2.warning = warning5; - exports2.notice = notice; - exports2.info = info8; - exports2.startGroup = startGroup2; - exports2.endGroup = endGroup2; - exports2.group = group; - exports2.saveState = saveState; - exports2.getState = getState; - exports2.getIDToken = getIDToken; - var command_1 = require_command(); - var file_command_1 = require_file_command(); - var utils_1 = require_utils(); - var os = __importStar(require("os")); - var path = __importStar(require("path")); - var oidc_utils_1 = require_oidc_utils(); - var ExitCode; - (function(ExitCode2) { - ExitCode2[ExitCode2["Success"] = 0] = "Success"; - ExitCode2[ExitCode2["Failure"] = 1] = "Failure"; - })(ExitCode || (exports2.ExitCode = ExitCode = {})); - function exportVariable(name, val) { - const convertedVal = (0, utils_1.toCommandValue)(val); - process.env[name] = convertedVal; - const filePath = process.env["GITHUB_ENV"] || ""; - if (filePath) { - return (0, file_command_1.issueFileCommand)("ENV", (0, file_command_1.prepareKeyValueMessage)(name, val)); - } - (0, command_1.issueCommand)("set-env", { name }, convertedVal); - } - function setSecret3(secret) { - (0, command_1.issueCommand)("add-mask", {}, secret); - } - function addPath(inputPath) { - const filePath = process.env["GITHUB_PATH"] || ""; - if (filePath) { - (0, file_command_1.issueFileCommand)("PATH", inputPath); - } else { - (0, command_1.issueCommand)("add-path", {}, inputPath); - } - process.env["PATH"] = `${inputPath}${path.delimiter}${process.env["PATH"]}`; - } - function getInput(name, options) { - const val = process.env[`INPUT_${name.replace(/ /g, "_").toUpperCase()}`] || ""; - if (options && options.required && !val) { - throw new Error(`Input required and not supplied: ${name}`); + var _0 = new Uint8Array(16); + var _9 = new Uint8Array(32); + _9[0] = 9; + var gf0 = gf(), gf1 = gf([1]), _121665 = gf([56129, 1]), D = gf([30883, 4953, 19914, 30187, 55467, 16705, 2637, 112, 59544, 30585, 16505, 36039, 65139, 11119, 27886, 20995]), D2 = gf([61785, 9906, 39828, 60374, 45398, 33411, 5274, 224, 53552, 61171, 33010, 6542, 64743, 22239, 55772, 9222]), X = gf([54554, 36645, 11616, 51542, 42930, 38181, 51040, 26924, 56412, 64982, 57905, 49316, 21502, 52590, 14035, 8553]), Y = gf([26200, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214]), I = gf([41136, 18958, 6951, 50414, 58488, 44335, 6150, 12099, 55207, 15867, 153, 11085, 57099, 20417, 9344, 11139]); + function ts64(x, i, h, l) { + x[i] = h >> 24 & 255; + x[i + 1] = h >> 16 & 255; + x[i + 2] = h >> 8 & 255; + x[i + 3] = h & 255; + x[i + 4] = l >> 24 & 255; + x[i + 5] = l >> 16 & 255; + x[i + 6] = l >> 8 & 255; + x[i + 7] = l & 255; } - if (options && options.trimWhitespace === false) { - return val; + function vn(x, xi, y, yi, n) { + var i, d = 0; + for (i = 0; i < n; i++) d |= x[xi + i] ^ y[yi + i]; + return (1 & d - 1 >>> 8) - 1; } - return val.trim(); - } - function getMultilineInput(name, options) { - const inputs = getInput(name, options).split("\n").filter((x) => x !== ""); - if (options && options.trimWhitespace === false) { - return inputs; + function crypto_verify_16(x, xi, y, yi) { + return vn(x, xi, y, yi, 16); } - return inputs.map((input) => input.trim()); - } - function getBooleanInput(name, options) { - const trueValue = ["true", "True", "TRUE"]; - const falseValue = ["false", "False", "FALSE"]; - const val = getInput(name, options); - if (trueValue.includes(val)) - return true; - if (falseValue.includes(val)) - return false; - throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name} -Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); - } - function setOutput(name, value) { - const filePath = process.env["GITHUB_OUTPUT"] || ""; - if (filePath) { - return (0, file_command_1.issueFileCommand)("OUTPUT", (0, file_command_1.prepareKeyValueMessage)(name, value)); + function crypto_verify_32(x, xi, y, yi) { + return vn(x, xi, y, yi, 32); } - process.stdout.write(os.EOL); - (0, command_1.issueCommand)("set-output", { name }, (0, utils_1.toCommandValue)(value)); - } - function setCommandEcho(enabled) { - (0, command_1.issue)("echo", enabled ? "on" : "off"); - } - function setFailed3(message) { - process.exitCode = ExitCode.Failure; - error3(message); - } - function isDebug() { - return process.env["RUNNER_DEBUG"] === "1"; - } - function debug2(message) { - (0, command_1.issueCommand)("debug", {}, message); - } - function error3(message, properties = {}) { - (0, command_1.issueCommand)("error", (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); - } - function warning5(message, properties = {}) { - (0, command_1.issueCommand)("warning", (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); - } - function notice(message, properties = {}) { - (0, command_1.issueCommand)("notice", (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); - } - function info8(message) { - process.stdout.write(message + os.EOL); - } - function startGroup2(name) { - (0, command_1.issue)("group", name); - } - function endGroup2() { - (0, command_1.issue)("endgroup"); - } - function group(name, fn) { - return __awaiter3(this, void 0, void 0, function* () { - startGroup2(name); - let result; - try { - result = yield fn(); - } finally { - endGroup2(); + function core_salsa20(o, p, k, c) { + var j0 = c[0] & 255 | (c[1] & 255) << 8 | (c[2] & 255) << 16 | (c[3] & 255) << 24, j1 = k[0] & 255 | (k[1] & 255) << 8 | (k[2] & 255) << 16 | (k[3] & 255) << 24, j2 = k[4] & 255 | (k[5] & 255) << 8 | (k[6] & 255) << 16 | (k[7] & 255) << 24, j3 = k[8] & 255 | (k[9] & 255) << 8 | (k[10] & 255) << 16 | (k[11] & 255) << 24, j4 = k[12] & 255 | (k[13] & 255) << 8 | (k[14] & 255) << 16 | (k[15] & 255) << 24, j5 = c[4] & 255 | (c[5] & 255) << 8 | (c[6] & 255) << 16 | (c[7] & 255) << 24, j6 = p[0] & 255 | (p[1] & 255) << 8 | (p[2] & 255) << 16 | (p[3] & 255) << 24, j7 = p[4] & 255 | (p[5] & 255) << 8 | (p[6] & 255) << 16 | (p[7] & 255) << 24, j8 = p[8] & 255 | (p[9] & 255) << 8 | (p[10] & 255) << 16 | (p[11] & 255) << 24, j9 = p[12] & 255 | (p[13] & 255) << 8 | (p[14] & 255) << 16 | (p[15] & 255) << 24, j10 = c[8] & 255 | (c[9] & 255) << 8 | (c[10] & 255) << 16 | (c[11] & 255) << 24, j11 = k[16] & 255 | (k[17] & 255) << 8 | (k[18] & 255) << 16 | (k[19] & 255) << 24, j12 = k[20] & 255 | (k[21] & 255) << 8 | (k[22] & 255) << 16 | (k[23] & 255) << 24, j13 = k[24] & 255 | (k[25] & 255) << 8 | (k[26] & 255) << 16 | (k[27] & 255) << 24, j14 = k[28] & 255 | (k[29] & 255) << 8 | (k[30] & 255) << 16 | (k[31] & 255) << 24, j15 = c[12] & 255 | (c[13] & 255) << 8 | (c[14] & 255) << 16 | (c[15] & 255) << 24; + var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, x15 = j15, u; + for (var i = 0; i < 20; i += 2) { + u = x0 + x12 | 0; + x4 ^= u << 7 | u >>> 32 - 7; + u = x4 + x0 | 0; + x8 ^= u << 9 | u >>> 32 - 9; + u = x8 + x4 | 0; + x12 ^= u << 13 | u >>> 32 - 13; + u = x12 + x8 | 0; + x0 ^= u << 18 | u >>> 32 - 18; + u = x5 + x1 | 0; + x9 ^= u << 7 | u >>> 32 - 7; + u = x9 + x5 | 0; + x13 ^= u << 9 | u >>> 32 - 9; + u = x13 + x9 | 0; + x1 ^= u << 13 | u >>> 32 - 13; + u = x1 + x13 | 0; + x5 ^= u << 18 | u >>> 32 - 18; + u = x10 + x6 | 0; + x14 ^= u << 7 | u >>> 32 - 7; + u = x14 + x10 | 0; + x2 ^= u << 9 | u >>> 32 - 9; + u = x2 + x14 | 0; + x6 ^= u << 13 | u >>> 32 - 13; + u = x6 + x2 | 0; + x10 ^= u << 18 | u >>> 32 - 18; + u = x15 + x11 | 0; + x3 ^= u << 7 | u >>> 32 - 7; + u = x3 + x15 | 0; + x7 ^= u << 9 | u >>> 32 - 9; + u = x7 + x3 | 0; + x11 ^= u << 13 | u >>> 32 - 13; + u = x11 + x7 | 0; + x15 ^= u << 18 | u >>> 32 - 18; + u = x0 + x3 | 0; + x1 ^= u << 7 | u >>> 32 - 7; + u = x1 + x0 | 0; + x2 ^= u << 9 | u >>> 32 - 9; + u = x2 + x1 | 0; + x3 ^= u << 13 | u >>> 32 - 13; + u = x3 + x2 | 0; + x0 ^= u << 18 | u >>> 32 - 18; + u = x5 + x4 | 0; + x6 ^= u << 7 | u >>> 32 - 7; + u = x6 + x5 | 0; + x7 ^= u << 9 | u >>> 32 - 9; + u = x7 + x6 | 0; + x4 ^= u << 13 | u >>> 32 - 13; + u = x4 + x7 | 0; + x5 ^= u << 18 | u >>> 32 - 18; + u = x10 + x9 | 0; + x11 ^= u << 7 | u >>> 32 - 7; + u = x11 + x10 | 0; + x8 ^= u << 9 | u >>> 32 - 9; + u = x8 + x11 | 0; + x9 ^= u << 13 | u >>> 32 - 13; + u = x9 + x8 | 0; + x10 ^= u << 18 | u >>> 32 - 18; + u = x15 + x14 | 0; + x12 ^= u << 7 | u >>> 32 - 7; + u = x12 + x15 | 0; + x13 ^= u << 9 | u >>> 32 - 9; + u = x13 + x12 | 0; + x14 ^= u << 13 | u >>> 32 - 13; + u = x14 + x13 | 0; + x15 ^= u << 18 | u >>> 32 - 18; } - return result; - }); - } - function saveState(name, value) { - const filePath = process.env["GITHUB_STATE"] || ""; - if (filePath) { - return (0, file_command_1.issueFileCommand)("STATE", (0, file_command_1.prepareKeyValueMessage)(name, value)); - } - (0, command_1.issueCommand)("save-state", { name }, (0, utils_1.toCommandValue)(value)); - } - function getState(name) { - return process.env[`STATE_${name}`] || ""; - } - function getIDToken(aud) { - return __awaiter3(this, void 0, void 0, function* () { - return yield oidc_utils_1.OidcClient.getIDToken(aud); - }); - } - var summary_1 = require_summary(); - Object.defineProperty(exports2, "summary", { enumerable: true, get: function() { - return summary_1.summary; - } }); - var summary_2 = require_summary(); - Object.defineProperty(exports2, "markdownSummary", { enumerable: true, get: function() { - return summary_2.markdownSummary; - } }); - var path_utils_1 = require_path_utils(); - Object.defineProperty(exports2, "toPosixPath", { enumerable: true, get: function() { - return path_utils_1.toPosixPath; - } }); - Object.defineProperty(exports2, "toWin32Path", { enumerable: true, get: function() { - return path_utils_1.toWin32Path; - } }); - Object.defineProperty(exports2, "toPlatformPath", { enumerable: true, get: function() { - return path_utils_1.toPlatformPath; - } }); - exports2.platform = __importStar(require_platform()); - } -}); - -// node_modules/@actions/github/node_modules/@actions/http-client/lib/proxy.js -var require_proxy2 = __commonJS({ - "node_modules/@actions/github/node_modules/@actions/http-client/lib/proxy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getProxyUrl = getProxyUrl2; - exports2.checkBypass = checkBypass2; - function getProxyUrl2(reqUrl) { - const usingSsl = reqUrl.protocol === "https:"; - if (checkBypass2(reqUrl)) { - return void 0; + x0 = x0 + j0 | 0; + x1 = x1 + j1 | 0; + x2 = x2 + j2 | 0; + x3 = x3 + j3 | 0; + x4 = x4 + j4 | 0; + x5 = x5 + j5 | 0; + x6 = x6 + j6 | 0; + x7 = x7 + j7 | 0; + x8 = x8 + j8 | 0; + x9 = x9 + j9 | 0; + x10 = x10 + j10 | 0; + x11 = x11 + j11 | 0; + x12 = x12 + j12 | 0; + x13 = x13 + j13 | 0; + x14 = x14 + j14 | 0; + x15 = x15 + j15 | 0; + o[0] = x0 >>> 0 & 255; + o[1] = x0 >>> 8 & 255; + o[2] = x0 >>> 16 & 255; + o[3] = x0 >>> 24 & 255; + o[4] = x1 >>> 0 & 255; + o[5] = x1 >>> 8 & 255; + o[6] = x1 >>> 16 & 255; + o[7] = x1 >>> 24 & 255; + o[8] = x2 >>> 0 & 255; + o[9] = x2 >>> 8 & 255; + o[10] = x2 >>> 16 & 255; + o[11] = x2 >>> 24 & 255; + o[12] = x3 >>> 0 & 255; + o[13] = x3 >>> 8 & 255; + o[14] = x3 >>> 16 & 255; + o[15] = x3 >>> 24 & 255; + o[16] = x4 >>> 0 & 255; + o[17] = x4 >>> 8 & 255; + o[18] = x4 >>> 16 & 255; + o[19] = x4 >>> 24 & 255; + o[20] = x5 >>> 0 & 255; + o[21] = x5 >>> 8 & 255; + o[22] = x5 >>> 16 & 255; + o[23] = x5 >>> 24 & 255; + o[24] = x6 >>> 0 & 255; + o[25] = x6 >>> 8 & 255; + o[26] = x6 >>> 16 & 255; + o[27] = x6 >>> 24 & 255; + o[28] = x7 >>> 0 & 255; + o[29] = x7 >>> 8 & 255; + o[30] = x7 >>> 16 & 255; + o[31] = x7 >>> 24 & 255; + o[32] = x8 >>> 0 & 255; + o[33] = x8 >>> 8 & 255; + o[34] = x8 >>> 16 & 255; + o[35] = x8 >>> 24 & 255; + o[36] = x9 >>> 0 & 255; + o[37] = x9 >>> 8 & 255; + o[38] = x9 >>> 16 & 255; + o[39] = x9 >>> 24 & 255; + o[40] = x10 >>> 0 & 255; + o[41] = x10 >>> 8 & 255; + o[42] = x10 >>> 16 & 255; + o[43] = x10 >>> 24 & 255; + o[44] = x11 >>> 0 & 255; + o[45] = x11 >>> 8 & 255; + o[46] = x11 >>> 16 & 255; + o[47] = x11 >>> 24 & 255; + o[48] = x12 >>> 0 & 255; + o[49] = x12 >>> 8 & 255; + o[50] = x12 >>> 16 & 255; + o[51] = x12 >>> 24 & 255; + o[52] = x13 >>> 0 & 255; + o[53] = x13 >>> 8 & 255; + o[54] = x13 >>> 16 & 255; + o[55] = x13 >>> 24 & 255; + o[56] = x14 >>> 0 & 255; + o[57] = x14 >>> 8 & 255; + o[58] = x14 >>> 16 & 255; + o[59] = x14 >>> 24 & 255; + o[60] = x15 >>> 0 & 255; + o[61] = x15 >>> 8 & 255; + o[62] = x15 >>> 16 & 255; + o[63] = x15 >>> 24 & 255; } - const proxyVar = (() => { - if (usingSsl) { - return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; - } else { - return process.env["http_proxy"] || process.env["HTTP_PROXY"]; - } - })(); - if (proxyVar) { - try { - return new DecodedURL2(proxyVar); - } catch (_a) { - if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) - return new DecodedURL2(`http://${proxyVar}`); + function core_hsalsa20(o, p, k, c) { + var j0 = c[0] & 255 | (c[1] & 255) << 8 | (c[2] & 255) << 16 | (c[3] & 255) << 24, j1 = k[0] & 255 | (k[1] & 255) << 8 | (k[2] & 255) << 16 | (k[3] & 255) << 24, j2 = k[4] & 255 | (k[5] & 255) << 8 | (k[6] & 255) << 16 | (k[7] & 255) << 24, j3 = k[8] & 255 | (k[9] & 255) << 8 | (k[10] & 255) << 16 | (k[11] & 255) << 24, j4 = k[12] & 255 | (k[13] & 255) << 8 | (k[14] & 255) << 16 | (k[15] & 255) << 24, j5 = c[4] & 255 | (c[5] & 255) << 8 | (c[6] & 255) << 16 | (c[7] & 255) << 24, j6 = p[0] & 255 | (p[1] & 255) << 8 | (p[2] & 255) << 16 | (p[3] & 255) << 24, j7 = p[4] & 255 | (p[5] & 255) << 8 | (p[6] & 255) << 16 | (p[7] & 255) << 24, j8 = p[8] & 255 | (p[9] & 255) << 8 | (p[10] & 255) << 16 | (p[11] & 255) << 24, j9 = p[12] & 255 | (p[13] & 255) << 8 | (p[14] & 255) << 16 | (p[15] & 255) << 24, j10 = c[8] & 255 | (c[9] & 255) << 8 | (c[10] & 255) << 16 | (c[11] & 255) << 24, j11 = k[16] & 255 | (k[17] & 255) << 8 | (k[18] & 255) << 16 | (k[19] & 255) << 24, j12 = k[20] & 255 | (k[21] & 255) << 8 | (k[22] & 255) << 16 | (k[23] & 255) << 24, j13 = k[24] & 255 | (k[25] & 255) << 8 | (k[26] & 255) << 16 | (k[27] & 255) << 24, j14 = k[28] & 255 | (k[29] & 255) << 8 | (k[30] & 255) << 16 | (k[31] & 255) << 24, j15 = c[12] & 255 | (c[13] & 255) << 8 | (c[14] & 255) << 16 | (c[15] & 255) << 24; + var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, x15 = j15, u; + for (var i = 0; i < 20; i += 2) { + u = x0 + x12 | 0; + x4 ^= u << 7 | u >>> 32 - 7; + u = x4 + x0 | 0; + x8 ^= u << 9 | u >>> 32 - 9; + u = x8 + x4 | 0; + x12 ^= u << 13 | u >>> 32 - 13; + u = x12 + x8 | 0; + x0 ^= u << 18 | u >>> 32 - 18; + u = x5 + x1 | 0; + x9 ^= u << 7 | u >>> 32 - 7; + u = x9 + x5 | 0; + x13 ^= u << 9 | u >>> 32 - 9; + u = x13 + x9 | 0; + x1 ^= u << 13 | u >>> 32 - 13; + u = x1 + x13 | 0; + x5 ^= u << 18 | u >>> 32 - 18; + u = x10 + x6 | 0; + x14 ^= u << 7 | u >>> 32 - 7; + u = x14 + x10 | 0; + x2 ^= u << 9 | u >>> 32 - 9; + u = x2 + x14 | 0; + x6 ^= u << 13 | u >>> 32 - 13; + u = x6 + x2 | 0; + x10 ^= u << 18 | u >>> 32 - 18; + u = x15 + x11 | 0; + x3 ^= u << 7 | u >>> 32 - 7; + u = x3 + x15 | 0; + x7 ^= u << 9 | u >>> 32 - 9; + u = x7 + x3 | 0; + x11 ^= u << 13 | u >>> 32 - 13; + u = x11 + x7 | 0; + x15 ^= u << 18 | u >>> 32 - 18; + u = x0 + x3 | 0; + x1 ^= u << 7 | u >>> 32 - 7; + u = x1 + x0 | 0; + x2 ^= u << 9 | u >>> 32 - 9; + u = x2 + x1 | 0; + x3 ^= u << 13 | u >>> 32 - 13; + u = x3 + x2 | 0; + x0 ^= u << 18 | u >>> 32 - 18; + u = x5 + x4 | 0; + x6 ^= u << 7 | u >>> 32 - 7; + u = x6 + x5 | 0; + x7 ^= u << 9 | u >>> 32 - 9; + u = x7 + x6 | 0; + x4 ^= u << 13 | u >>> 32 - 13; + u = x4 + x7 | 0; + x5 ^= u << 18 | u >>> 32 - 18; + u = x10 + x9 | 0; + x11 ^= u << 7 | u >>> 32 - 7; + u = x11 + x10 | 0; + x8 ^= u << 9 | u >>> 32 - 9; + u = x8 + x11 | 0; + x9 ^= u << 13 | u >>> 32 - 13; + u = x9 + x8 | 0; + x10 ^= u << 18 | u >>> 32 - 18; + u = x15 + x14 | 0; + x12 ^= u << 7 | u >>> 32 - 7; + u = x12 + x15 | 0; + x13 ^= u << 9 | u >>> 32 - 9; + u = x13 + x12 | 0; + x14 ^= u << 13 | u >>> 32 - 13; + u = x14 + x13 | 0; + x15 ^= u << 18 | u >>> 32 - 18; } - } else { - return void 0; - } - } - function checkBypass2(reqUrl) { - if (!reqUrl.hostname) { - return false; - } - const reqHost = reqUrl.hostname; - if (isLoopbackAddress2(reqHost)) { - return true; - } - const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; - if (!noProxy) { - return false; + o[0] = x0 >>> 0 & 255; + o[1] = x0 >>> 8 & 255; + o[2] = x0 >>> 16 & 255; + o[3] = x0 >>> 24 & 255; + o[4] = x5 >>> 0 & 255; + o[5] = x5 >>> 8 & 255; + o[6] = x5 >>> 16 & 255; + o[7] = x5 >>> 24 & 255; + o[8] = x10 >>> 0 & 255; + o[9] = x10 >>> 8 & 255; + o[10] = x10 >>> 16 & 255; + o[11] = x10 >>> 24 & 255; + o[12] = x15 >>> 0 & 255; + o[13] = x15 >>> 8 & 255; + o[14] = x15 >>> 16 & 255; + o[15] = x15 >>> 24 & 255; + o[16] = x6 >>> 0 & 255; + o[17] = x6 >>> 8 & 255; + o[18] = x6 >>> 16 & 255; + o[19] = x6 >>> 24 & 255; + o[20] = x7 >>> 0 & 255; + o[21] = x7 >>> 8 & 255; + o[22] = x7 >>> 16 & 255; + o[23] = x7 >>> 24 & 255; + o[24] = x8 >>> 0 & 255; + o[25] = x8 >>> 8 & 255; + o[26] = x8 >>> 16 & 255; + o[27] = x8 >>> 24 & 255; + o[28] = x9 >>> 0 & 255; + o[29] = x9 >>> 8 & 255; + o[30] = x9 >>> 16 & 255; + o[31] = x9 >>> 24 & 255; } - let reqPort; - if (reqUrl.port) { - reqPort = Number(reqUrl.port); - } else if (reqUrl.protocol === "http:") { - reqPort = 80; - } else if (reqUrl.protocol === "https:") { - reqPort = 443; + function crypto_core_salsa20(out, inp, k, c) { + core_salsa20(out, inp, k, c); } - const upperReqHosts = [reqUrl.hostname.toUpperCase()]; - if (typeof reqPort === "number") { - upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + function crypto_core_hsalsa20(out, inp, k, c) { + core_hsalsa20(out, inp, k, c); } - for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { - if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { - return true; + var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]); + function crypto_stream_salsa20_xor(c, cpos, m, mpos, b, n, k) { + var z = new Uint8Array(16), x = new Uint8Array(64); + var u, i; + for (i = 0; i < 16; i++) z[i] = 0; + for (i = 0; i < 8; i++) z[i] = n[i]; + while (b >= 64) { + crypto_core_salsa20(x, z, k, sigma); + for (i = 0; i < 64; i++) c[cpos + i] = m[mpos + i] ^ x[i]; + u = 1; + for (i = 8; i < 16; i++) { + u = u + (z[i] & 255) | 0; + z[i] = u & 255; + u >>>= 8; + } + b -= 64; + cpos += 64; + mpos += 64; } - } - return false; - } - function isLoopbackAddress2(host) { - const hostLower = host.toLowerCase(); - return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); - } - var DecodedURL2 = class extends URL { - constructor(url, base) { - super(url, base); - this._decodedUsername = decodeURIComponent(super.username); - this._decodedPassword = decodeURIComponent(super.password); - } - get username() { - return this._decodedUsername; - } - get password() { - return this._decodedPassword; - } - }; - } -}); - -// node_modules/@actions/github/node_modules/@actions/http-client/lib/index.js -var require_lib2 = __commonJS({ - "node_modules/@actions/github/node_modules/@actions/http-client/lib/index.js"(exports2) { - "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - 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 ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + if (b > 0) { + crypto_core_salsa20(x, z, k, sigma); + for (i = 0; i < b; i++) c[cpos + i] = m[mpos + i] ^ x[i]; } - __setModuleDefault(result, mod); - return result; - }; - })(); - var __awaiter3 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); + return 0; } - return new (P || (P = 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 crypto_stream_salsa20(c, cpos, b, n, k) { + var z = new Uint8Array(16), x = new Uint8Array(64); + var u, i; + for (i = 0; i < 16; i++) z[i] = 0; + for (i = 0; i < 8; i++) z[i] = n[i]; + while (b >= 64) { + crypto_core_salsa20(x, z, k, sigma); + for (i = 0; i < 64; i++) c[cpos + i] = x[i]; + u = 1; + for (i = 8; i < 16; i++) { + u = u + (z[i] & 255) | 0; + z[i] = u & 255; + u >>>= 8; } + b -= 64; + cpos += 64; } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + if (b > 0) { + crypto_core_salsa20(x, z, k, sigma); + for (i = 0; i < b; i++) c[cpos + i] = x[i]; } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.HttpClient = exports2.HttpClientResponse = exports2.HttpClientError = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; - exports2.getProxyUrl = getProxyUrl2; - exports2.isHttps = isHttps; - var http2 = __importStar(require("http")); - var https2 = __importStar(require("https")); - var pm = __importStar(require_proxy2()); - var tunnel2 = __importStar(require_tunnel2()); - var undici_1 = require_undici(); - var HttpCodes2; - (function(HttpCodes3) { - HttpCodes3[HttpCodes3["OK"] = 200] = "OK"; - HttpCodes3[HttpCodes3["MultipleChoices"] = 300] = "MultipleChoices"; - HttpCodes3[HttpCodes3["MovedPermanently"] = 301] = "MovedPermanently"; - HttpCodes3[HttpCodes3["ResourceMoved"] = 302] = "ResourceMoved"; - HttpCodes3[HttpCodes3["SeeOther"] = 303] = "SeeOther"; - HttpCodes3[HttpCodes3["NotModified"] = 304] = "NotModified"; - HttpCodes3[HttpCodes3["UseProxy"] = 305] = "UseProxy"; - HttpCodes3[HttpCodes3["SwitchProxy"] = 306] = "SwitchProxy"; - HttpCodes3[HttpCodes3["TemporaryRedirect"] = 307] = "TemporaryRedirect"; - HttpCodes3[HttpCodes3["PermanentRedirect"] = 308] = "PermanentRedirect"; - HttpCodes3[HttpCodes3["BadRequest"] = 400] = "BadRequest"; - HttpCodes3[HttpCodes3["Unauthorized"] = 401] = "Unauthorized"; - HttpCodes3[HttpCodes3["PaymentRequired"] = 402] = "PaymentRequired"; - HttpCodes3[HttpCodes3["Forbidden"] = 403] = "Forbidden"; - HttpCodes3[HttpCodes3["NotFound"] = 404] = "NotFound"; - HttpCodes3[HttpCodes3["MethodNotAllowed"] = 405] = "MethodNotAllowed"; - HttpCodes3[HttpCodes3["NotAcceptable"] = 406] = "NotAcceptable"; - HttpCodes3[HttpCodes3["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; - HttpCodes3[HttpCodes3["RequestTimeout"] = 408] = "RequestTimeout"; - HttpCodes3[HttpCodes3["Conflict"] = 409] = "Conflict"; - HttpCodes3[HttpCodes3["Gone"] = 410] = "Gone"; - HttpCodes3[HttpCodes3["TooManyRequests"] = 429] = "TooManyRequests"; - HttpCodes3[HttpCodes3["InternalServerError"] = 500] = "InternalServerError"; - HttpCodes3[HttpCodes3["NotImplemented"] = 501] = "NotImplemented"; - HttpCodes3[HttpCodes3["BadGateway"] = 502] = "BadGateway"; - HttpCodes3[HttpCodes3["ServiceUnavailable"] = 503] = "ServiceUnavailable"; - HttpCodes3[HttpCodes3["GatewayTimeout"] = 504] = "GatewayTimeout"; - })(HttpCodes2 || (exports2.HttpCodes = HttpCodes2 = {})); - var Headers2; - (function(Headers3) { - Headers3["Accept"] = "accept"; - Headers3["ContentType"] = "content-type"; - })(Headers2 || (exports2.Headers = Headers2 = {})); - var MediaTypes2; - (function(MediaTypes3) { - MediaTypes3["ApplicationJson"] = "application/json"; - })(MediaTypes2 || (exports2.MediaTypes = MediaTypes2 = {})); - function getProxyUrl2(serverUrl) { - const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); - return proxyUrl ? proxyUrl.href : ""; - } - var HttpRedirectCodes2 = [ - HttpCodes2.MovedPermanently, - HttpCodes2.ResourceMoved, - HttpCodes2.SeeOther, - HttpCodes2.TemporaryRedirect, - HttpCodes2.PermanentRedirect - ]; - var HttpResponseRetryCodes2 = [ - HttpCodes2.BadGateway, - HttpCodes2.ServiceUnavailable, - HttpCodes2.GatewayTimeout - ]; - var RetryableHttpVerbs2 = ["OPTIONS", "GET", "DELETE", "HEAD"]; - var ExponentialBackoffCeiling2 = 10; - var ExponentialBackoffTimeSlice2 = 5; - var HttpClientError2 = class _HttpClientError extends Error { - constructor(message, statusCode) { - super(message); - this.name = "HttpClientError"; - this.statusCode = statusCode; - Object.setPrototypeOf(this, _HttpClientError.prototype); - } - }; - exports2.HttpClientError = HttpClientError2; - var HttpClientResponse2 = class { - constructor(message) { - this.message = message; + return 0; } - readBody() { - return __awaiter3(this, void 0, void 0, function* () { - return new Promise((resolve) => __awaiter3(this, void 0, void 0, function* () { - let output = Buffer.alloc(0); - this.message.on("data", (chunk) => { - output = Buffer.concat([output, chunk]); - }); - this.message.on("end", () => { - resolve(output.toString()); - }); - })); - }); + function crypto_stream(c, cpos, d, n, k) { + var s = new Uint8Array(32); + crypto_core_hsalsa20(s, n, k, sigma); + var sn = new Uint8Array(8); + for (var i = 0; i < 8; i++) sn[i] = n[i + 16]; + return crypto_stream_salsa20(c, cpos, d, sn, s); } - readBodyBuffer() { - return __awaiter3(this, void 0, void 0, function* () { - return new Promise((resolve) => __awaiter3(this, void 0, void 0, function* () { - const chunks = []; - this.message.on("data", (chunk) => { - chunks.push(chunk); - }); - this.message.on("end", () => { - resolve(Buffer.concat(chunks)); - }); - })); - }); + function crypto_stream_xor(c, cpos, m, mpos, d, n, k) { + var s = new Uint8Array(32); + crypto_core_hsalsa20(s, n, k, sigma); + var sn = new Uint8Array(8); + for (var i = 0; i < 8; i++) sn[i] = n[i + 16]; + return crypto_stream_salsa20_xor(c, cpos, m, mpos, d, sn, s); } - }; - exports2.HttpClientResponse = HttpClientResponse2; - function isHttps(requestUrl) { - const parsedUrl = new URL(requestUrl); - return parsedUrl.protocol === "https:"; - } - var HttpClient3 = class { - constructor(userAgent2, handlers, requestOptions) { - this._ignoreSslError = false; - this._allowRedirects = true; - this._allowRedirectDowngrade = false; - this._maxRedirects = 50; - this._allowRetries = false; - this._maxRetries = 1; - this._keepAlive = false; - this._disposed = false; - this.userAgent = this._getUserAgentWithOrchestrationId(userAgent2); - this.handlers = handlers || []; - this.requestOptions = requestOptions; - if (requestOptions) { - if (requestOptions.ignoreSslError != null) { - this._ignoreSslError = requestOptions.ignoreSslError; - } - this._socketTimeout = requestOptions.socketTimeout; - if (requestOptions.allowRedirects != null) { - this._allowRedirects = requestOptions.allowRedirects; - } - if (requestOptions.allowRedirectDowngrade != null) { - this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; - } - if (requestOptions.maxRedirects != null) { - this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); - } - if (requestOptions.keepAlive != null) { - this._keepAlive = requestOptions.keepAlive; - } - if (requestOptions.allowRetries != null) { - this._allowRetries = requestOptions.allowRetries; - } - if (requestOptions.maxRetries != null) { - this._maxRetries = requestOptions.maxRetries; - } + var poly1305 = function(key) { + this.buffer = new Uint8Array(16); + this.r = new Uint16Array(10); + this.h = new Uint16Array(10); + this.pad = new Uint16Array(8); + this.leftover = 0; + this.fin = 0; + var t0, t1, t2, t3, t4, t5, t6, t7; + t0 = key[0] & 255 | (key[1] & 255) << 8; + this.r[0] = t0 & 8191; + t1 = key[2] & 255 | (key[3] & 255) << 8; + this.r[1] = (t0 >>> 13 | t1 << 3) & 8191; + t2 = key[4] & 255 | (key[5] & 255) << 8; + this.r[2] = (t1 >>> 10 | t2 << 6) & 7939; + t3 = key[6] & 255 | (key[7] & 255) << 8; + this.r[3] = (t2 >>> 7 | t3 << 9) & 8191; + t4 = key[8] & 255 | (key[9] & 255) << 8; + this.r[4] = (t3 >>> 4 | t4 << 12) & 255; + this.r[5] = t4 >>> 1 & 8190; + t5 = key[10] & 255 | (key[11] & 255) << 8; + this.r[6] = (t4 >>> 14 | t5 << 2) & 8191; + t6 = key[12] & 255 | (key[13] & 255) << 8; + this.r[7] = (t5 >>> 11 | t6 << 5) & 8065; + t7 = key[14] & 255 | (key[15] & 255) << 8; + this.r[8] = (t6 >>> 8 | t7 << 8) & 8191; + this.r[9] = t7 >>> 5 & 127; + this.pad[0] = key[16] & 255 | (key[17] & 255) << 8; + this.pad[1] = key[18] & 255 | (key[19] & 255) << 8; + this.pad[2] = key[20] & 255 | (key[21] & 255) << 8; + this.pad[3] = key[22] & 255 | (key[23] & 255) << 8; + this.pad[4] = key[24] & 255 | (key[25] & 255) << 8; + this.pad[5] = key[26] & 255 | (key[27] & 255) << 8; + this.pad[6] = key[28] & 255 | (key[29] & 255) << 8; + this.pad[7] = key[30] & 255 | (key[31] & 255) << 8; + }; + poly1305.prototype.blocks = function(m, mpos, bytes) { + var hibit = this.fin ? 0 : 1 << 11; + var t0, t1, t2, t3, t4, t5, t6, t7, c; + var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9; + var h0 = this.h[0], h1 = this.h[1], h2 = this.h[2], h3 = this.h[3], h4 = this.h[4], h5 = this.h[5], h6 = this.h[6], h7 = this.h[7], h8 = this.h[8], h9 = this.h[9]; + var r0 = this.r[0], r1 = this.r[1], r2 = this.r[2], r3 = this.r[3], r4 = this.r[4], r5 = this.r[5], r6 = this.r[6], r7 = this.r[7], r8 = this.r[8], r9 = this.r[9]; + while (bytes >= 16) { + t0 = m[mpos + 0] & 255 | (m[mpos + 1] & 255) << 8; + h0 += t0 & 8191; + t1 = m[mpos + 2] & 255 | (m[mpos + 3] & 255) << 8; + h1 += (t0 >>> 13 | t1 << 3) & 8191; + t2 = m[mpos + 4] & 255 | (m[mpos + 5] & 255) << 8; + h2 += (t1 >>> 10 | t2 << 6) & 8191; + t3 = m[mpos + 6] & 255 | (m[mpos + 7] & 255) << 8; + h3 += (t2 >>> 7 | t3 << 9) & 8191; + t4 = m[mpos + 8] & 255 | (m[mpos + 9] & 255) << 8; + h4 += (t3 >>> 4 | t4 << 12) & 8191; + h5 += t4 >>> 1 & 8191; + t5 = m[mpos + 10] & 255 | (m[mpos + 11] & 255) << 8; + h6 += (t4 >>> 14 | t5 << 2) & 8191; + t6 = m[mpos + 12] & 255 | (m[mpos + 13] & 255) << 8; + h7 += (t5 >>> 11 | t6 << 5) & 8191; + t7 = m[mpos + 14] & 255 | (m[mpos + 15] & 255) << 8; + h8 += (t6 >>> 8 | t7 << 8) & 8191; + h9 += t7 >>> 5 | hibit; + c = 0; + d0 = c; + d0 += h0 * r0; + d0 += h1 * (5 * r9); + d0 += h2 * (5 * r8); + d0 += h3 * (5 * r7); + d0 += h4 * (5 * r6); + c = d0 >>> 13; + d0 &= 8191; + d0 += h5 * (5 * r5); + d0 += h6 * (5 * r4); + d0 += h7 * (5 * r3); + d0 += h8 * (5 * r2); + d0 += h9 * (5 * r1); + c += d0 >>> 13; + d0 &= 8191; + d1 = c; + d1 += h0 * r1; + d1 += h1 * r0; + d1 += h2 * (5 * r9); + d1 += h3 * (5 * r8); + d1 += h4 * (5 * r7); + c = d1 >>> 13; + d1 &= 8191; + d1 += h5 * (5 * r6); + d1 += h6 * (5 * r5); + d1 += h7 * (5 * r4); + d1 += h8 * (5 * r3); + d1 += h9 * (5 * r2); + c += d1 >>> 13; + d1 &= 8191; + d2 = c; + d2 += h0 * r2; + d2 += h1 * r1; + d2 += h2 * r0; + d2 += h3 * (5 * r9); + d2 += h4 * (5 * r8); + c = d2 >>> 13; + d2 &= 8191; + d2 += h5 * (5 * r7); + d2 += h6 * (5 * r6); + d2 += h7 * (5 * r5); + d2 += h8 * (5 * r4); + d2 += h9 * (5 * r3); + c += d2 >>> 13; + d2 &= 8191; + d3 = c; + d3 += h0 * r3; + d3 += h1 * r2; + d3 += h2 * r1; + d3 += h3 * r0; + d3 += h4 * (5 * r9); + c = d3 >>> 13; + d3 &= 8191; + d3 += h5 * (5 * r8); + d3 += h6 * (5 * r7); + d3 += h7 * (5 * r6); + d3 += h8 * (5 * r5); + d3 += h9 * (5 * r4); + c += d3 >>> 13; + d3 &= 8191; + d4 = c; + d4 += h0 * r4; + d4 += h1 * r3; + d4 += h2 * r2; + d4 += h3 * r1; + d4 += h4 * r0; + c = d4 >>> 13; + d4 &= 8191; + d4 += h5 * (5 * r9); + d4 += h6 * (5 * r8); + d4 += h7 * (5 * r7); + d4 += h8 * (5 * r6); + d4 += h9 * (5 * r5); + c += d4 >>> 13; + d4 &= 8191; + d5 = c; + d5 += h0 * r5; + d5 += h1 * r4; + d5 += h2 * r3; + d5 += h3 * r2; + d5 += h4 * r1; + c = d5 >>> 13; + d5 &= 8191; + d5 += h5 * r0; + d5 += h6 * (5 * r9); + d5 += h7 * (5 * r8); + d5 += h8 * (5 * r7); + d5 += h9 * (5 * r6); + c += d5 >>> 13; + d5 &= 8191; + d6 = c; + d6 += h0 * r6; + d6 += h1 * r5; + d6 += h2 * r4; + d6 += h3 * r3; + d6 += h4 * r2; + c = d6 >>> 13; + d6 &= 8191; + d6 += h5 * r1; + d6 += h6 * r0; + d6 += h7 * (5 * r9); + d6 += h8 * (5 * r8); + d6 += h9 * (5 * r7); + c += d6 >>> 13; + d6 &= 8191; + d7 = c; + d7 += h0 * r7; + d7 += h1 * r6; + d7 += h2 * r5; + d7 += h3 * r4; + d7 += h4 * r3; + c = d7 >>> 13; + d7 &= 8191; + d7 += h5 * r2; + d7 += h6 * r1; + d7 += h7 * r0; + d7 += h8 * (5 * r9); + d7 += h9 * (5 * r8); + c += d7 >>> 13; + d7 &= 8191; + d8 = c; + d8 += h0 * r8; + d8 += h1 * r7; + d8 += h2 * r6; + d8 += h3 * r5; + d8 += h4 * r4; + c = d8 >>> 13; + d8 &= 8191; + d8 += h5 * r3; + d8 += h6 * r2; + d8 += h7 * r1; + d8 += h8 * r0; + d8 += h9 * (5 * r9); + c += d8 >>> 13; + d8 &= 8191; + d9 = c; + d9 += h0 * r9; + d9 += h1 * r8; + d9 += h2 * r7; + d9 += h3 * r6; + d9 += h4 * r5; + c = d9 >>> 13; + d9 &= 8191; + d9 += h5 * r4; + d9 += h6 * r3; + d9 += h7 * r2; + d9 += h8 * r1; + d9 += h9 * r0; + c += d9 >>> 13; + d9 &= 8191; + c = (c << 2) + c | 0; + c = c + d0 | 0; + d0 = c & 8191; + c = c >>> 13; + d1 += c; + h0 = d0; + h1 = d1; + h2 = d2; + h3 = d3; + h4 = d4; + h5 = d5; + h6 = d6; + h7 = d7; + h8 = d8; + h9 = d9; + mpos += 16; + bytes -= 16; } + this.h[0] = h0; + this.h[1] = h1; + this.h[2] = h2; + this.h[3] = h3; + this.h[4] = h4; + this.h[5] = h5; + this.h[6] = h6; + this.h[7] = h7; + this.h[8] = h8; + this.h[9] = h9; + }; + poly1305.prototype.finish = function(mac, macpos) { + var g = new Uint16Array(10); + var c, mask, f, i; + if (this.leftover) { + i = this.leftover; + this.buffer[i++] = 1; + for (; i < 16; i++) this.buffer[i] = 0; + this.fin = 1; + this.blocks(this.buffer, 0, 16); + } + c = this.h[1] >>> 13; + this.h[1] &= 8191; + for (i = 2; i < 10; i++) { + this.h[i] += c; + c = this.h[i] >>> 13; + this.h[i] &= 8191; + } + this.h[0] += c * 5; + c = this.h[0] >>> 13; + this.h[0] &= 8191; + this.h[1] += c; + c = this.h[1] >>> 13; + this.h[1] &= 8191; + this.h[2] += c; + g[0] = this.h[0] + 5; + c = g[0] >>> 13; + g[0] &= 8191; + for (i = 1; i < 10; i++) { + g[i] = this.h[i] + c; + c = g[i] >>> 13; + g[i] &= 8191; + } + g[9] -= 1 << 13; + mask = (c ^ 1) - 1; + for (i = 0; i < 10; i++) g[i] &= mask; + mask = ~mask; + for (i = 0; i < 10; i++) this.h[i] = this.h[i] & mask | g[i]; + this.h[0] = (this.h[0] | this.h[1] << 13) & 65535; + this.h[1] = (this.h[1] >>> 3 | this.h[2] << 10) & 65535; + this.h[2] = (this.h[2] >>> 6 | this.h[3] << 7) & 65535; + this.h[3] = (this.h[3] >>> 9 | this.h[4] << 4) & 65535; + this.h[4] = (this.h[4] >>> 12 | this.h[5] << 1 | this.h[6] << 14) & 65535; + this.h[5] = (this.h[6] >>> 2 | this.h[7] << 11) & 65535; + this.h[6] = (this.h[7] >>> 5 | this.h[8] << 8) & 65535; + this.h[7] = (this.h[8] >>> 8 | this.h[9] << 5) & 65535; + f = this.h[0] + this.pad[0]; + this.h[0] = f & 65535; + for (i = 1; i < 8; i++) { + f = (this.h[i] + this.pad[i] | 0) + (f >>> 16) | 0; + this.h[i] = f & 65535; + } + mac[macpos + 0] = this.h[0] >>> 0 & 255; + mac[macpos + 1] = this.h[0] >>> 8 & 255; + mac[macpos + 2] = this.h[1] >>> 0 & 255; + mac[macpos + 3] = this.h[1] >>> 8 & 255; + mac[macpos + 4] = this.h[2] >>> 0 & 255; + mac[macpos + 5] = this.h[2] >>> 8 & 255; + mac[macpos + 6] = this.h[3] >>> 0 & 255; + mac[macpos + 7] = this.h[3] >>> 8 & 255; + mac[macpos + 8] = this.h[4] >>> 0 & 255; + mac[macpos + 9] = this.h[4] >>> 8 & 255; + mac[macpos + 10] = this.h[5] >>> 0 & 255; + mac[macpos + 11] = this.h[5] >>> 8 & 255; + mac[macpos + 12] = this.h[6] >>> 0 & 255; + mac[macpos + 13] = this.h[6] >>> 8 & 255; + mac[macpos + 14] = this.h[7] >>> 0 & 255; + mac[macpos + 15] = this.h[7] >>> 8 & 255; + }; + poly1305.prototype.update = function(m, mpos, bytes) { + var i, want; + if (this.leftover) { + want = 16 - this.leftover; + if (want > bytes) + want = bytes; + for (i = 0; i < want; i++) + this.buffer[this.leftover + i] = m[mpos + i]; + bytes -= want; + mpos += want; + this.leftover += want; + if (this.leftover < 16) + return; + this.blocks(this.buffer, 0, 16); + this.leftover = 0; + } + if (bytes >= 16) { + want = bytes - bytes % 16; + this.blocks(m, mpos, want); + mpos += want; + bytes -= want; + } + if (bytes) { + for (i = 0; i < bytes; i++) + this.buffer[this.leftover + i] = m[mpos + i]; + this.leftover += bytes; + } + }; + function crypto_onetimeauth(out, outpos, m, mpos, n, k) { + var s = new poly1305(k); + s.update(m, mpos, n); + s.finish(out, outpos); + return 0; } - options(requestUrl, additionalHeaders) { - return __awaiter3(this, void 0, void 0, function* () { - return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); - }); - } - get(requestUrl, additionalHeaders) { - return __awaiter3(this, void 0, void 0, function* () { - return this.request("GET", requestUrl, null, additionalHeaders || {}); - }); + function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) { + var x = new Uint8Array(16); + crypto_onetimeauth(x, 0, m, mpos, n, k); + return crypto_verify_16(h, hpos, x, 0); } - del(requestUrl, additionalHeaders) { - return __awaiter3(this, void 0, void 0, function* () { - return this.request("DELETE", requestUrl, null, additionalHeaders || {}); - }); + function crypto_secretbox(c, m, d, n, k) { + var i; + if (d < 32) return -1; + crypto_stream_xor(c, 0, m, 0, d, n, k); + crypto_onetimeauth(c, 16, c, 32, d - 32, c); + for (i = 0; i < 16; i++) c[i] = 0; + return 0; } - post(requestUrl, data, additionalHeaders) { - return __awaiter3(this, void 0, void 0, function* () { - return this.request("POST", requestUrl, data, additionalHeaders || {}); - }); + function crypto_secretbox_open(m, c, d, n, k) { + var i; + var x = new Uint8Array(32); + if (d < 32) return -1; + crypto_stream(x, 0, 32, n, k); + if (crypto_onetimeauth_verify(c, 16, c, 32, d - 32, x) !== 0) return -1; + crypto_stream_xor(m, 0, c, 0, d, n, k); + for (i = 0; i < 32; i++) m[i] = 0; + return 0; } - patch(requestUrl, data, additionalHeaders) { - return __awaiter3(this, void 0, void 0, function* () { - return this.request("PATCH", requestUrl, data, additionalHeaders || {}); - }); + function set25519(r, a) { + var i; + for (i = 0; i < 16; i++) r[i] = a[i] | 0; } - put(requestUrl, data, additionalHeaders) { - return __awaiter3(this, void 0, void 0, function* () { - return this.request("PUT", requestUrl, data, additionalHeaders || {}); - }); + function car25519(o) { + var i, v, c = 1; + for (i = 0; i < 16; i++) { + v = o[i] + c + 65535; + c = Math.floor(v / 65536); + o[i] = v - c * 65536; + } + o[0] += c - 1 + 37 * (c - 1); } - head(requestUrl, additionalHeaders) { - return __awaiter3(this, void 0, void 0, function* () { - return this.request("HEAD", requestUrl, null, additionalHeaders || {}); - }); + function sel25519(p, q, b) { + var t, c = ~(b - 1); + for (var i = 0; i < 16; i++) { + t = c & (p[i] ^ q[i]); + p[i] ^= t; + q[i] ^= t; + } } - sendStream(verb, requestUrl, stream2, additionalHeaders) { - return __awaiter3(this, void 0, void 0, function* () { - return this.request(verb, requestUrl, stream2, additionalHeaders); - }); + function pack25519(o, n) { + var i, j, b; + var m = gf(), t = gf(); + for (i = 0; i < 16; i++) t[i] = n[i]; + car25519(t); + car25519(t); + car25519(t); + for (j = 0; j < 2; j++) { + m[0] = t[0] - 65517; + for (i = 1; i < 15; i++) { + m[i] = t[i] - 65535 - (m[i - 1] >> 16 & 1); + m[i - 1] &= 65535; + } + m[15] = t[15] - 32767 - (m[14] >> 16 & 1); + b = m[15] >> 16 & 1; + m[14] &= 65535; + sel25519(t, m, 1 - b); + } + for (i = 0; i < 16; i++) { + o[2 * i] = t[i] & 255; + o[2 * i + 1] = t[i] >> 8; + } } - /** - * Gets a typed object from an endpoint - * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise - */ - getJson(requestUrl_1) { - return __awaiter3(this, arguments, void 0, function* (requestUrl, additionalHeaders = {}) { - additionalHeaders[Headers2.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers2.Accept, MediaTypes2.ApplicationJson); - const res = yield this.get(requestUrl, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - postJson(requestUrl_1, obj_1) { - return __awaiter3(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers2.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers2.Accept, MediaTypes2.ApplicationJson); - additionalHeaders[Headers2.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes2.ApplicationJson); - const res = yield this.post(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - putJson(requestUrl_1, obj_1) { - return __awaiter3(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers2.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers2.Accept, MediaTypes2.ApplicationJson); - additionalHeaders[Headers2.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes2.ApplicationJson); - const res = yield this.put(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - patchJson(requestUrl_1, obj_1) { - return __awaiter3(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers2.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers2.Accept, MediaTypes2.ApplicationJson); - additionalHeaders[Headers2.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes2.ApplicationJson); - const res = yield this.patch(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - /** - * Makes a raw http request. - * All other methods such as get, post, patch, and request ultimately call this. - * Prefer get, del, post and patch - */ - request(verb, requestUrl, data, headers) { - return __awaiter3(this, void 0, void 0, function* () { - if (this._disposed) { - throw new Error("Client has already been disposed."); - } - const parsedUrl = new URL(requestUrl); - let info8 = this._prepareRequest(verb, parsedUrl, headers); - const maxTries = this._allowRetries && RetryableHttpVerbs2.includes(verb) ? this._maxRetries + 1 : 1; - let numTries = 0; - let response; - do { - response = yield this.requestRaw(info8, data); - if (response && response.message && response.message.statusCode === HttpCodes2.Unauthorized) { - let authenticationHandler; - for (const handler2 of this.handlers) { - if (handler2.canHandleAuthentication(response)) { - authenticationHandler = handler2; - break; - } - } - if (authenticationHandler) { - return authenticationHandler.handleAuthentication(this, info8, data); - } else { - return response; - } - } - let redirectsRemaining = this._maxRedirects; - while (response.message.statusCode && HttpRedirectCodes2.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { - const redirectUrl = response.message.headers["location"]; - if (!redirectUrl) { - break; - } - const parsedRedirectUrl = new URL(redirectUrl); - if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { - throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); - } - yield response.readBody(); - if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { - for (const header in headers) { - if (header.toLowerCase() === "authorization") { - delete headers[header]; - } - } - } - info8 = this._prepareRequest(verb, parsedRedirectUrl, headers); - response = yield this.requestRaw(info8, data); - redirectsRemaining--; - } - if (!response.message.statusCode || !HttpResponseRetryCodes2.includes(response.message.statusCode)) { - return response; - } - numTries += 1; - if (numTries < maxTries) { - yield response.readBody(); - yield this._performExponentialBackoff(numTries); - } - } while (numTries < maxTries); - return response; - }); - } - /** - * Needs to be called if keepAlive is set to true in request options. - */ - dispose() { - if (this._agent) { - this._agent.destroy(); - } - this._disposed = true; - } - /** - * Raw request. - * @param info - * @param data - */ - requestRaw(info8, data) { - return __awaiter3(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => { - function callbackForResult(err, res) { - if (err) { - reject(err); - } else if (!res) { - reject(new Error("Unknown error")); - } else { - resolve(res); - } - } - this.requestRawWithCallback(info8, data, callbackForResult); - }); - }); - } - /** - * Raw request with callback. - * @param info - * @param data - * @param onResult - */ - requestRawWithCallback(info8, data, onResult) { - if (typeof data === "string") { - if (!info8.options.headers) { - info8.options.headers = {}; - } - info8.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); - } - let callbackCalled = false; - function handleResult(err, res) { - if (!callbackCalled) { - callbackCalled = true; - onResult(err, res); - } - } - const req = info8.httpModule.request(info8.options, (msg) => { - const res = new HttpClientResponse2(msg); - handleResult(void 0, res); - }); - let socket; - req.on("socket", (sock) => { - socket = sock; - }); - req.setTimeout(this._socketTimeout || 3 * 6e4, () => { - if (socket) { - socket.end(); - } - handleResult(new Error(`Request timeout: ${info8.options.path}`)); - }); - req.on("error", function(err) { - handleResult(err); - }); - if (data && typeof data === "string") { - req.write(data, "utf8"); - } - if (data && typeof data !== "string") { - data.on("close", function() { - req.end(); - }); - data.pipe(req); - } else { - req.end(); - } - } - /** - * Gets an http agent. This function is useful when you need an http agent that handles - * routing through a proxy server - depending upon the url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com - */ - getAgent(serverUrl) { - const parsedUrl = new URL(serverUrl); - return this._getAgent(parsedUrl); - } - getAgentDispatcher(serverUrl) { - const parsedUrl = new URL(serverUrl); - const proxyUrl = pm.getProxyUrl(parsedUrl); - const useProxy = proxyUrl && proxyUrl.hostname; - if (!useProxy) { - return; - } - return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); - } - _prepareRequest(method, requestUrl, headers) { - const info8 = {}; - info8.parsedUrl = requestUrl; - const usingSsl = info8.parsedUrl.protocol === "https:"; - info8.httpModule = usingSsl ? https2 : http2; - const defaultPort = usingSsl ? 443 : 80; - info8.options = {}; - info8.options.host = info8.parsedUrl.hostname; - info8.options.port = info8.parsedUrl.port ? parseInt(info8.parsedUrl.port) : defaultPort; - info8.options.path = (info8.parsedUrl.pathname || "") + (info8.parsedUrl.search || ""); - info8.options.method = method; - info8.options.headers = this._mergeHeaders(headers); - if (this.userAgent != null) { - info8.options.headers["user-agent"] = this.userAgent; - } - info8.options.agent = this._getAgent(info8.parsedUrl); - if (this.handlers) { - for (const handler2 of this.handlers) { - handler2.prepareRequest(info8.options); - } - } - return info8; - } - _mergeHeaders(headers) { - if (this.requestOptions && this.requestOptions.headers) { - return Object.assign({}, lowercaseKeys3(this.requestOptions.headers), lowercaseKeys3(headers || {})); - } - return lowercaseKeys3(headers || {}); - } - /** - * Gets an existing header value or returns a default. - * Handles converting number header values to strings since HTTP headers must be strings. - * Note: This returns string | string[] since some headers can have multiple values. - * For headers that must always be a single string (like Content-Type), use the - * specialized _getExistingOrDefaultContentTypeHeader method instead. - */ - _getExistingOrDefaultHeader(additionalHeaders, header, _default) { - let clientHeader; - if (this.requestOptions && this.requestOptions.headers) { - const headerValue = lowercaseKeys3(this.requestOptions.headers)[header]; - if (headerValue) { - clientHeader = typeof headerValue === "number" ? headerValue.toString() : headerValue; - } - } - const additionalValue = additionalHeaders[header]; - if (additionalValue !== void 0) { - return typeof additionalValue === "number" ? additionalValue.toString() : additionalValue; - } - if (clientHeader !== void 0) { - return clientHeader; - } - return _default; - } - /** - * Specialized version of _getExistingOrDefaultHeader for Content-Type header. - * Always returns a single string (not an array) since Content-Type should be a single value. - * Converts arrays to comma-separated strings and numbers to strings to ensure type safety. - * This was split from _getExistingOrDefaultHeader to provide stricter typing for callers - * that assign the result to places expecting a string (e.g., additionalHeaders[Headers.ContentType]). - */ - _getExistingOrDefaultContentTypeHeader(additionalHeaders, _default) { - let clientHeader; - if (this.requestOptions && this.requestOptions.headers) { - const headerValue = lowercaseKeys3(this.requestOptions.headers)[Headers2.ContentType]; - if (headerValue) { - if (typeof headerValue === "number") { - clientHeader = String(headerValue); - } else if (Array.isArray(headerValue)) { - clientHeader = headerValue.join(", "); - } else { - clientHeader = headerValue; - } - } - } - const additionalValue = additionalHeaders[Headers2.ContentType]; - if (additionalValue !== void 0) { - if (typeof additionalValue === "number") { - return String(additionalValue); - } else if (Array.isArray(additionalValue)) { - return additionalValue.join(", "); - } else { - return additionalValue; - } - } - if (clientHeader !== void 0) { - return clientHeader; - } - return _default; - } - _getAgent(parsedUrl) { - let agent; - const proxyUrl = pm.getProxyUrl(parsedUrl); - const useProxy = proxyUrl && proxyUrl.hostname; - if (this._keepAlive && useProxy) { - agent = this._proxyAgent; - } - if (!useProxy) { - agent = this._agent; - } - if (agent) { - return agent; - } - const usingSsl = parsedUrl.protocol === "https:"; - let maxSockets = 100; - if (this.requestOptions) { - maxSockets = this.requestOptions.maxSockets || http2.globalAgent.maxSockets; - } - if (proxyUrl && proxyUrl.hostname) { - const agentOptions = { - maxSockets, - keepAlive: this._keepAlive, - proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { - proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` - }), { host: proxyUrl.hostname, port: proxyUrl.port }) - }; - let tunnelAgent; - const overHttps = proxyUrl.protocol === "https:"; - if (usingSsl) { - tunnelAgent = overHttps ? tunnel2.httpsOverHttps : tunnel2.httpsOverHttp; - } else { - tunnelAgent = overHttps ? tunnel2.httpOverHttps : tunnel2.httpOverHttp; - } - agent = tunnelAgent(agentOptions); - this._proxyAgent = agent; - } - if (!agent) { - const options = { keepAlive: this._keepAlive, maxSockets }; - agent = usingSsl ? new https2.Agent(options) : new http2.Agent(options); - this._agent = agent; - } - if (usingSsl && this._ignoreSslError) { - agent.options = Object.assign(agent.options || {}, { - rejectUnauthorized: false - }); - } - return agent; - } - _getProxyAgentDispatcher(parsedUrl, proxyUrl) { - let proxyAgent; - if (this._keepAlive) { - proxyAgent = this._proxyAgentDispatcher; - } - if (proxyAgent) { - return proxyAgent; - } - const usingSsl = parsedUrl.protocol === "https:"; - proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { - token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` - })); - this._proxyAgentDispatcher = proxyAgent; - if (usingSsl && this._ignoreSslError) { - proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { - rejectUnauthorized: false - }); - } - return proxyAgent; + function neq25519(a, b) { + var c = new Uint8Array(32), d = new Uint8Array(32); + pack25519(c, a); + pack25519(d, b); + return crypto_verify_32(c, 0, d, 0); } - _getUserAgentWithOrchestrationId(userAgent2) { - const baseUserAgent = userAgent2 || "actions/http-client"; - const orchId = process.env["ACTIONS_ORCHESTRATION_ID"]; - if (orchId) { - const sanitizedId = orchId.replace(/[^a-z0-9_.-]/gi, "_"); - return `${baseUserAgent} actions_orchestration_id/${sanitizedId}`; - } - return baseUserAgent; + function par25519(a) { + var d = new Uint8Array(32); + pack25519(d, a); + return d[0] & 1; } - _performExponentialBackoff(retryNumber) { - return __awaiter3(this, void 0, void 0, function* () { - retryNumber = Math.min(ExponentialBackoffCeiling2, retryNumber); - const ms = ExponentialBackoffTimeSlice2 * Math.pow(2, retryNumber); - return new Promise((resolve) => setTimeout(() => resolve(), ms)); - }); + function unpack25519(o, n) { + var i; + for (i = 0; i < 16; i++) o[i] = n[2 * i] + (n[2 * i + 1] << 8); + o[15] &= 32767; } - _processResponse(res, options) { - return __awaiter3(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => __awaiter3(this, void 0, void 0, function* () { - const statusCode = res.message.statusCode || 0; - const response = { - statusCode, - result: null, - headers: {} - }; - if (statusCode === HttpCodes2.NotFound) { - resolve(response); - } - function dateTimeDeserializer(key, value) { - if (typeof value === "string") { - const a = new Date(value); - if (!isNaN(a.valueOf())) { - return a; - } - } - return value; - } - let obj; - let contents; - try { - contents = yield res.readBody(); - if (contents && contents.length > 0) { - if (options && options.deserializeDates) { - obj = JSON.parse(contents, dateTimeDeserializer); - } else { - obj = JSON.parse(contents); - } - response.result = obj; - } - response.headers = res.message.headers; - } catch (err) { - } - if (statusCode > 299) { - let msg; - if (obj && obj.message) { - msg = obj.message; - } else if (contents && contents.length > 0) { - msg = contents; - } else { - msg = `Failed request: (${statusCode})`; - } - const err = new HttpClientError2(msg, statusCode); - err.result = response.result; - reject(err); - } else { - resolve(response); - } - })); - }); + function A(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; } - }; - exports2.HttpClient = HttpClient3; - var lowercaseKeys3 = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); - } -}); - -// node_modules/docker-modem/lib/utils.js -var require_utils3 = __commonJS({ - "node_modules/docker-modem/lib/utils.js"(exports2, module2) { - var arr = []; - var each = arr.forEach; - var slice = arr.slice; - module2.exports.extend = function(obj) { - each.call(slice.call(arguments, 1), function(source) { - if (source) { - for (var prop in source) { - obj[prop] = source[prop]; - } - } - }); - return obj; - }; - module2.exports.parseJSON = function(s) { - try { - return JSON.parse(s); - } catch (e) { - return null; + function Z(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; } - }; - } -}); - -// node_modules/docker-modem/lib/http.js -var require_http = __commonJS({ - "node_modules/docker-modem/lib/http.js"(exports2, module2) { - var nativeHttps = require("https"); - var nativeHttp = require("http"); - var url = require("url"); - var utils = require_utils3(); - var maxRedirects = module2.exports.maxRedirects = 5; - var protocols = { - https: nativeHttps, - http: nativeHttp - }; - for (protocol in protocols) { - h = function() { - }; - h.prototype = protocols[protocol]; - h = new h(); - h.request = /* @__PURE__ */ (function(h2) { - return function(options, callback, redirectOptions) { - redirectOptions = redirectOptions || {}; - var max = typeof options === "object" && "maxRedirects" in options ? options.maxRedirects : exports2.maxRedirects; - var redirect = utils.extend({ - count: 0, - max, - clientRequest: null, - userCallback: callback - }, redirectOptions); - if (redirect.count > redirect.max) { - var err = new Error("Max redirects exceeded. To allow more redirects, pass options.maxRedirects property."); - redirect.clientRequest.emit("error", err); - return redirect.clientRequest; - } - redirect.count++; - var reqUrl; - if (typeof options === "string") { - reqUrl = options; - } else { - reqUrl = url.format(utils.extend({ - protocol - }, options)); - } - var clientRequest = Object.getPrototypeOf(h2).request(options, redirectCallback(reqUrl, redirect)); - if (!redirect.clientRequest) redirect.clientRequest = clientRequest; - function redirectCallback(reqUrl2, redirect2) { - return function(res) { - if (res.statusCode < 300 || res.statusCode > 399) { - return redirect2.userCallback(res); - } - if (!("location" in res.headers)) { - return redirect2.userCallback(res); - } - var redirectUrl = url.resolve(reqUrl2, res.headers.location); - var proto = url.parse(redirectUrl).protocol; - proto = proto.substr(0, proto.length - 1); - return module2.exports[proto].get(redirectUrl, redirectCallback(reqUrl2, redirect2), redirect2); - }; - } - return clientRequest; - }; - })(h); - h.get = /* @__PURE__ */ (function(h2) { - return function(options, cb, redirectOptions) { - var req = h2.request(options, cb, redirectOptions); - req.end(); - return req; - }; - })(h); - module2.exports[protocol] = h; - } - var h; - var protocol; - } -}); - -// node_modules/asn1/lib/ber/errors.js -var require_errors2 = __commonJS({ - "node_modules/asn1/lib/ber/errors.js"(exports2, module2) { - module2.exports = { - newInvalidAsn1Error: function(msg) { - var e = new Error(); - e.name = "InvalidAsn1Error"; - e.message = msg || ""; - return e; + function M(o, a, b) { + var v, c, t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3], b4 = b[4], b5 = b[5], b6 = b[6], b7 = b[7], b8 = b[8], b9 = b[9], b10 = b[10], b11 = b[11], b12 = b[12], b13 = b[13], b14 = b[14], b15 = b[15]; + v = a[0]; + t0 += v * b0; + t1 += v * b1; + t2 += v * b2; + t3 += v * b3; + t4 += v * b4; + t5 += v * b5; + t6 += v * b6; + t7 += v * b7; + t8 += v * b8; + t9 += v * b9; + t10 += v * b10; + t11 += v * b11; + t12 += v * b12; + t13 += v * b13; + t14 += v * b14; + t15 += v * b15; + v = a[1]; + t1 += v * b0; + t2 += v * b1; + t3 += v * b2; + t4 += v * b3; + t5 += v * b4; + t6 += v * b5; + t7 += v * b6; + t8 += v * b7; + t9 += v * b8; + t10 += v * b9; + t11 += v * b10; + t12 += v * b11; + t13 += v * b12; + t14 += v * b13; + t15 += v * b14; + t16 += v * b15; + v = a[2]; + t2 += v * b0; + t3 += v * b1; + t4 += v * b2; + t5 += v * b3; + t6 += v * b4; + t7 += v * b5; + t8 += v * b6; + t9 += v * b7; + t10 += v * b8; + t11 += v * b9; + t12 += v * b10; + t13 += v * b11; + t14 += v * b12; + t15 += v * b13; + t16 += v * b14; + t17 += v * b15; + v = a[3]; + t3 += v * b0; + t4 += v * b1; + t5 += v * b2; + t6 += v * b3; + t7 += v * b4; + t8 += v * b5; + t9 += v * b6; + t10 += v * b7; + t11 += v * b8; + t12 += v * b9; + t13 += v * b10; + t14 += v * b11; + t15 += v * b12; + t16 += v * b13; + t17 += v * b14; + t18 += v * b15; + v = a[4]; + t4 += v * b0; + t5 += v * b1; + t6 += v * b2; + t7 += v * b3; + t8 += v * b4; + t9 += v * b5; + t10 += v * b6; + t11 += v * b7; + t12 += v * b8; + t13 += v * b9; + t14 += v * b10; + t15 += v * b11; + t16 += v * b12; + t17 += v * b13; + t18 += v * b14; + t19 += v * b15; + v = a[5]; + t5 += v * b0; + t6 += v * b1; + t7 += v * b2; + t8 += v * b3; + t9 += v * b4; + t10 += v * b5; + t11 += v * b6; + t12 += v * b7; + t13 += v * b8; + t14 += v * b9; + t15 += v * b10; + t16 += v * b11; + t17 += v * b12; + t18 += v * b13; + t19 += v * b14; + t20 += v * b15; + v = a[6]; + t6 += v * b0; + t7 += v * b1; + t8 += v * b2; + t9 += v * b3; + t10 += v * b4; + t11 += v * b5; + t12 += v * b6; + t13 += v * b7; + t14 += v * b8; + t15 += v * b9; + t16 += v * b10; + t17 += v * b11; + t18 += v * b12; + t19 += v * b13; + t20 += v * b14; + t21 += v * b15; + v = a[7]; + t7 += v * b0; + t8 += v * b1; + t9 += v * b2; + t10 += v * b3; + t11 += v * b4; + t12 += v * b5; + t13 += v * b6; + t14 += v * b7; + t15 += v * b8; + t16 += v * b9; + t17 += v * b10; + t18 += v * b11; + t19 += v * b12; + t20 += v * b13; + t21 += v * b14; + t22 += v * b15; + v = a[8]; + t8 += v * b0; + t9 += v * b1; + t10 += v * b2; + t11 += v * b3; + t12 += v * b4; + t13 += v * b5; + t14 += v * b6; + t15 += v * b7; + t16 += v * b8; + t17 += v * b9; + t18 += v * b10; + t19 += v * b11; + t20 += v * b12; + t21 += v * b13; + t22 += v * b14; + t23 += v * b15; + v = a[9]; + t9 += v * b0; + t10 += v * b1; + t11 += v * b2; + t12 += v * b3; + t13 += v * b4; + t14 += v * b5; + t15 += v * b6; + t16 += v * b7; + t17 += v * b8; + t18 += v * b9; + t19 += v * b10; + t20 += v * b11; + t21 += v * b12; + t22 += v * b13; + t23 += v * b14; + t24 += v * b15; + v = a[10]; + t10 += v * b0; + t11 += v * b1; + t12 += v * b2; + t13 += v * b3; + t14 += v * b4; + t15 += v * b5; + t16 += v * b6; + t17 += v * b7; + t18 += v * b8; + t19 += v * b9; + t20 += v * b10; + t21 += v * b11; + t22 += v * b12; + t23 += v * b13; + t24 += v * b14; + t25 += v * b15; + v = a[11]; + t11 += v * b0; + t12 += v * b1; + t13 += v * b2; + t14 += v * b3; + t15 += v * b4; + t16 += v * b5; + t17 += v * b6; + t18 += v * b7; + t19 += v * b8; + t20 += v * b9; + t21 += v * b10; + t22 += v * b11; + t23 += v * b12; + t24 += v * b13; + t25 += v * b14; + t26 += v * b15; + v = a[12]; + t12 += v * b0; + t13 += v * b1; + t14 += v * b2; + t15 += v * b3; + t16 += v * b4; + t17 += v * b5; + t18 += v * b6; + t19 += v * b7; + t20 += v * b8; + t21 += v * b9; + t22 += v * b10; + t23 += v * b11; + t24 += v * b12; + t25 += v * b13; + t26 += v * b14; + t27 += v * b15; + v = a[13]; + t13 += v * b0; + t14 += v * b1; + t15 += v * b2; + t16 += v * b3; + t17 += v * b4; + t18 += v * b5; + t19 += v * b6; + t20 += v * b7; + t21 += v * b8; + t22 += v * b9; + t23 += v * b10; + t24 += v * b11; + t25 += v * b12; + t26 += v * b13; + t27 += v * b14; + t28 += v * b15; + v = a[14]; + t14 += v * b0; + t15 += v * b1; + t16 += v * b2; + t17 += v * b3; + t18 += v * b4; + t19 += v * b5; + t20 += v * b6; + t21 += v * b7; + t22 += v * b8; + t23 += v * b9; + t24 += v * b10; + t25 += v * b11; + t26 += v * b12; + t27 += v * b13; + t28 += v * b14; + t29 += v * b15; + v = a[15]; + t15 += v * b0; + t16 += v * b1; + t17 += v * b2; + t18 += v * b3; + t19 += v * b4; + t20 += v * b5; + t21 += v * b6; + t22 += v * b7; + t23 += v * b8; + t24 += v * b9; + t25 += v * b10; + t26 += v * b11; + t27 += v * b12; + t28 += v * b13; + t29 += v * b14; + t30 += v * b15; + t0 += 38 * t16; + t1 += 38 * t17; + t2 += 38 * t18; + t3 += 38 * t19; + t4 += 38 * t20; + t5 += 38 * t21; + t6 += 38 * t22; + t7 += 38 * t23; + t8 += 38 * t24; + t9 += 38 * t25; + t10 += 38 * t26; + t11 += 38 * t27; + t12 += 38 * t28; + t13 += 38 * t29; + t14 += 38 * t30; + c = 1; + v = t0 + c + 65535; + c = Math.floor(v / 65536); + t0 = v - c * 65536; + v = t1 + c + 65535; + c = Math.floor(v / 65536); + t1 = v - c * 65536; + v = t2 + c + 65535; + c = Math.floor(v / 65536); + t2 = v - c * 65536; + v = t3 + c + 65535; + c = Math.floor(v / 65536); + t3 = v - c * 65536; + v = t4 + c + 65535; + c = Math.floor(v / 65536); + t4 = v - c * 65536; + v = t5 + c + 65535; + c = Math.floor(v / 65536); + t5 = v - c * 65536; + v = t6 + c + 65535; + c = Math.floor(v / 65536); + t6 = v - c * 65536; + v = t7 + c + 65535; + c = Math.floor(v / 65536); + t7 = v - c * 65536; + v = t8 + c + 65535; + c = Math.floor(v / 65536); + t8 = v - c * 65536; + v = t9 + c + 65535; + c = Math.floor(v / 65536); + t9 = v - c * 65536; + v = t10 + c + 65535; + c = Math.floor(v / 65536); + t10 = v - c * 65536; + v = t11 + c + 65535; + c = Math.floor(v / 65536); + t11 = v - c * 65536; + v = t12 + c + 65535; + c = Math.floor(v / 65536); + t12 = v - c * 65536; + v = t13 + c + 65535; + c = Math.floor(v / 65536); + t13 = v - c * 65536; + v = t14 + c + 65535; + c = Math.floor(v / 65536); + t14 = v - c * 65536; + v = t15 + c + 65535; + c = Math.floor(v / 65536); + t15 = v - c * 65536; + t0 += c - 1 + 37 * (c - 1); + c = 1; + v = t0 + c + 65535; + c = Math.floor(v / 65536); + t0 = v - c * 65536; + v = t1 + c + 65535; + c = Math.floor(v / 65536); + t1 = v - c * 65536; + v = t2 + c + 65535; + c = Math.floor(v / 65536); + t2 = v - c * 65536; + v = t3 + c + 65535; + c = Math.floor(v / 65536); + t3 = v - c * 65536; + v = t4 + c + 65535; + c = Math.floor(v / 65536); + t4 = v - c * 65536; + v = t5 + c + 65535; + c = Math.floor(v / 65536); + t5 = v - c * 65536; + v = t6 + c + 65535; + c = Math.floor(v / 65536); + t6 = v - c * 65536; + v = t7 + c + 65535; + c = Math.floor(v / 65536); + t7 = v - c * 65536; + v = t8 + c + 65535; + c = Math.floor(v / 65536); + t8 = v - c * 65536; + v = t9 + c + 65535; + c = Math.floor(v / 65536); + t9 = v - c * 65536; + v = t10 + c + 65535; + c = Math.floor(v / 65536); + t10 = v - c * 65536; + v = t11 + c + 65535; + c = Math.floor(v / 65536); + t11 = v - c * 65536; + v = t12 + c + 65535; + c = Math.floor(v / 65536); + t12 = v - c * 65536; + v = t13 + c + 65535; + c = Math.floor(v / 65536); + t13 = v - c * 65536; + v = t14 + c + 65535; + c = Math.floor(v / 65536); + t14 = v - c * 65536; + v = t15 + c + 65535; + c = Math.floor(v / 65536); + t15 = v - c * 65536; + t0 += c - 1 + 37 * (c - 1); + o[0] = t0; + o[1] = t1; + o[2] = t2; + o[3] = t3; + o[4] = t4; + o[5] = t5; + o[6] = t6; + o[7] = t7; + o[8] = t8; + o[9] = t9; + o[10] = t10; + o[11] = t11; + o[12] = t12; + o[13] = t13; + o[14] = t14; + o[15] = t15; } - }; - } -}); - -// node_modules/asn1/lib/ber/types.js -var require_types = __commonJS({ - "node_modules/asn1/lib/ber/types.js"(exports2, module2) { - module2.exports = { - EOC: 0, - Boolean: 1, - Integer: 2, - BitString: 3, - OctetString: 4, - Null: 5, - OID: 6, - ObjectDescriptor: 7, - External: 8, - Real: 9, - // float - Enumeration: 10, - PDV: 11, - Utf8String: 12, - RelativeOID: 13, - Sequence: 16, - Set: 17, - NumericString: 18, - PrintableString: 19, - T61String: 20, - VideotexString: 21, - IA5String: 22, - UTCTime: 23, - GeneralizedTime: 24, - GraphicString: 25, - VisibleString: 26, - GeneralString: 28, - UniversalString: 29, - CharacterString: 30, - BMPString: 31, - Constructor: 32, - Context: 128 - }; - } -}); - -// node_modules/safer-buffer/safer.js -var require_safer = __commonJS({ - "node_modules/safer-buffer/safer.js"(exports2, module2) { - "use strict"; - var buffer = require("buffer"); - var Buffer2 = buffer.Buffer; - var safer = {}; - var key; - for (key in buffer) { - if (!buffer.hasOwnProperty(key)) continue; - if (key === "SlowBuffer" || key === "Buffer") continue; - safer[key] = buffer[key]; - } - var Safer = safer.Buffer = {}; - for (key in Buffer2) { - if (!Buffer2.hasOwnProperty(key)) continue; - if (key === "allocUnsafe" || key === "allocUnsafeSlow") continue; - Safer[key] = Buffer2[key]; - } - safer.Buffer.prototype = Buffer2.prototype; - if (!Safer.from || Safer.from === Uint8Array.from) { - Safer.from = function(value, encodingOrOffset, length) { - if (typeof value === "number") { - throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value); - } - if (value && typeof value.length === "undefined") { - throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value); - } - return Buffer2(value, encodingOrOffset, length); - }; - } - if (!Safer.alloc) { - Safer.alloc = function(size, fill, encoding) { - if (typeof size !== "number") { - throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size); + function S(o, a) { + M(o, a, a); + } + function inv25519(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 253; a >= 0; a--) { + S(c, c); + if (a !== 2 && a !== 4) M(c, c, i); } - if (size < 0 || size >= 2 * (1 << 30)) { - throw new RangeError('The value "' + size + '" is invalid for option "size"'); + for (a = 0; a < 16; a++) o[a] = c[a]; + } + function pow2523(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 250; a >= 0; a--) { + S(c, c); + if (a !== 1) M(c, c, i); } - var buf = Buffer2(size); - if (!fill || fill.length === 0) { - buf.fill(0); - } else if (typeof encoding === "string") { - buf.fill(fill, encoding); - } else { - buf.fill(fill); - } - return buf; - }; - } - if (!safer.kStringMaxLength) { - try { - safer.kStringMaxLength = process.binding("buffer").kStringMaxLength; - } catch (e) { - } - } - if (!safer.constants) { - safer.constants = { - MAX_LENGTH: safer.kMaxLength - }; - if (safer.kStringMaxLength) { - safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength; - } - } - module2.exports = safer; - } -}); - -// node_modules/asn1/lib/ber/reader.js -var require_reader = __commonJS({ - "node_modules/asn1/lib/ber/reader.js"(exports2, module2) { - var assert = require("assert"); - var Buffer2 = require_safer().Buffer; - var ASN1 = require_types(); - var errors = require_errors2(); - var newInvalidAsn1Error = errors.newInvalidAsn1Error; - function Reader(data) { - if (!data || !Buffer2.isBuffer(data)) - throw new TypeError("data must be a node Buffer"); - this._buf = data; - this._size = data.length; - this._len = 0; - this._offset = 0; - } - Object.defineProperty(Reader.prototype, "length", { - enumerable: true, - get: function() { - return this._len; - } - }); - Object.defineProperty(Reader.prototype, "offset", { - enumerable: true, - get: function() { - return this._offset; - } - }); - Object.defineProperty(Reader.prototype, "remain", { - get: function() { - return this._size - this._offset; - } - }); - Object.defineProperty(Reader.prototype, "buffer", { - get: function() { - return this._buf.slice(this._offset); - } - }); - Reader.prototype.readByte = function(peek) { - if (this._size - this._offset < 1) - return null; - var b = this._buf[this._offset] & 255; - if (!peek) - this._offset += 1; - return b; - }; - Reader.prototype.peek = function() { - return this.readByte(true); - }; - Reader.prototype.readLength = function(offset) { - if (offset === void 0) - offset = this._offset; - if (offset >= this._size) - return null; - var lenB = this._buf[offset++] & 255; - if (lenB === null) - return null; - if ((lenB & 128) === 128) { - lenB &= 127; - if (lenB === 0) - throw newInvalidAsn1Error("Indefinite length not supported"); - if (lenB > 4) - throw newInvalidAsn1Error("encoding too long"); - if (this._size - offset < lenB) - return null; - this._len = 0; - for (var i = 0; i < lenB; i++) - this._len = (this._len << 8) + (this._buf[offset++] & 255); - } else { - this._len = lenB; + for (a = 0; a < 16; a++) o[a] = c[a]; } - return offset; - }; - Reader.prototype.readSequence = function(tag) { - var seq = this.peek(); - if (seq === null) - return null; - if (tag !== void 0 && tag !== seq) - throw newInvalidAsn1Error("Expected 0x" + tag.toString(16) + ": got 0x" + seq.toString(16)); - var o = this.readLength(this._offset + 1); - if (o === null) - return null; - this._offset = o; - return seq; - }; - Reader.prototype.readInt = function() { - return this._readTag(ASN1.Integer); - }; - Reader.prototype.readBoolean = function() { - return this._readTag(ASN1.Boolean) === 0 ? false : true; - }; - Reader.prototype.readEnumeration = function() { - return this._readTag(ASN1.Enumeration); - }; - Reader.prototype.readString = function(tag, retbuf) { - if (!tag) - tag = ASN1.OctetString; - var b = this.peek(); - if (b === null) - return null; - if (b !== tag) - throw newInvalidAsn1Error("Expected 0x" + tag.toString(16) + ": got 0x" + b.toString(16)); - var o = this.readLength(this._offset + 1); - if (o === null) - return null; - if (this.length > this._size - o) - return null; - this._offset = o; - if (this.length === 0) - return retbuf ? Buffer2.alloc(0) : ""; - var str = this._buf.slice(this._offset, this._offset + this.length); - this._offset += this.length; - return retbuf ? str : str.toString("utf8"); - }; - Reader.prototype.readOID = function(tag) { - if (!tag) - tag = ASN1.OID; - var b = this.readString(tag, true); - if (b === null) - return null; - var values = []; - var value = 0; - for (var i = 0; i < b.length; i++) { - var byte = b[i] & 255; - value <<= 7; - value += byte & 127; - if ((byte & 128) === 0) { - values.push(value); - value = 0; + function crypto_scalarmult(q, n, p) { + var z = new Uint8Array(32); + var x = new Float64Array(80), r, i; + var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(); + for (i = 0; i < 31; i++) z[i] = n[i]; + z[31] = n[31] & 127 | 64; + z[0] &= 248; + unpack25519(x, p); + for (i = 0; i < 16; i++) { + b[i] = x[i]; + d[i] = a[i] = c[i] = 0; } + a[0] = d[0] = 1; + for (i = 254; i >= 0; --i) { + r = z[i >>> 3] >>> (i & 7) & 1; + sel25519(a, b, r); + sel25519(c, d, r); + A(e, a, c); + Z(a, a, c); + A(c, b, d); + Z(b, b, d); + S(d, e); + S(f, a); + M(a, c, a); + M(c, b, e); + A(e, a, c); + Z(a, a, c); + S(b, a); + Z(c, d, f); + M(a, c, _121665); + A(a, a, d); + M(c, c, a); + M(a, d, f); + M(d, b, x); + S(b, e); + sel25519(a, b, r); + sel25519(c, d, r); + } + for (i = 0; i < 16; i++) { + x[i + 16] = a[i]; + x[i + 32] = c[i]; + x[i + 48] = b[i]; + x[i + 64] = d[i]; + } + var x32 = x.subarray(32); + var x16 = x.subarray(16); + inv25519(x32, x32); + M(x16, x16, x32); + pack25519(q, x16); + return 0; } - value = values.shift(); - values.unshift(value % 40); - values.unshift(value / 40 >> 0); - return values.join("."); - }; - Reader.prototype._readTag = function(tag) { - assert.ok(tag !== void 0); - var b = this.peek(); - if (b === null) - return null; - if (b !== tag) - throw newInvalidAsn1Error("Expected 0x" + tag.toString(16) + ": got 0x" + b.toString(16)); - var o = this.readLength(this._offset + 1); - if (o === null) - return null; - if (this.length > 4) - throw newInvalidAsn1Error("Integer too long: " + this.length); - if (this.length > this._size - o) - return null; - this._offset = o; - var fb = this._buf[this._offset]; - var value = 0; - for (var i = 0; i < this.length; i++) { - value <<= 8; - value |= this._buf[this._offset++] & 255; - } - if ((fb & 128) === 128 && i !== 4) - value -= 1 << i * 8; - return value >> 0; - }; - module2.exports = Reader; - } -}); - -// node_modules/asn1/lib/ber/writer.js -var require_writer = __commonJS({ - "node_modules/asn1/lib/ber/writer.js"(exports2, module2) { - var assert = require("assert"); - var Buffer2 = require_safer().Buffer; - var ASN1 = require_types(); - var errors = require_errors2(); - var newInvalidAsn1Error = errors.newInvalidAsn1Error; - var DEFAULT_OPTS = { - size: 1024, - growthFactor: 8 - }; - function merge2(from, to) { - assert.ok(from); - assert.equal(typeof from, "object"); - assert.ok(to); - assert.equal(typeof to, "object"); - var keys = Object.getOwnPropertyNames(from); - keys.forEach(function(key) { - if (to[key]) - return; - var value = Object.getOwnPropertyDescriptor(from, key); - Object.defineProperty(to, key, value); - }); - return to; - } - function Writer(options) { - options = merge2(DEFAULT_OPTS, options || {}); - this._buf = Buffer2.alloc(options.size || 1024); - this._size = this._buf.length; - this._offset = 0; - this._options = options; - this._seq = []; - } - Object.defineProperty(Writer.prototype, "buffer", { - get: function() { - if (this._seq.length) - throw newInvalidAsn1Error(this._seq.length + " unended sequence(s)"); - return this._buf.slice(0, this._offset); - } - }); - Writer.prototype.writeByte = function(b) { - if (typeof b !== "number") - throw new TypeError("argument must be a Number"); - this._ensure(1); - this._buf[this._offset++] = b; - }; - Writer.prototype.writeInt = function(i, tag) { - if (typeof i !== "number") - throw new TypeError("argument must be a Number"); - if (typeof tag !== "number") - tag = ASN1.Integer; - var sz = 4; - while (((i & 4286578688) === 0 || (i & 4286578688) === 4286578688 >> 0) && sz > 1) { - sz--; - i <<= 8; - } - if (sz > 4) - throw newInvalidAsn1Error("BER ints cannot be > 0xffffffff"); - this._ensure(2 + sz); - this._buf[this._offset++] = tag; - this._buf[this._offset++] = sz; - while (sz-- > 0) { - this._buf[this._offset++] = (i & 4278190080) >>> 24; - i <<= 8; - } - }; - Writer.prototype.writeNull = function() { - this.writeByte(ASN1.Null); - this.writeByte(0); - }; - Writer.prototype.writeEnumeration = function(i, tag) { - if (typeof i !== "number") - throw new TypeError("argument must be a Number"); - if (typeof tag !== "number") - tag = ASN1.Enumeration; - return this.writeInt(i, tag); - }; - Writer.prototype.writeBoolean = function(b, tag) { - if (typeof b !== "boolean") - throw new TypeError("argument must be a Boolean"); - if (typeof tag !== "number") - tag = ASN1.Boolean; - this._ensure(3); - this._buf[this._offset++] = tag; - this._buf[this._offset++] = 1; - this._buf[this._offset++] = b ? 255 : 0; - }; - Writer.prototype.writeString = function(s, tag) { - if (typeof s !== "string") - throw new TypeError("argument must be a string (was: " + typeof s + ")"); - if (typeof tag !== "number") - tag = ASN1.OctetString; - var len = Buffer2.byteLength(s); - this.writeByte(tag); - this.writeLength(len); - if (len) { - this._ensure(len); - this._buf.write(s, this._offset); - this._offset += len; + function crypto_scalarmult_base(q, n) { + return crypto_scalarmult(q, n, _9); } - }; - Writer.prototype.writeBuffer = function(buf, tag) { - if (typeof tag !== "number") - throw new TypeError("tag must be a number"); - if (!Buffer2.isBuffer(buf)) - throw new TypeError("argument must be a buffer"); - this.writeByte(tag); - this.writeLength(buf.length); - this._ensure(buf.length); - buf.copy(this._buf, this._offset, 0, buf.length); - this._offset += buf.length; - }; - Writer.prototype.writeStringArray = function(strings) { - if (!strings instanceof Array) - throw new TypeError("argument must be an Array[String]"); - var self2 = this; - strings.forEach(function(s) { - self2.writeString(s); - }); - }; - Writer.prototype.writeOID = function(s, tag) { - if (typeof s !== "string") - throw new TypeError("argument must be a string"); - if (typeof tag !== "number") - tag = ASN1.OID; - if (!/^([0-9]+\.){3,}[0-9]+$/.test(s)) - throw new Error("argument is not a valid OID string"); - function encodeOctet(bytes2, octet) { - if (octet < 128) { - bytes2.push(octet); - } else if (octet < 16384) { - bytes2.push(octet >>> 7 | 128); - bytes2.push(octet & 127); - } else if (octet < 2097152) { - bytes2.push(octet >>> 14 | 128); - bytes2.push((octet >>> 7 | 128) & 255); - bytes2.push(octet & 127); - } else if (octet < 268435456) { - bytes2.push(octet >>> 21 | 128); - bytes2.push((octet >>> 14 | 128) & 255); - bytes2.push((octet >>> 7 | 128) & 255); - bytes2.push(octet & 127); - } else { - bytes2.push((octet >>> 28 | 128) & 255); - bytes2.push((octet >>> 21 | 128) & 255); - bytes2.push((octet >>> 14 | 128) & 255); - bytes2.push((octet >>> 7 | 128) & 255); - bytes2.push(octet & 127); - } + function crypto_box_keypair(y, x) { + randombytes(x, 32); + return crypto_scalarmult_base(y, x); } - var tmp = s.split("."); - var bytes = []; - bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10)); - tmp.slice(2).forEach(function(b) { - encodeOctet(bytes, parseInt(b, 10)); - }); - var self2 = this; - this._ensure(2 + bytes.length); - this.writeByte(tag); - this.writeLength(bytes.length); - bytes.forEach(function(b) { - self2.writeByte(b); - }); - }; - Writer.prototype.writeLength = function(len) { - if (typeof len !== "number") - throw new TypeError("argument must be a Number"); - this._ensure(4); - if (len <= 127) { - this._buf[this._offset++] = len; - } else if (len <= 255) { - this._buf[this._offset++] = 129; - this._buf[this._offset++] = len; - } else if (len <= 65535) { - this._buf[this._offset++] = 130; - this._buf[this._offset++] = len >> 8; - this._buf[this._offset++] = len; - } else if (len <= 16777215) { - this._buf[this._offset++] = 131; - this._buf[this._offset++] = len >> 16; - this._buf[this._offset++] = len >> 8; - this._buf[this._offset++] = len; - } else { - throw newInvalidAsn1Error("Length too long (> 4 bytes)"); + function crypto_box_beforenm(k, y, x) { + var s = new Uint8Array(32); + crypto_scalarmult(s, x, y); + return crypto_core_hsalsa20(k, _0, s, sigma); } - }; - Writer.prototype.startSequence = function(tag) { - if (typeof tag !== "number") - tag = ASN1.Sequence | ASN1.Constructor; - this.writeByte(tag); - this._seq.push(this._offset); - this._ensure(3); - this._offset += 3; - }; - Writer.prototype.endSequence = function() { - var seq = this._seq.pop(); - var start = seq + 3; - var len = this._offset - start; - if (len <= 127) { - this._shift(start, len, -2); - this._buf[seq] = len; - } else if (len <= 255) { - this._shift(start, len, -1); - this._buf[seq] = 129; - this._buf[seq + 1] = len; - } else if (len <= 65535) { - this._buf[seq] = 130; - this._buf[seq + 1] = len >> 8; - this._buf[seq + 2] = len; - } else if (len <= 16777215) { - this._shift(start, len, 1); - this._buf[seq] = 131; - this._buf[seq + 1] = len >> 16; - this._buf[seq + 2] = len >> 8; - this._buf[seq + 3] = len; - } else { - throw newInvalidAsn1Error("Sequence too long"); + var crypto_box_afternm = crypto_secretbox; + var crypto_box_open_afternm = crypto_secretbox_open; + function crypto_box(c, m, d, n, y, x) { + var k = new Uint8Array(32); + crypto_box_beforenm(k, y, x); + return crypto_box_afternm(c, m, d, n, k); } - }; - Writer.prototype._shift = function(start, len, shift) { - assert.ok(start !== void 0); - assert.ok(len !== void 0); - assert.ok(shift); - this._buf.copy(this._buf, start + shift, start, start + len); - this._offset += shift; - }; - Writer.prototype._ensure = function(len) { - assert.ok(len); - if (this._size - this._offset < len) { - var sz = this._size * this._options.growthFactor; - if (sz - this._offset < len) - sz += len; - var buf = Buffer2.alloc(sz); - this._buf.copy(buf, 0, 0, this._offset); - this._buf = buf; - this._size = sz; + function crypto_box_open(m, c, d, n, y, x) { + var k = new Uint8Array(32); + crypto_box_beforenm(k, y, x); + return crypto_box_open_afternm(m, c, d, n, k); } - }; - module2.exports = Writer; - } -}); - -// node_modules/asn1/lib/ber/index.js -var require_ber = __commonJS({ - "node_modules/asn1/lib/ber/index.js"(exports2, module2) { - var errors = require_errors2(); - var types = require_types(); - var Reader = require_reader(); - var Writer = require_writer(); - module2.exports = { - Reader, - Writer - }; - for (t in types) { - if (types.hasOwnProperty(t)) - module2.exports[t] = types[t]; - } - var t; - for (e in errors) { - if (errors.hasOwnProperty(e)) - module2.exports[e] = errors[e]; - } - var e; - } -}); - -// node_modules/asn1/lib/index.js -var require_lib3 = __commonJS({ - "node_modules/asn1/lib/index.js"(exports2, module2) { - var Ber = require_ber(); - module2.exports = { - Ber, - BerReader: Ber.Reader, - BerWriter: Ber.Writer - }; - } -}); - -// node_modules/tweetnacl/nacl-fast.js -var require_nacl_fast = __commonJS({ - "node_modules/tweetnacl/nacl-fast.js"(exports2, module2) { - (function(nacl) { - "use strict"; - var gf = function(init) { - var i, r = new Float64Array(16); - if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; - return r; - }; - var randombytes = function() { - throw new Error("no PRNG"); - }; - var _0 = new Uint8Array(16); - var _9 = new Uint8Array(32); - _9[0] = 9; - var gf0 = gf(), gf1 = gf([1]), _121665 = gf([56129, 1]), D = gf([30883, 4953, 19914, 30187, 55467, 16705, 2637, 112, 59544, 30585, 16505, 36039, 65139, 11119, 27886, 20995]), D2 = gf([61785, 9906, 39828, 60374, 45398, 33411, 5274, 224, 53552, 61171, 33010, 6542, 64743, 22239, 55772, 9222]), X = gf([54554, 36645, 11616, 51542, 42930, 38181, 51040, 26924, 56412, 64982, 57905, 49316, 21502, 52590, 14035, 8553]), Y = gf([26200, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214]), I = gf([41136, 18958, 6951, 50414, 58488, 44335, 6150, 12099, 55207, 15867, 153, 11085, 57099, 20417, 9344, 11139]); - function ts64(x, i, h, l) { - x[i] = h >> 24 & 255; - x[i + 1] = h >> 16 & 255; - x[i + 2] = h >> 8 & 255; - x[i + 3] = h & 255; - x[i + 4] = l >> 24 & 255; - x[i + 5] = l >> 16 & 255; - x[i + 6] = l >> 8 & 255; - x[i + 7] = l & 255; - } - function vn(x, xi, y, yi, n) { - var i, d = 0; - for (i = 0; i < n; i++) d |= x[xi + i] ^ y[yi + i]; - return (1 & d - 1 >>> 8) - 1; - } - function crypto_verify_16(x, xi, y, yi) { - return vn(x, xi, y, yi, 16); - } - function crypto_verify_32(x, xi, y, yi) { - return vn(x, xi, y, yi, 32); - } - function core_salsa20(o, p, k, c) { - var j0 = c[0] & 255 | (c[1] & 255) << 8 | (c[2] & 255) << 16 | (c[3] & 255) << 24, j1 = k[0] & 255 | (k[1] & 255) << 8 | (k[2] & 255) << 16 | (k[3] & 255) << 24, j2 = k[4] & 255 | (k[5] & 255) << 8 | (k[6] & 255) << 16 | (k[7] & 255) << 24, j3 = k[8] & 255 | (k[9] & 255) << 8 | (k[10] & 255) << 16 | (k[11] & 255) << 24, j4 = k[12] & 255 | (k[13] & 255) << 8 | (k[14] & 255) << 16 | (k[15] & 255) << 24, j5 = c[4] & 255 | (c[5] & 255) << 8 | (c[6] & 255) << 16 | (c[7] & 255) << 24, j6 = p[0] & 255 | (p[1] & 255) << 8 | (p[2] & 255) << 16 | (p[3] & 255) << 24, j7 = p[4] & 255 | (p[5] & 255) << 8 | (p[6] & 255) << 16 | (p[7] & 255) << 24, j8 = p[8] & 255 | (p[9] & 255) << 8 | (p[10] & 255) << 16 | (p[11] & 255) << 24, j9 = p[12] & 255 | (p[13] & 255) << 8 | (p[14] & 255) << 16 | (p[15] & 255) << 24, j10 = c[8] & 255 | (c[9] & 255) << 8 | (c[10] & 255) << 16 | (c[11] & 255) << 24, j11 = k[16] & 255 | (k[17] & 255) << 8 | (k[18] & 255) << 16 | (k[19] & 255) << 24, j12 = k[20] & 255 | (k[21] & 255) << 8 | (k[22] & 255) << 16 | (k[23] & 255) << 24, j13 = k[24] & 255 | (k[25] & 255) << 8 | (k[26] & 255) << 16 | (k[27] & 255) << 24, j14 = k[28] & 255 | (k[29] & 255) << 8 | (k[30] & 255) << 16 | (k[31] & 255) << 24, j15 = c[12] & 255 | (c[13] & 255) << 8 | (c[14] & 255) << 16 | (c[15] & 255) << 24; - var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, x15 = j15, u; - for (var i = 0; i < 20; i += 2) { - u = x0 + x12 | 0; - x4 ^= u << 7 | u >>> 32 - 7; - u = x4 + x0 | 0; - x8 ^= u << 9 | u >>> 32 - 9; - u = x8 + x4 | 0; - x12 ^= u << 13 | u >>> 32 - 13; - u = x12 + x8 | 0; - x0 ^= u << 18 | u >>> 32 - 18; - u = x5 + x1 | 0; - x9 ^= u << 7 | u >>> 32 - 7; - u = x9 + x5 | 0; - x13 ^= u << 9 | u >>> 32 - 9; - u = x13 + x9 | 0; - x1 ^= u << 13 | u >>> 32 - 13; - u = x1 + x13 | 0; - x5 ^= u << 18 | u >>> 32 - 18; - u = x10 + x6 | 0; - x14 ^= u << 7 | u >>> 32 - 7; - u = x14 + x10 | 0; - x2 ^= u << 9 | u >>> 32 - 9; - u = x2 + x14 | 0; - x6 ^= u << 13 | u >>> 32 - 13; - u = x6 + x2 | 0; - x10 ^= u << 18 | u >>> 32 - 18; - u = x15 + x11 | 0; - x3 ^= u << 7 | u >>> 32 - 7; - u = x3 + x15 | 0; - x7 ^= u << 9 | u >>> 32 - 9; - u = x7 + x3 | 0; - x11 ^= u << 13 | u >>> 32 - 13; - u = x11 + x7 | 0; - x15 ^= u << 18 | u >>> 32 - 18; - u = x0 + x3 | 0; - x1 ^= u << 7 | u >>> 32 - 7; - u = x1 + x0 | 0; - x2 ^= u << 9 | u >>> 32 - 9; - u = x2 + x1 | 0; - x3 ^= u << 13 | u >>> 32 - 13; - u = x3 + x2 | 0; - x0 ^= u << 18 | u >>> 32 - 18; - u = x5 + x4 | 0; - x6 ^= u << 7 | u >>> 32 - 7; - u = x6 + x5 | 0; - x7 ^= u << 9 | u >>> 32 - 9; - u = x7 + x6 | 0; - x4 ^= u << 13 | u >>> 32 - 13; - u = x4 + x7 | 0; - x5 ^= u << 18 | u >>> 32 - 18; - u = x10 + x9 | 0; - x11 ^= u << 7 | u >>> 32 - 7; - u = x11 + x10 | 0; - x8 ^= u << 9 | u >>> 32 - 9; - u = x8 + x11 | 0; - x9 ^= u << 13 | u >>> 32 - 13; - u = x9 + x8 | 0; - x10 ^= u << 18 | u >>> 32 - 18; - u = x15 + x14 | 0; - x12 ^= u << 7 | u >>> 32 - 7; - u = x12 + x15 | 0; - x13 ^= u << 9 | u >>> 32 - 9; - u = x13 + x12 | 0; - x14 ^= u << 13 | u >>> 32 - 13; - u = x14 + x13 | 0; - x15 ^= u << 18 | u >>> 32 - 18; - } - x0 = x0 + j0 | 0; - x1 = x1 + j1 | 0; - x2 = x2 + j2 | 0; - x3 = x3 + j3 | 0; - x4 = x4 + j4 | 0; - x5 = x5 + j5 | 0; - x6 = x6 + j6 | 0; - x7 = x7 + j7 | 0; - x8 = x8 + j8 | 0; - x9 = x9 + j9 | 0; - x10 = x10 + j10 | 0; - x11 = x11 + j11 | 0; - x12 = x12 + j12 | 0; - x13 = x13 + j13 | 0; - x14 = x14 + j14 | 0; - x15 = x15 + j15 | 0; - o[0] = x0 >>> 0 & 255; - o[1] = x0 >>> 8 & 255; - o[2] = x0 >>> 16 & 255; - o[3] = x0 >>> 24 & 255; - o[4] = x1 >>> 0 & 255; - o[5] = x1 >>> 8 & 255; - o[6] = x1 >>> 16 & 255; - o[7] = x1 >>> 24 & 255; - o[8] = x2 >>> 0 & 255; - o[9] = x2 >>> 8 & 255; - o[10] = x2 >>> 16 & 255; - o[11] = x2 >>> 24 & 255; - o[12] = x3 >>> 0 & 255; - o[13] = x3 >>> 8 & 255; - o[14] = x3 >>> 16 & 255; - o[15] = x3 >>> 24 & 255; - o[16] = x4 >>> 0 & 255; - o[17] = x4 >>> 8 & 255; - o[18] = x4 >>> 16 & 255; - o[19] = x4 >>> 24 & 255; - o[20] = x5 >>> 0 & 255; - o[21] = x5 >>> 8 & 255; - o[22] = x5 >>> 16 & 255; - o[23] = x5 >>> 24 & 255; - o[24] = x6 >>> 0 & 255; - o[25] = x6 >>> 8 & 255; - o[26] = x6 >>> 16 & 255; - o[27] = x6 >>> 24 & 255; - o[28] = x7 >>> 0 & 255; - o[29] = x7 >>> 8 & 255; - o[30] = x7 >>> 16 & 255; - o[31] = x7 >>> 24 & 255; - o[32] = x8 >>> 0 & 255; - o[33] = x8 >>> 8 & 255; - o[34] = x8 >>> 16 & 255; - o[35] = x8 >>> 24 & 255; - o[36] = x9 >>> 0 & 255; - o[37] = x9 >>> 8 & 255; - o[38] = x9 >>> 16 & 255; - o[39] = x9 >>> 24 & 255; - o[40] = x10 >>> 0 & 255; - o[41] = x10 >>> 8 & 255; - o[42] = x10 >>> 16 & 255; - o[43] = x10 >>> 24 & 255; - o[44] = x11 >>> 0 & 255; - o[45] = x11 >>> 8 & 255; - o[46] = x11 >>> 16 & 255; - o[47] = x11 >>> 24 & 255; - o[48] = x12 >>> 0 & 255; - o[49] = x12 >>> 8 & 255; - o[50] = x12 >>> 16 & 255; - o[51] = x12 >>> 24 & 255; - o[52] = x13 >>> 0 & 255; - o[53] = x13 >>> 8 & 255; - o[54] = x13 >>> 16 & 255; - o[55] = x13 >>> 24 & 255; - o[56] = x14 >>> 0 & 255; - o[57] = x14 >>> 8 & 255; - o[58] = x14 >>> 16 & 255; - o[59] = x14 >>> 24 & 255; - o[60] = x15 >>> 0 & 255; - o[61] = x15 >>> 8 & 255; - o[62] = x15 >>> 16 & 255; - o[63] = x15 >>> 24 & 255; - } - function core_hsalsa20(o, p, k, c) { - var j0 = c[0] & 255 | (c[1] & 255) << 8 | (c[2] & 255) << 16 | (c[3] & 255) << 24, j1 = k[0] & 255 | (k[1] & 255) << 8 | (k[2] & 255) << 16 | (k[3] & 255) << 24, j2 = k[4] & 255 | (k[5] & 255) << 8 | (k[6] & 255) << 16 | (k[7] & 255) << 24, j3 = k[8] & 255 | (k[9] & 255) << 8 | (k[10] & 255) << 16 | (k[11] & 255) << 24, j4 = k[12] & 255 | (k[13] & 255) << 8 | (k[14] & 255) << 16 | (k[15] & 255) << 24, j5 = c[4] & 255 | (c[5] & 255) << 8 | (c[6] & 255) << 16 | (c[7] & 255) << 24, j6 = p[0] & 255 | (p[1] & 255) << 8 | (p[2] & 255) << 16 | (p[3] & 255) << 24, j7 = p[4] & 255 | (p[5] & 255) << 8 | (p[6] & 255) << 16 | (p[7] & 255) << 24, j8 = p[8] & 255 | (p[9] & 255) << 8 | (p[10] & 255) << 16 | (p[11] & 255) << 24, j9 = p[12] & 255 | (p[13] & 255) << 8 | (p[14] & 255) << 16 | (p[15] & 255) << 24, j10 = c[8] & 255 | (c[9] & 255) << 8 | (c[10] & 255) << 16 | (c[11] & 255) << 24, j11 = k[16] & 255 | (k[17] & 255) << 8 | (k[18] & 255) << 16 | (k[19] & 255) << 24, j12 = k[20] & 255 | (k[21] & 255) << 8 | (k[22] & 255) << 16 | (k[23] & 255) << 24, j13 = k[24] & 255 | (k[25] & 255) << 8 | (k[26] & 255) << 16 | (k[27] & 255) << 24, j14 = k[28] & 255 | (k[29] & 255) << 8 | (k[30] & 255) << 16 | (k[31] & 255) << 24, j15 = c[12] & 255 | (c[13] & 255) << 8 | (c[14] & 255) << 16 | (c[15] & 255) << 24; - var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, x15 = j15, u; - for (var i = 0; i < 20; i += 2) { - u = x0 + x12 | 0; - x4 ^= u << 7 | u >>> 32 - 7; - u = x4 + x0 | 0; - x8 ^= u << 9 | u >>> 32 - 9; - u = x8 + x4 | 0; - x12 ^= u << 13 | u >>> 32 - 13; - u = x12 + x8 | 0; - x0 ^= u << 18 | u >>> 32 - 18; - u = x5 + x1 | 0; - x9 ^= u << 7 | u >>> 32 - 7; - u = x9 + x5 | 0; - x13 ^= u << 9 | u >>> 32 - 9; - u = x13 + x9 | 0; - x1 ^= u << 13 | u >>> 32 - 13; - u = x1 + x13 | 0; - x5 ^= u << 18 | u >>> 32 - 18; - u = x10 + x6 | 0; - x14 ^= u << 7 | u >>> 32 - 7; - u = x14 + x10 | 0; - x2 ^= u << 9 | u >>> 32 - 9; - u = x2 + x14 | 0; - x6 ^= u << 13 | u >>> 32 - 13; - u = x6 + x2 | 0; - x10 ^= u << 18 | u >>> 32 - 18; - u = x15 + x11 | 0; - x3 ^= u << 7 | u >>> 32 - 7; - u = x3 + x15 | 0; - x7 ^= u << 9 | u >>> 32 - 9; - u = x7 + x3 | 0; - x11 ^= u << 13 | u >>> 32 - 13; - u = x11 + x7 | 0; - x15 ^= u << 18 | u >>> 32 - 18; - u = x0 + x3 | 0; - x1 ^= u << 7 | u >>> 32 - 7; - u = x1 + x0 | 0; - x2 ^= u << 9 | u >>> 32 - 9; - u = x2 + x1 | 0; - x3 ^= u << 13 | u >>> 32 - 13; - u = x3 + x2 | 0; - x0 ^= u << 18 | u >>> 32 - 18; - u = x5 + x4 | 0; - x6 ^= u << 7 | u >>> 32 - 7; - u = x6 + x5 | 0; - x7 ^= u << 9 | u >>> 32 - 9; - u = x7 + x6 | 0; - x4 ^= u << 13 | u >>> 32 - 13; - u = x4 + x7 | 0; - x5 ^= u << 18 | u >>> 32 - 18; - u = x10 + x9 | 0; - x11 ^= u << 7 | u >>> 32 - 7; - u = x11 + x10 | 0; - x8 ^= u << 9 | u >>> 32 - 9; - u = x8 + x11 | 0; - x9 ^= u << 13 | u >>> 32 - 13; - u = x9 + x8 | 0; - x10 ^= u << 18 | u >>> 32 - 18; - u = x15 + x14 | 0; - x12 ^= u << 7 | u >>> 32 - 7; - u = x12 + x15 | 0; - x13 ^= u << 9 | u >>> 32 - 9; - u = x13 + x12 | 0; - x14 ^= u << 13 | u >>> 32 - 13; - u = x14 + x13 | 0; - x15 ^= u << 18 | u >>> 32 - 18; - } - o[0] = x0 >>> 0 & 255; - o[1] = x0 >>> 8 & 255; - o[2] = x0 >>> 16 & 255; - o[3] = x0 >>> 24 & 255; - o[4] = x5 >>> 0 & 255; - o[5] = x5 >>> 8 & 255; - o[6] = x5 >>> 16 & 255; - o[7] = x5 >>> 24 & 255; - o[8] = x10 >>> 0 & 255; - o[9] = x10 >>> 8 & 255; - o[10] = x10 >>> 16 & 255; - o[11] = x10 >>> 24 & 255; - o[12] = x15 >>> 0 & 255; - o[13] = x15 >>> 8 & 255; - o[14] = x15 >>> 16 & 255; - o[15] = x15 >>> 24 & 255; - o[16] = x6 >>> 0 & 255; - o[17] = x6 >>> 8 & 255; - o[18] = x6 >>> 16 & 255; - o[19] = x6 >>> 24 & 255; - o[20] = x7 >>> 0 & 255; - o[21] = x7 >>> 8 & 255; - o[22] = x7 >>> 16 & 255; - o[23] = x7 >>> 24 & 255; - o[24] = x8 >>> 0 & 255; - o[25] = x8 >>> 8 & 255; - o[26] = x8 >>> 16 & 255; - o[27] = x8 >>> 24 & 255; - o[28] = x9 >>> 0 & 255; - o[29] = x9 >>> 8 & 255; - o[30] = x9 >>> 16 & 255; - o[31] = x9 >>> 24 & 255; - } - function crypto_core_salsa20(out, inp, k, c) { - core_salsa20(out, inp, k, c); - } - function crypto_core_hsalsa20(out, inp, k, c) { - core_hsalsa20(out, inp, k, c); - } - var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]); - function crypto_stream_salsa20_xor(c, cpos, m, mpos, b, n, k) { - var z = new Uint8Array(16), x = new Uint8Array(64); - var u, i; - for (i = 0; i < 16; i++) z[i] = 0; - for (i = 0; i < 8; i++) z[i] = n[i]; - while (b >= 64) { - crypto_core_salsa20(x, z, k, sigma); - for (i = 0; i < 64; i++) c[cpos + i] = m[mpos + i] ^ x[i]; - u = 1; - for (i = 8; i < 16; i++) { - u = u + (z[i] & 255) | 0; - z[i] = u & 255; - u >>>= 8; + var K = [ + 1116352408, + 3609767458, + 1899447441, + 602891725, + 3049323471, + 3964484399, + 3921009573, + 2173295548, + 961987163, + 4081628472, + 1508970993, + 3053834265, + 2453635748, + 2937671579, + 2870763221, + 3664609560, + 3624381080, + 2734883394, + 310598401, + 1164996542, + 607225278, + 1323610764, + 1426881987, + 3590304994, + 1925078388, + 4068182383, + 2162078206, + 991336113, + 2614888103, + 633803317, + 3248222580, + 3479774868, + 3835390401, + 2666613458, + 4022224774, + 944711139, + 264347078, + 2341262773, + 604807628, + 2007800933, + 770255983, + 1495990901, + 1249150122, + 1856431235, + 1555081692, + 3175218132, + 1996064986, + 2198950837, + 2554220882, + 3999719339, + 2821834349, + 766784016, + 2952996808, + 2566594879, + 3210313671, + 3203337956, + 3336571891, + 1034457026, + 3584528711, + 2466948901, + 113926993, + 3758326383, + 338241895, + 168717936, + 666307205, + 1188179964, + 773529912, + 1546045734, + 1294757372, + 1522805485, + 1396182291, + 2643833823, + 1695183700, + 2343527390, + 1986661051, + 1014477480, + 2177026350, + 1206759142, + 2456956037, + 344077627, + 2730485921, + 1290863460, + 2820302411, + 3158454273, + 3259730800, + 3505952657, + 3345764771, + 106217008, + 3516065817, + 3606008344, + 3600352804, + 1432725776, + 4094571909, + 1467031594, + 275423344, + 851169720, + 430227734, + 3100823752, + 506948616, + 1363258195, + 659060556, + 3750685593, + 883997877, + 3785050280, + 958139571, + 3318307427, + 1322822218, + 3812723403, + 1537002063, + 2003034995, + 1747873779, + 3602036899, + 1955562222, + 1575990012, + 2024104815, + 1125592928, + 2227730452, + 2716904306, + 2361852424, + 442776044, + 2428436474, + 593698344, + 2756734187, + 3733110249, + 3204031479, + 2999351573, + 3329325298, + 3815920427, + 3391569614, + 3928383900, + 3515267271, + 566280711, + 3940187606, + 3454069534, + 4118630271, + 4000239992, + 116418474, + 1914138554, + 174292421, + 2731055270, + 289380356, + 3203993006, + 460393269, + 320620315, + 685471733, + 587496836, + 852142971, + 1086792851, + 1017036298, + 365543100, + 1126000580, + 2618297676, + 1288033470, + 3409855158, + 1501505948, + 4234509866, + 1607167915, + 987167468, + 1816402316, + 1246189591 + ]; + function crypto_hashblocks_hl(hh, hl, m, n) { + var wh = new Int32Array(16), wl = new Int32Array(16), bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, th, tl, i, j, h, l, a, b, c, d; + var ah0 = hh[0], ah1 = hh[1], ah2 = hh[2], ah3 = hh[3], ah4 = hh[4], ah5 = hh[5], ah6 = hh[6], ah7 = hh[7], al0 = hl[0], al1 = hl[1], al2 = hl[2], al3 = hl[3], al4 = hl[4], al5 = hl[5], al6 = hl[6], al7 = hl[7]; + var pos = 0; + while (n >= 128) { + for (i = 0; i < 16; i++) { + j = 8 * i + pos; + wh[i] = m[j + 0] << 24 | m[j + 1] << 16 | m[j + 2] << 8 | m[j + 3]; + wl[i] = m[j + 4] << 24 | m[j + 5] << 16 | m[j + 6] << 8 | m[j + 7]; } - b -= 64; - cpos += 64; - mpos += 64; - } - if (b > 0) { - crypto_core_salsa20(x, z, k, sigma); - for (i = 0; i < b; i++) c[cpos + i] = m[mpos + i] ^ x[i]; - } - return 0; - } - function crypto_stream_salsa20(c, cpos, b, n, k) { - var z = new Uint8Array(16), x = new Uint8Array(64); - var u, i; - for (i = 0; i < 16; i++) z[i] = 0; - for (i = 0; i < 8; i++) z[i] = n[i]; - while (b >= 64) { - crypto_core_salsa20(x, z, k, sigma); - for (i = 0; i < 64; i++) c[cpos + i] = x[i]; - u = 1; - for (i = 8; i < 16; i++) { - u = u + (z[i] & 255) | 0; - z[i] = u & 255; - u >>>= 8; + for (i = 0; i < 80; i++) { + bh0 = ah0; + bh1 = ah1; + bh2 = ah2; + bh3 = ah3; + bh4 = ah4; + bh5 = ah5; + bh6 = ah6; + bh7 = ah7; + bl0 = al0; + bl1 = al1; + bl2 = al2; + bl3 = al3; + bl4 = al4; + bl5 = al5; + bl6 = al6; + bl7 = al7; + h = ah7; + l = al7; + a = l & 65535; + b = l >>> 16; + c = h & 65535; + d = h >>> 16; + h = (ah4 >>> 14 | al4 << 32 - 14) ^ (ah4 >>> 18 | al4 << 32 - 18) ^ (al4 >>> 41 - 32 | ah4 << 32 - (41 - 32)); + l = (al4 >>> 14 | ah4 << 32 - 14) ^ (al4 >>> 18 | ah4 << 32 - 18) ^ (ah4 >>> 41 - 32 | al4 << 32 - (41 - 32)); + a += l & 65535; + b += l >>> 16; + c += h & 65535; + d += h >>> 16; + h = ah4 & ah5 ^ ~ah4 & ah6; + l = al4 & al5 ^ ~al4 & al6; + a += l & 65535; + b += l >>> 16; + c += h & 65535; + d += h >>> 16; + h = K[i * 2]; + l = K[i * 2 + 1]; + a += l & 65535; + b += l >>> 16; + c += h & 65535; + d += h >>> 16; + h = wh[i % 16]; + l = wl[i % 16]; + a += l & 65535; + b += l >>> 16; + c += h & 65535; + d += h >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + th = c & 65535 | d << 16; + tl = a & 65535 | b << 16; + h = th; + l = tl; + a = l & 65535; + b = l >>> 16; + c = h & 65535; + d = h >>> 16; + h = (ah0 >>> 28 | al0 << 32 - 28) ^ (al0 >>> 34 - 32 | ah0 << 32 - (34 - 32)) ^ (al0 >>> 39 - 32 | ah0 << 32 - (39 - 32)); + l = (al0 >>> 28 | ah0 << 32 - 28) ^ (ah0 >>> 34 - 32 | al0 << 32 - (34 - 32)) ^ (ah0 >>> 39 - 32 | al0 << 32 - (39 - 32)); + a += l & 65535; + b += l >>> 16; + c += h & 65535; + d += h >>> 16; + h = ah0 & ah1 ^ ah0 & ah2 ^ ah1 & ah2; + l = al0 & al1 ^ al0 & al2 ^ al1 & al2; + a += l & 65535; + b += l >>> 16; + c += h & 65535; + d += h >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + bh7 = c & 65535 | d << 16; + bl7 = a & 65535 | b << 16; + h = bh3; + l = bl3; + a = l & 65535; + b = l >>> 16; + c = h & 65535; + d = h >>> 16; + h = th; + l = tl; + a += l & 65535; + b += l >>> 16; + c += h & 65535; + d += h >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + bh3 = c & 65535 | d << 16; + bl3 = a & 65535 | b << 16; + ah1 = bh0; + ah2 = bh1; + ah3 = bh2; + ah4 = bh3; + ah5 = bh4; + ah6 = bh5; + ah7 = bh6; + ah0 = bh7; + al1 = bl0; + al2 = bl1; + al3 = bl2; + al4 = bl3; + al5 = bl4; + al6 = bl5; + al7 = bl6; + al0 = bl7; + if (i % 16 === 15) { + for (j = 0; j < 16; j++) { + h = wh[j]; + l = wl[j]; + a = l & 65535; + b = l >>> 16; + c = h & 65535; + d = h >>> 16; + h = wh[(j + 9) % 16]; + l = wl[(j + 9) % 16]; + a += l & 65535; + b += l >>> 16; + c += h & 65535; + d += h >>> 16; + th = wh[(j + 1) % 16]; + tl = wl[(j + 1) % 16]; + h = (th >>> 1 | tl << 32 - 1) ^ (th >>> 8 | tl << 32 - 8) ^ th >>> 7; + l = (tl >>> 1 | th << 32 - 1) ^ (tl >>> 8 | th << 32 - 8) ^ (tl >>> 7 | th << 32 - 7); + a += l & 65535; + b += l >>> 16; + c += h & 65535; + d += h >>> 16; + th = wh[(j + 14) % 16]; + tl = wl[(j + 14) % 16]; + h = (th >>> 19 | tl << 32 - 19) ^ (tl >>> 61 - 32 | th << 32 - (61 - 32)) ^ th >>> 6; + l = (tl >>> 19 | th << 32 - 19) ^ (th >>> 61 - 32 | tl << 32 - (61 - 32)) ^ (tl >>> 6 | th << 32 - 6); + a += l & 65535; + b += l >>> 16; + c += h & 65535; + d += h >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + wh[j] = c & 65535 | d << 16; + wl[j] = a & 65535 | b << 16; + } + } } - b -= 64; - cpos += 64; + h = ah0; + l = al0; + a = l & 65535; + b = l >>> 16; + c = h & 65535; + d = h >>> 16; + h = hh[0]; + l = hl[0]; + a += l & 65535; + b += l >>> 16; + c += h & 65535; + d += h >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + hh[0] = ah0 = c & 65535 | d << 16; + hl[0] = al0 = a & 65535 | b << 16; + h = ah1; + l = al1; + a = l & 65535; + b = l >>> 16; + c = h & 65535; + d = h >>> 16; + h = hh[1]; + l = hl[1]; + a += l & 65535; + b += l >>> 16; + c += h & 65535; + d += h >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + hh[1] = ah1 = c & 65535 | d << 16; + hl[1] = al1 = a & 65535 | b << 16; + h = ah2; + l = al2; + a = l & 65535; + b = l >>> 16; + c = h & 65535; + d = h >>> 16; + h = hh[2]; + l = hl[2]; + a += l & 65535; + b += l >>> 16; + c += h & 65535; + d += h >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + hh[2] = ah2 = c & 65535 | d << 16; + hl[2] = al2 = a & 65535 | b << 16; + h = ah3; + l = al3; + a = l & 65535; + b = l >>> 16; + c = h & 65535; + d = h >>> 16; + h = hh[3]; + l = hl[3]; + a += l & 65535; + b += l >>> 16; + c += h & 65535; + d += h >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + hh[3] = ah3 = c & 65535 | d << 16; + hl[3] = al3 = a & 65535 | b << 16; + h = ah4; + l = al4; + a = l & 65535; + b = l >>> 16; + c = h & 65535; + d = h >>> 16; + h = hh[4]; + l = hl[4]; + a += l & 65535; + b += l >>> 16; + c += h & 65535; + d += h >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + hh[4] = ah4 = c & 65535 | d << 16; + hl[4] = al4 = a & 65535 | b << 16; + h = ah5; + l = al5; + a = l & 65535; + b = l >>> 16; + c = h & 65535; + d = h >>> 16; + h = hh[5]; + l = hl[5]; + a += l & 65535; + b += l >>> 16; + c += h & 65535; + d += h >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + hh[5] = ah5 = c & 65535 | d << 16; + hl[5] = al5 = a & 65535 | b << 16; + h = ah6; + l = al6; + a = l & 65535; + b = l >>> 16; + c = h & 65535; + d = h >>> 16; + h = hh[6]; + l = hl[6]; + a += l & 65535; + b += l >>> 16; + c += h & 65535; + d += h >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + hh[6] = ah6 = c & 65535 | d << 16; + hl[6] = al6 = a & 65535 | b << 16; + h = ah7; + l = al7; + a = l & 65535; + b = l >>> 16; + c = h & 65535; + d = h >>> 16; + h = hh[7]; + l = hl[7]; + a += l & 65535; + b += l >>> 16; + c += h & 65535; + d += h >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + hh[7] = ah7 = c & 65535 | d << 16; + hl[7] = al7 = a & 65535 | b << 16; + pos += 128; + n -= 128; } - if (b > 0) { - crypto_core_salsa20(x, z, k, sigma); - for (i = 0; i < b; i++) c[cpos + i] = x[i]; + return n; + } + function crypto_hash(out, m, n) { + var hh = new Int32Array(8), hl = new Int32Array(8), x = new Uint8Array(256), i, b = n; + hh[0] = 1779033703; + hh[1] = 3144134277; + hh[2] = 1013904242; + hh[3] = 2773480762; + hh[4] = 1359893119; + hh[5] = 2600822924; + hh[6] = 528734635; + hh[7] = 1541459225; + hl[0] = 4089235720; + hl[1] = 2227873595; + hl[2] = 4271175723; + hl[3] = 1595750129; + hl[4] = 2917565137; + hl[5] = 725511199; + hl[6] = 4215389547; + hl[7] = 327033209; + crypto_hashblocks_hl(hh, hl, m, n); + n %= 128; + for (i = 0; i < n; i++) x[i] = m[b - n + i]; + x[n] = 128; + n = 256 - 128 * (n < 112 ? 1 : 0); + x[n - 9] = 0; + ts64(x, n - 8, b / 536870912 | 0, b << 3); + crypto_hashblocks_hl(hh, hl, x, n); + for (i = 0; i < 8; i++) ts64(out, 8 * i, hh[i], hl[i]); + return 0; + } + function add(p, q) { + var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(), g = gf(), h = gf(), t = gf(); + Z(a, p[1], p[0]); + Z(t, q[1], q[0]); + M(a, a, t); + A(b, p[0], p[1]); + A(t, q[0], q[1]); + M(b, b, t); + M(c, p[3], q[3]); + M(c, c, D2); + M(d, p[2], q[2]); + A(d, d, d); + Z(e, b, a); + Z(f, d, c); + A(g, d, c); + A(h, b, a); + M(p[0], e, f); + M(p[1], h, g); + M(p[2], g, f); + M(p[3], e, h); + } + function cswap(p, q, b) { + var i; + for (i = 0; i < 4; i++) { + sel25519(p[i], q[i], b); + } + } + function pack2(r, p) { + var tx = gf(), ty = gf(), zi = gf(); + inv25519(zi, p[2]); + M(tx, p[0], zi); + M(ty, p[1], zi); + pack25519(r, ty); + r[31] ^= par25519(tx) << 7; + } + function scalarmult(p, q, s) { + var b, i; + set25519(p[0], gf0); + set25519(p[1], gf1); + set25519(p[2], gf1); + set25519(p[3], gf0); + for (i = 255; i >= 0; --i) { + b = s[i / 8 | 0] >> (i & 7) & 1; + cswap(p, q, b); + add(q, p); + add(p, p); + cswap(p, q, b); } + } + function scalarbase(p, s) { + var q = [gf(), gf(), gf(), gf()]; + set25519(q[0], X); + set25519(q[1], Y); + set25519(q[2], gf1); + M(q[3], X, Y); + scalarmult(p, q, s); + } + function crypto_sign_keypair(pk, sk, seeded) { + var d = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()]; + var i; + if (!seeded) randombytes(sk, 32); + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + scalarbase(p, d); + pack2(pk, p); + for (i = 0; i < 32; i++) sk[i + 32] = pk[i]; return 0; } - function crypto_stream(c, cpos, d, n, k) { - var s = new Uint8Array(32); - crypto_core_hsalsa20(s, n, k, sigma); - var sn = new Uint8Array(8); - for (var i = 0; i < 8; i++) sn[i] = n[i + 16]; - return crypto_stream_salsa20(c, cpos, d, sn, s); + var L = new Float64Array([237, 211, 245, 92, 26, 99, 18, 88, 214, 156, 247, 162, 222, 249, 222, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16]); + function modL(r, x) { + var carry, i, j, k; + for (i = 63; i >= 32; --i) { + carry = 0; + for (j = i - 32, k = i - 12; j < k; ++j) { + x[j] += carry - 16 * x[i] * L[j - (i - 32)]; + carry = x[j] + 128 >> 8; + x[j] -= carry * 256; + } + x[j] += carry; + x[i] = 0; + } + carry = 0; + for (j = 0; j < 32; j++) { + x[j] += carry - (x[31] >> 4) * L[j]; + carry = x[j] >> 8; + x[j] &= 255; + } + for (j = 0; j < 32; j++) x[j] -= carry * L[j]; + for (i = 0; i < 32; i++) { + x[i + 1] += x[i] >> 8; + r[i] = x[i] & 255; + } } - function crypto_stream_xor(c, cpos, m, mpos, d, n, k) { - var s = new Uint8Array(32); - crypto_core_hsalsa20(s, n, k, sigma); - var sn = new Uint8Array(8); - for (var i = 0; i < 8; i++) sn[i] = n[i + 16]; - return crypto_stream_salsa20_xor(c, cpos, m, mpos, d, sn, s); + function reduce(r) { + var x = new Float64Array(64), i; + for (i = 0; i < 64; i++) x[i] = r[i]; + for (i = 0; i < 64; i++) r[i] = 0; + modL(r, x); } - var poly1305 = function(key) { - this.buffer = new Uint8Array(16); - this.r = new Uint16Array(10); - this.h = new Uint16Array(10); - this.pad = new Uint16Array(8); - this.leftover = 0; - this.fin = 0; - var t0, t1, t2, t3, t4, t5, t6, t7; - t0 = key[0] & 255 | (key[1] & 255) << 8; - this.r[0] = t0 & 8191; - t1 = key[2] & 255 | (key[3] & 255) << 8; - this.r[1] = (t0 >>> 13 | t1 << 3) & 8191; - t2 = key[4] & 255 | (key[5] & 255) << 8; - this.r[2] = (t1 >>> 10 | t2 << 6) & 7939; - t3 = key[6] & 255 | (key[7] & 255) << 8; - this.r[3] = (t2 >>> 7 | t3 << 9) & 8191; - t4 = key[8] & 255 | (key[9] & 255) << 8; - this.r[4] = (t3 >>> 4 | t4 << 12) & 255; - this.r[5] = t4 >>> 1 & 8190; - t5 = key[10] & 255 | (key[11] & 255) << 8; - this.r[6] = (t4 >>> 14 | t5 << 2) & 8191; - t6 = key[12] & 255 | (key[13] & 255) << 8; - this.r[7] = (t5 >>> 11 | t6 << 5) & 8065; - t7 = key[14] & 255 | (key[15] & 255) << 8; - this.r[8] = (t6 >>> 8 | t7 << 8) & 8191; - this.r[9] = t7 >>> 5 & 127; - this.pad[0] = key[16] & 255 | (key[17] & 255) << 8; - this.pad[1] = key[18] & 255 | (key[19] & 255) << 8; - this.pad[2] = key[20] & 255 | (key[21] & 255) << 8; - this.pad[3] = key[22] & 255 | (key[23] & 255) << 8; - this.pad[4] = key[24] & 255 | (key[25] & 255) << 8; - this.pad[5] = key[26] & 255 | (key[27] & 255) << 8; - this.pad[6] = key[28] & 255 | (key[29] & 255) << 8; - this.pad[7] = key[30] & 255 | (key[31] & 255) << 8; - }; - poly1305.prototype.blocks = function(m, mpos, bytes) { - var hibit = this.fin ? 0 : 1 << 11; - var t0, t1, t2, t3, t4, t5, t6, t7, c; - var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9; - var h0 = this.h[0], h1 = this.h[1], h2 = this.h[2], h3 = this.h[3], h4 = this.h[4], h5 = this.h[5], h6 = this.h[6], h7 = this.h[7], h8 = this.h[8], h9 = this.h[9]; - var r0 = this.r[0], r1 = this.r[1], r2 = this.r[2], r3 = this.r[3], r4 = this.r[4], r5 = this.r[5], r6 = this.r[6], r7 = this.r[7], r8 = this.r[8], r9 = this.r[9]; - while (bytes >= 16) { - t0 = m[mpos + 0] & 255 | (m[mpos + 1] & 255) << 8; - h0 += t0 & 8191; - t1 = m[mpos + 2] & 255 | (m[mpos + 3] & 255) << 8; - h1 += (t0 >>> 13 | t1 << 3) & 8191; - t2 = m[mpos + 4] & 255 | (m[mpos + 5] & 255) << 8; - h2 += (t1 >>> 10 | t2 << 6) & 8191; - t3 = m[mpos + 6] & 255 | (m[mpos + 7] & 255) << 8; - h3 += (t2 >>> 7 | t3 << 9) & 8191; - t4 = m[mpos + 8] & 255 | (m[mpos + 9] & 255) << 8; - h4 += (t3 >>> 4 | t4 << 12) & 8191; - h5 += t4 >>> 1 & 8191; - t5 = m[mpos + 10] & 255 | (m[mpos + 11] & 255) << 8; - h6 += (t4 >>> 14 | t5 << 2) & 8191; - t6 = m[mpos + 12] & 255 | (m[mpos + 13] & 255) << 8; - h7 += (t5 >>> 11 | t6 << 5) & 8191; - t7 = m[mpos + 14] & 255 | (m[mpos + 15] & 255) << 8; - h8 += (t6 >>> 8 | t7 << 8) & 8191; - h9 += t7 >>> 5 | hibit; - c = 0; - d0 = c; - d0 += h0 * r0; - d0 += h1 * (5 * r9); - d0 += h2 * (5 * r8); - d0 += h3 * (5 * r7); - d0 += h4 * (5 * r6); - c = d0 >>> 13; - d0 &= 8191; - d0 += h5 * (5 * r5); - d0 += h6 * (5 * r4); - d0 += h7 * (5 * r3); - d0 += h8 * (5 * r2); - d0 += h9 * (5 * r1); - c += d0 >>> 13; - d0 &= 8191; - d1 = c; - d1 += h0 * r1; - d1 += h1 * r0; - d1 += h2 * (5 * r9); - d1 += h3 * (5 * r8); - d1 += h4 * (5 * r7); - c = d1 >>> 13; - d1 &= 8191; - d1 += h5 * (5 * r6); - d1 += h6 * (5 * r5); - d1 += h7 * (5 * r4); - d1 += h8 * (5 * r3); - d1 += h9 * (5 * r2); - c += d1 >>> 13; - d1 &= 8191; - d2 = c; - d2 += h0 * r2; - d2 += h1 * r1; - d2 += h2 * r0; - d2 += h3 * (5 * r9); - d2 += h4 * (5 * r8); - c = d2 >>> 13; - d2 &= 8191; - d2 += h5 * (5 * r7); - d2 += h6 * (5 * r6); - d2 += h7 * (5 * r5); - d2 += h8 * (5 * r4); - d2 += h9 * (5 * r3); - c += d2 >>> 13; - d2 &= 8191; - d3 = c; - d3 += h0 * r3; - d3 += h1 * r2; - d3 += h2 * r1; - d3 += h3 * r0; - d3 += h4 * (5 * r9); - c = d3 >>> 13; - d3 &= 8191; - d3 += h5 * (5 * r8); - d3 += h6 * (5 * r7); - d3 += h7 * (5 * r6); - d3 += h8 * (5 * r5); - d3 += h9 * (5 * r4); - c += d3 >>> 13; - d3 &= 8191; - d4 = c; - d4 += h0 * r4; - d4 += h1 * r3; - d4 += h2 * r2; - d4 += h3 * r1; - d4 += h4 * r0; - c = d4 >>> 13; - d4 &= 8191; - d4 += h5 * (5 * r9); - d4 += h6 * (5 * r8); - d4 += h7 * (5 * r7); - d4 += h8 * (5 * r6); - d4 += h9 * (5 * r5); - c += d4 >>> 13; - d4 &= 8191; - d5 = c; - d5 += h0 * r5; - d5 += h1 * r4; - d5 += h2 * r3; - d5 += h3 * r2; - d5 += h4 * r1; - c = d5 >>> 13; - d5 &= 8191; - d5 += h5 * r0; - d5 += h6 * (5 * r9); - d5 += h7 * (5 * r8); - d5 += h8 * (5 * r7); - d5 += h9 * (5 * r6); - c += d5 >>> 13; - d5 &= 8191; - d6 = c; - d6 += h0 * r6; - d6 += h1 * r5; - d6 += h2 * r4; - d6 += h3 * r3; - d6 += h4 * r2; - c = d6 >>> 13; - d6 &= 8191; - d6 += h5 * r1; - d6 += h6 * r0; - d6 += h7 * (5 * r9); - d6 += h8 * (5 * r8); - d6 += h9 * (5 * r7); - c += d6 >>> 13; - d6 &= 8191; - d7 = c; - d7 += h0 * r7; - d7 += h1 * r6; - d7 += h2 * r5; - d7 += h3 * r4; - d7 += h4 * r3; - c = d7 >>> 13; - d7 &= 8191; - d7 += h5 * r2; - d7 += h6 * r1; - d7 += h7 * r0; - d7 += h8 * (5 * r9); - d7 += h9 * (5 * r8); - c += d7 >>> 13; - d7 &= 8191; - d8 = c; - d8 += h0 * r8; - d8 += h1 * r7; - d8 += h2 * r6; - d8 += h3 * r5; - d8 += h4 * r4; - c = d8 >>> 13; - d8 &= 8191; - d8 += h5 * r3; - d8 += h6 * r2; - d8 += h7 * r1; - d8 += h8 * r0; - d8 += h9 * (5 * r9); - c += d8 >>> 13; - d8 &= 8191; - d9 = c; - d9 += h0 * r9; - d9 += h1 * r8; - d9 += h2 * r7; - d9 += h3 * r6; - d9 += h4 * r5; - c = d9 >>> 13; - d9 &= 8191; - d9 += h5 * r4; - d9 += h6 * r3; - d9 += h7 * r2; - d9 += h8 * r1; - d9 += h9 * r0; - c += d9 >>> 13; - d9 &= 8191; - c = (c << 2) + c | 0; - c = c + d0 | 0; - d0 = c & 8191; - c = c >>> 13; - d1 += c; - h0 = d0; - h1 = d1; - h2 = d2; - h3 = d3; - h4 = d4; - h5 = d5; - h6 = d6; - h7 = d7; - h8 = d8; - h9 = d9; - mpos += 16; - bytes -= 16; - } - this.h[0] = h0; - this.h[1] = h1; - this.h[2] = h2; - this.h[3] = h3; - this.h[4] = h4; - this.h[5] = h5; - this.h[6] = h6; - this.h[7] = h7; - this.h[8] = h8; - this.h[9] = h9; - }; - poly1305.prototype.finish = function(mac, macpos) { - var g = new Uint16Array(10); - var c, mask, f, i; - if (this.leftover) { - i = this.leftover; - this.buffer[i++] = 1; - for (; i < 16; i++) this.buffer[i] = 0; - this.fin = 1; - this.blocks(this.buffer, 0, 16); - } - c = this.h[1] >>> 13; - this.h[1] &= 8191; - for (i = 2; i < 10; i++) { - this.h[i] += c; - c = this.h[i] >>> 13; - this.h[i] &= 8191; - } - this.h[0] += c * 5; - c = this.h[0] >>> 13; - this.h[0] &= 8191; - this.h[1] += c; - c = this.h[1] >>> 13; - this.h[1] &= 8191; - this.h[2] += c; - g[0] = this.h[0] + 5; - c = g[0] >>> 13; - g[0] &= 8191; - for (i = 1; i < 10; i++) { - g[i] = this.h[i] + c; - c = g[i] >>> 13; - g[i] &= 8191; - } - g[9] -= 1 << 13; - mask = (c ^ 1) - 1; - for (i = 0; i < 10; i++) g[i] &= mask; - mask = ~mask; - for (i = 0; i < 10; i++) this.h[i] = this.h[i] & mask | g[i]; - this.h[0] = (this.h[0] | this.h[1] << 13) & 65535; - this.h[1] = (this.h[1] >>> 3 | this.h[2] << 10) & 65535; - this.h[2] = (this.h[2] >>> 6 | this.h[3] << 7) & 65535; - this.h[3] = (this.h[3] >>> 9 | this.h[4] << 4) & 65535; - this.h[4] = (this.h[4] >>> 12 | this.h[5] << 1 | this.h[6] << 14) & 65535; - this.h[5] = (this.h[6] >>> 2 | this.h[7] << 11) & 65535; - this.h[6] = (this.h[7] >>> 5 | this.h[8] << 8) & 65535; - this.h[7] = (this.h[8] >>> 8 | this.h[9] << 5) & 65535; - f = this.h[0] + this.pad[0]; - this.h[0] = f & 65535; - for (i = 1; i < 8; i++) { - f = (this.h[i] + this.pad[i] | 0) + (f >>> 16) | 0; - this.h[i] = f & 65535; - } - mac[macpos + 0] = this.h[0] >>> 0 & 255; - mac[macpos + 1] = this.h[0] >>> 8 & 255; - mac[macpos + 2] = this.h[1] >>> 0 & 255; - mac[macpos + 3] = this.h[1] >>> 8 & 255; - mac[macpos + 4] = this.h[2] >>> 0 & 255; - mac[macpos + 5] = this.h[2] >>> 8 & 255; - mac[macpos + 6] = this.h[3] >>> 0 & 255; - mac[macpos + 7] = this.h[3] >>> 8 & 255; - mac[macpos + 8] = this.h[4] >>> 0 & 255; - mac[macpos + 9] = this.h[4] >>> 8 & 255; - mac[macpos + 10] = this.h[5] >>> 0 & 255; - mac[macpos + 11] = this.h[5] >>> 8 & 255; - mac[macpos + 12] = this.h[6] >>> 0 & 255; - mac[macpos + 13] = this.h[6] >>> 8 & 255; - mac[macpos + 14] = this.h[7] >>> 0 & 255; - mac[macpos + 15] = this.h[7] >>> 8 & 255; - }; - poly1305.prototype.update = function(m, mpos, bytes) { - var i, want; - if (this.leftover) { - want = 16 - this.leftover; - if (want > bytes) - want = bytes; - for (i = 0; i < want; i++) - this.buffer[this.leftover + i] = m[mpos + i]; - bytes -= want; - mpos += want; - this.leftover += want; - if (this.leftover < 16) - return; - this.blocks(this.buffer, 0, 16); - this.leftover = 0; - } - if (bytes >= 16) { - want = bytes - bytes % 16; - this.blocks(m, mpos, want); - mpos += want; - bytes -= want; - } - if (bytes) { - for (i = 0; i < bytes; i++) - this.buffer[this.leftover + i] = m[mpos + i]; - this.leftover += bytes; + function crypto_sign(sm, m, n, sk) { + var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); + var i, j, x = new Float64Array(64); + var p = [gf(), gf(), gf(), gf()]; + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + var smlen = n + 64; + for (i = 0; i < n; i++) sm[64 + i] = m[i]; + for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; + crypto_hash(r, sm.subarray(32), n + 32); + reduce(r); + scalarbase(p, r); + pack2(sm, p); + for (i = 32; i < 64; i++) sm[i] = sk[i]; + crypto_hash(h, sm, n + 64); + reduce(h); + for (i = 0; i < 64; i++) x[i] = 0; + for (i = 0; i < 32; i++) x[i] = r[i]; + for (i = 0; i < 32; i++) { + for (j = 0; j < 32; j++) { + x[i + j] += h[i] * d[j]; + } } - }; - function crypto_onetimeauth(out, outpos, m, mpos, n, k) { - var s = new poly1305(k); - s.update(m, mpos, n); - s.finish(out, outpos); - return 0; - } - function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) { - var x = new Uint8Array(16); - crypto_onetimeauth(x, 0, m, mpos, n, k); - return crypto_verify_16(h, hpos, x, 0); - } - function crypto_secretbox(c, m, d, n, k) { - var i; - if (d < 32) return -1; - crypto_stream_xor(c, 0, m, 0, d, n, k); - crypto_onetimeauth(c, 16, c, 32, d - 32, c); - for (i = 0; i < 16; i++) c[i] = 0; - return 0; + modL(sm.subarray(32), x); + return smlen; } - function crypto_secretbox_open(m, c, d, n, k) { - var i; - var x = new Uint8Array(32); - if (d < 32) return -1; - crypto_stream(x, 0, 32, n, k); - if (crypto_onetimeauth_verify(c, 16, c, 32, d - 32, x) !== 0) return -1; - crypto_stream_xor(m, 0, c, 0, d, n, k); - for (i = 0; i < 32; i++) m[i] = 0; + function unpackneg(r, p) { + var t = gf(), chk = gf(), num = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf(); + set25519(r[2], gf1); + unpack25519(r[1], p); + S(num, r[1]); + M(den, num, D); + Z(num, num, r[2]); + A(den, r[2], den); + S(den2, den); + S(den4, den2); + M(den6, den4, den2); + M(t, den6, num); + M(t, t, den); + pow2523(t, t); + M(t, t, num); + M(t, t, den); + M(t, t, den); + M(r[0], t, den); + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) M(r[0], r[0], I); + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) return -1; + if (par25519(r[0]) === p[31] >> 7) Z(r[0], gf0, r[0]); + M(r[3], r[0], r[1]); return 0; } - function set25519(r, a) { - var i; - for (i = 0; i < 16; i++) r[i] = a[i] | 0; - } - function car25519(o) { - var i, v, c = 1; - for (i = 0; i < 16; i++) { - v = o[i] + c + 65535; - c = Math.floor(v / 65536); - o[i] = v - c * 65536; - } - o[0] += c - 1 + 37 * (c - 1); - } - function sel25519(p, q, b) { - var t, c = ~(b - 1); - for (var i = 0; i < 16; i++) { - t = c & (p[i] ^ q[i]); - p[i] ^= t; - q[i] ^= t; - } - } - function pack25519(o, n) { - var i, j, b; - var m = gf(), t = gf(); - for (i = 0; i < 16; i++) t[i] = n[i]; - car25519(t); - car25519(t); - car25519(t); - for (j = 0; j < 2; j++) { - m[0] = t[0] - 65517; - for (i = 1; i < 15; i++) { - m[i] = t[i] - 65535 - (m[i - 1] >> 16 & 1); - m[i - 1] &= 65535; - } - m[15] = t[15] - 32767 - (m[14] >> 16 & 1); - b = m[15] >> 16 & 1; - m[14] &= 65535; - sel25519(t, m, 1 - b); - } - for (i = 0; i < 16; i++) { - o[2 * i] = t[i] & 255; - o[2 * i + 1] = t[i] >> 8; + function crypto_sign_open(m, sm, n, pk) { + var i, mlen; + var t = new Uint8Array(32), h = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()], q = [gf(), gf(), gf(), gf()]; + mlen = -1; + if (n < 64) return -1; + if (unpackneg(q, pk)) return -1; + for (i = 0; i < n; i++) m[i] = sm[i]; + for (i = 0; i < 32; i++) m[i + 32] = pk[i]; + crypto_hash(h, m, n); + reduce(h); + scalarmult(p, q, h); + scalarbase(q, sm.subarray(32)); + add(p, q); + pack2(t, p); + n -= 64; + if (crypto_verify_32(sm, 0, t, 0)) { + for (i = 0; i < n; i++) m[i] = 0; + return -1; } + for (i = 0; i < n; i++) m[i] = sm[i + 64]; + mlen = n; + return mlen; } - function neq25519(a, b) { - var c = new Uint8Array(32), d = new Uint8Array(32); - pack25519(c, a); - pack25519(d, b); - return crypto_verify_32(c, 0, d, 0); + var crypto_secretbox_KEYBYTES = 32, crypto_secretbox_NONCEBYTES = 24, crypto_secretbox_ZEROBYTES = 32, crypto_secretbox_BOXZEROBYTES = 16, crypto_scalarmult_BYTES = 32, crypto_scalarmult_SCALARBYTES = 32, crypto_box_PUBLICKEYBYTES = 32, crypto_box_SECRETKEYBYTES = 32, crypto_box_BEFORENMBYTES = 32, crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, crypto_sign_BYTES = 64, crypto_sign_PUBLICKEYBYTES = 32, crypto_sign_SECRETKEYBYTES = 64, crypto_sign_SEEDBYTES = 32, crypto_hash_BYTES = 64; + nacl.lowlevel = { + crypto_core_hsalsa20, + crypto_stream_xor, + crypto_stream, + crypto_stream_salsa20_xor, + crypto_stream_salsa20, + crypto_onetimeauth, + crypto_onetimeauth_verify, + crypto_verify_16, + crypto_verify_32, + crypto_secretbox, + crypto_secretbox_open, + crypto_scalarmult, + crypto_scalarmult_base, + crypto_box_beforenm, + crypto_box_afternm, + crypto_box, + crypto_box_open, + crypto_box_keypair, + crypto_hash, + crypto_sign, + crypto_sign_keypair, + crypto_sign_open, + crypto_secretbox_KEYBYTES, + crypto_secretbox_NONCEBYTES, + crypto_secretbox_ZEROBYTES, + crypto_secretbox_BOXZEROBYTES, + crypto_scalarmult_BYTES, + crypto_scalarmult_SCALARBYTES, + crypto_box_PUBLICKEYBYTES, + crypto_box_SECRETKEYBYTES, + crypto_box_BEFORENMBYTES, + crypto_box_NONCEBYTES, + crypto_box_ZEROBYTES, + crypto_box_BOXZEROBYTES, + crypto_sign_BYTES, + crypto_sign_PUBLICKEYBYTES, + crypto_sign_SECRETKEYBYTES, + crypto_sign_SEEDBYTES, + crypto_hash_BYTES + }; + function checkLengths(k, n) { + if (k.length !== crypto_secretbox_KEYBYTES) throw new Error("bad key size"); + if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error("bad nonce size"); } - function par25519(a) { - var d = new Uint8Array(32); - pack25519(d, a); - return d[0] & 1; + function checkBoxLengths(pk, sk) { + if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error("bad public key size"); + if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error("bad secret key size"); } - function unpack25519(o, n) { - var i; - for (i = 0; i < 16; i++) o[i] = n[2 * i] + (n[2 * i + 1] << 8); - o[15] &= 32767; + function checkArrayTypes() { + var t, i; + for (i = 0; i < arguments.length; i++) { + if ((t = Object.prototype.toString.call(arguments[i])) !== "[object Uint8Array]") + throw new TypeError("unexpected type " + t + ", use Uint8Array"); + } } - function A(o, a, b) { - for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; + function cleanup(arr) { + for (var i = 0; i < arr.length; i++) arr[i] = 0; } - function Z(o, a, b) { - for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; + if (!nacl.util) { + nacl.util = {}; + nacl.util.decodeUTF8 = nacl.util.encodeUTF8 = nacl.util.encodeBase64 = nacl.util.decodeBase64 = function() { + throw new Error("nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js"); + }; } - function M(o, a, b) { - var v, c, t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3], b4 = b[4], b5 = b[5], b6 = b[6], b7 = b[7], b8 = b[8], b9 = b[9], b10 = b[10], b11 = b[11], b12 = b[12], b13 = b[13], b14 = b[14], b15 = b[15]; - v = a[0]; - t0 += v * b0; - t1 += v * b1; - t2 += v * b2; - t3 += v * b3; - t4 += v * b4; - t5 += v * b5; - t6 += v * b6; - t7 += v * b7; - t8 += v * b8; - t9 += v * b9; - t10 += v * b10; - t11 += v * b11; - t12 += v * b12; - t13 += v * b13; - t14 += v * b14; - t15 += v * b15; - v = a[1]; - t1 += v * b0; - t2 += v * b1; - t3 += v * b2; - t4 += v * b3; - t5 += v * b4; - t6 += v * b5; - t7 += v * b6; - t8 += v * b7; - t9 += v * b8; - t10 += v * b9; - t11 += v * b10; - t12 += v * b11; - t13 += v * b12; - t14 += v * b13; - t15 += v * b14; - t16 += v * b15; - v = a[2]; - t2 += v * b0; - t3 += v * b1; - t4 += v * b2; - t5 += v * b3; - t6 += v * b4; - t7 += v * b5; - t8 += v * b6; - t9 += v * b7; - t10 += v * b8; - t11 += v * b9; - t12 += v * b10; - t13 += v * b11; - t14 += v * b12; - t15 += v * b13; - t16 += v * b14; - t17 += v * b15; - v = a[3]; - t3 += v * b0; - t4 += v * b1; - t5 += v * b2; - t6 += v * b3; - t7 += v * b4; - t8 += v * b5; - t9 += v * b6; - t10 += v * b7; - t11 += v * b8; - t12 += v * b9; - t13 += v * b10; - t14 += v * b11; - t15 += v * b12; - t16 += v * b13; - t17 += v * b14; - t18 += v * b15; - v = a[4]; - t4 += v * b0; - t5 += v * b1; - t6 += v * b2; - t7 += v * b3; - t8 += v * b4; - t9 += v * b5; - t10 += v * b6; - t11 += v * b7; - t12 += v * b8; - t13 += v * b9; - t14 += v * b10; - t15 += v * b11; - t16 += v * b12; - t17 += v * b13; - t18 += v * b14; - t19 += v * b15; - v = a[5]; - t5 += v * b0; - t6 += v * b1; - t7 += v * b2; - t8 += v * b3; - t9 += v * b4; - t10 += v * b5; - t11 += v * b6; - t12 += v * b7; - t13 += v * b8; - t14 += v * b9; - t15 += v * b10; - t16 += v * b11; - t17 += v * b12; - t18 += v * b13; - t19 += v * b14; - t20 += v * b15; - v = a[6]; - t6 += v * b0; - t7 += v * b1; - t8 += v * b2; - t9 += v * b3; - t10 += v * b4; - t11 += v * b5; - t12 += v * b6; - t13 += v * b7; - t14 += v * b8; - t15 += v * b9; - t16 += v * b10; - t17 += v * b11; - t18 += v * b12; - t19 += v * b13; - t20 += v * b14; - t21 += v * b15; - v = a[7]; - t7 += v * b0; - t8 += v * b1; - t9 += v * b2; - t10 += v * b3; - t11 += v * b4; - t12 += v * b5; - t13 += v * b6; - t14 += v * b7; - t15 += v * b8; - t16 += v * b9; - t17 += v * b10; - t18 += v * b11; - t19 += v * b12; - t20 += v * b13; - t21 += v * b14; - t22 += v * b15; - v = a[8]; - t8 += v * b0; - t9 += v * b1; - t10 += v * b2; - t11 += v * b3; - t12 += v * b4; - t13 += v * b5; - t14 += v * b6; - t15 += v * b7; - t16 += v * b8; - t17 += v * b9; - t18 += v * b10; - t19 += v * b11; - t20 += v * b12; - t21 += v * b13; - t22 += v * b14; - t23 += v * b15; - v = a[9]; - t9 += v * b0; - t10 += v * b1; - t11 += v * b2; - t12 += v * b3; - t13 += v * b4; - t14 += v * b5; - t15 += v * b6; - t16 += v * b7; - t17 += v * b8; - t18 += v * b9; - t19 += v * b10; - t20 += v * b11; - t21 += v * b12; - t22 += v * b13; - t23 += v * b14; - t24 += v * b15; - v = a[10]; - t10 += v * b0; - t11 += v * b1; - t12 += v * b2; - t13 += v * b3; - t14 += v * b4; - t15 += v * b5; - t16 += v * b6; - t17 += v * b7; - t18 += v * b8; - t19 += v * b9; - t20 += v * b10; - t21 += v * b11; - t22 += v * b12; - t23 += v * b13; - t24 += v * b14; - t25 += v * b15; - v = a[11]; - t11 += v * b0; - t12 += v * b1; - t13 += v * b2; - t14 += v * b3; - t15 += v * b4; - t16 += v * b5; - t17 += v * b6; - t18 += v * b7; - t19 += v * b8; - t20 += v * b9; - t21 += v * b10; - t22 += v * b11; - t23 += v * b12; - t24 += v * b13; - t25 += v * b14; - t26 += v * b15; - v = a[12]; - t12 += v * b0; - t13 += v * b1; - t14 += v * b2; - t15 += v * b3; - t16 += v * b4; - t17 += v * b5; - t18 += v * b6; - t19 += v * b7; - t20 += v * b8; - t21 += v * b9; - t22 += v * b10; - t23 += v * b11; - t24 += v * b12; - t25 += v * b13; - t26 += v * b14; - t27 += v * b15; - v = a[13]; - t13 += v * b0; - t14 += v * b1; - t15 += v * b2; - t16 += v * b3; - t17 += v * b4; - t18 += v * b5; - t19 += v * b6; - t20 += v * b7; - t21 += v * b8; - t22 += v * b9; - t23 += v * b10; - t24 += v * b11; - t25 += v * b12; - t26 += v * b13; - t27 += v * b14; - t28 += v * b15; - v = a[14]; - t14 += v * b0; - t15 += v * b1; - t16 += v * b2; - t17 += v * b3; - t18 += v * b4; - t19 += v * b5; - t20 += v * b6; - t21 += v * b7; - t22 += v * b8; - t23 += v * b9; - t24 += v * b10; - t25 += v * b11; - t26 += v * b12; - t27 += v * b13; - t28 += v * b14; - t29 += v * b15; - v = a[15]; - t15 += v * b0; - t16 += v * b1; - t17 += v * b2; - t18 += v * b3; - t19 += v * b4; - t20 += v * b5; - t21 += v * b6; - t22 += v * b7; - t23 += v * b8; - t24 += v * b9; - t25 += v * b10; - t26 += v * b11; - t27 += v * b12; - t28 += v * b13; - t29 += v * b14; - t30 += v * b15; - t0 += 38 * t16; - t1 += 38 * t17; - t2 += 38 * t18; - t3 += 38 * t19; - t4 += 38 * t20; - t5 += 38 * t21; - t6 += 38 * t22; - t7 += 38 * t23; - t8 += 38 * t24; - t9 += 38 * t25; - t10 += 38 * t26; - t11 += 38 * t27; - t12 += 38 * t28; - t13 += 38 * t29; - t14 += 38 * t30; - c = 1; - v = t0 + c + 65535; - c = Math.floor(v / 65536); - t0 = v - c * 65536; - v = t1 + c + 65535; - c = Math.floor(v / 65536); - t1 = v - c * 65536; - v = t2 + c + 65535; - c = Math.floor(v / 65536); - t2 = v - c * 65536; - v = t3 + c + 65535; - c = Math.floor(v / 65536); - t3 = v - c * 65536; - v = t4 + c + 65535; - c = Math.floor(v / 65536); - t4 = v - c * 65536; - v = t5 + c + 65535; - c = Math.floor(v / 65536); - t5 = v - c * 65536; - v = t6 + c + 65535; - c = Math.floor(v / 65536); - t6 = v - c * 65536; - v = t7 + c + 65535; - c = Math.floor(v / 65536); - t7 = v - c * 65536; - v = t8 + c + 65535; - c = Math.floor(v / 65536); - t8 = v - c * 65536; - v = t9 + c + 65535; - c = Math.floor(v / 65536); - t9 = v - c * 65536; - v = t10 + c + 65535; - c = Math.floor(v / 65536); - t10 = v - c * 65536; - v = t11 + c + 65535; - c = Math.floor(v / 65536); - t11 = v - c * 65536; - v = t12 + c + 65535; - c = Math.floor(v / 65536); - t12 = v - c * 65536; - v = t13 + c + 65535; - c = Math.floor(v / 65536); - t13 = v - c * 65536; - v = t14 + c + 65535; - c = Math.floor(v / 65536); - t14 = v - c * 65536; - v = t15 + c + 65535; - c = Math.floor(v / 65536); - t15 = v - c * 65536; - t0 += c - 1 + 37 * (c - 1); - c = 1; - v = t0 + c + 65535; - c = Math.floor(v / 65536); - t0 = v - c * 65536; - v = t1 + c + 65535; - c = Math.floor(v / 65536); - t1 = v - c * 65536; - v = t2 + c + 65535; - c = Math.floor(v / 65536); - t2 = v - c * 65536; - v = t3 + c + 65535; - c = Math.floor(v / 65536); - t3 = v - c * 65536; - v = t4 + c + 65535; - c = Math.floor(v / 65536); - t4 = v - c * 65536; - v = t5 + c + 65535; - c = Math.floor(v / 65536); - t5 = v - c * 65536; - v = t6 + c + 65535; - c = Math.floor(v / 65536); - t6 = v - c * 65536; - v = t7 + c + 65535; - c = Math.floor(v / 65536); - t7 = v - c * 65536; - v = t8 + c + 65535; - c = Math.floor(v / 65536); - t8 = v - c * 65536; - v = t9 + c + 65535; - c = Math.floor(v / 65536); - t9 = v - c * 65536; - v = t10 + c + 65535; - c = Math.floor(v / 65536); - t10 = v - c * 65536; - v = t11 + c + 65535; - c = Math.floor(v / 65536); - t11 = v - c * 65536; - v = t12 + c + 65535; - c = Math.floor(v / 65536); - t12 = v - c * 65536; - v = t13 + c + 65535; - c = Math.floor(v / 65536); - t13 = v - c * 65536; - v = t14 + c + 65535; - c = Math.floor(v / 65536); - t14 = v - c * 65536; - v = t15 + c + 65535; - c = Math.floor(v / 65536); - t15 = v - c * 65536; - t0 += c - 1 + 37 * (c - 1); - o[0] = t0; - o[1] = t1; - o[2] = t2; - o[3] = t3; - o[4] = t4; - o[5] = t5; - o[6] = t6; - o[7] = t7; - o[8] = t8; - o[9] = t9; - o[10] = t10; - o[11] = t11; - o[12] = t12; - o[13] = t13; - o[14] = t14; - o[15] = t15; - } - function S(o, a) { - M(o, a, a); - } - function inv25519(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 253; a >= 0; a--) { - S(c, c); - if (a !== 2 && a !== 4) M(c, c, i); - } - for (a = 0; a < 16; a++) o[a] = c[a]; - } - function pow2523(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 250; a >= 0; a--) { - S(c, c); - if (a !== 1) M(c, c, i); - } - for (a = 0; a < 16; a++) o[a] = c[a]; - } - function crypto_scalarmult(q, n, p) { - var z = new Uint8Array(32); - var x = new Float64Array(80), r, i; - var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(); - for (i = 0; i < 31; i++) z[i] = n[i]; - z[31] = n[31] & 127 | 64; - z[0] &= 248; - unpack25519(x, p); - for (i = 0; i < 16; i++) { - b[i] = x[i]; - d[i] = a[i] = c[i] = 0; - } - a[0] = d[0] = 1; - for (i = 254; i >= 0; --i) { - r = z[i >>> 3] >>> (i & 7) & 1; - sel25519(a, b, r); - sel25519(c, d, r); - A(e, a, c); - Z(a, a, c); - A(c, b, d); - Z(b, b, d); - S(d, e); - S(f, a); - M(a, c, a); - M(c, b, e); - A(e, a, c); - Z(a, a, c); - S(b, a); - Z(c, d, f); - M(a, c, _121665); - A(a, a, d); - M(c, c, a); - M(a, d, f); - M(d, b, x); - S(b, e); - sel25519(a, b, r); - sel25519(c, d, r); - } - for (i = 0; i < 16; i++) { - x[i + 16] = a[i]; - x[i + 32] = c[i]; - x[i + 48] = b[i]; - x[i + 64] = d[i]; - } - var x32 = x.subarray(32); - var x16 = x.subarray(16); - inv25519(x32, x32); - M(x16, x16, x32); - pack25519(q, x16); - return 0; - } - function crypto_scalarmult_base(q, n) { - return crypto_scalarmult(q, n, _9); - } - function crypto_box_keypair(y, x) { - randombytes(x, 32); - return crypto_scalarmult_base(y, x); - } - function crypto_box_beforenm(k, y, x) { - var s = new Uint8Array(32); - crypto_scalarmult(s, x, y); - return crypto_core_hsalsa20(k, _0, s, sigma); - } - var crypto_box_afternm = crypto_secretbox; - var crypto_box_open_afternm = crypto_secretbox_open; - function crypto_box(c, m, d, n, y, x) { - var k = new Uint8Array(32); - crypto_box_beforenm(k, y, x); - return crypto_box_afternm(c, m, d, n, k); - } - function crypto_box_open(m, c, d, n, y, x) { - var k = new Uint8Array(32); - crypto_box_beforenm(k, y, x); - return crypto_box_open_afternm(m, c, d, n, k); - } - var K = [ - 1116352408, - 3609767458, - 1899447441, - 602891725, - 3049323471, - 3964484399, - 3921009573, - 2173295548, - 961987163, - 4081628472, - 1508970993, - 3053834265, - 2453635748, - 2937671579, - 2870763221, - 3664609560, - 3624381080, - 2734883394, - 310598401, - 1164996542, - 607225278, - 1323610764, - 1426881987, - 3590304994, - 1925078388, - 4068182383, - 2162078206, - 991336113, - 2614888103, - 633803317, - 3248222580, - 3479774868, - 3835390401, - 2666613458, - 4022224774, - 944711139, - 264347078, - 2341262773, - 604807628, - 2007800933, - 770255983, - 1495990901, - 1249150122, - 1856431235, - 1555081692, - 3175218132, - 1996064986, - 2198950837, - 2554220882, - 3999719339, - 2821834349, - 766784016, - 2952996808, - 2566594879, - 3210313671, - 3203337956, - 3336571891, - 1034457026, - 3584528711, - 2466948901, - 113926993, - 3758326383, - 338241895, - 168717936, - 666307205, - 1188179964, - 773529912, - 1546045734, - 1294757372, - 1522805485, - 1396182291, - 2643833823, - 1695183700, - 2343527390, - 1986661051, - 1014477480, - 2177026350, - 1206759142, - 2456956037, - 344077627, - 2730485921, - 1290863460, - 2820302411, - 3158454273, - 3259730800, - 3505952657, - 3345764771, - 106217008, - 3516065817, - 3606008344, - 3600352804, - 1432725776, - 4094571909, - 1467031594, - 275423344, - 851169720, - 430227734, - 3100823752, - 506948616, - 1363258195, - 659060556, - 3750685593, - 883997877, - 3785050280, - 958139571, - 3318307427, - 1322822218, - 3812723403, - 1537002063, - 2003034995, - 1747873779, - 3602036899, - 1955562222, - 1575990012, - 2024104815, - 1125592928, - 2227730452, - 2716904306, - 2361852424, - 442776044, - 2428436474, - 593698344, - 2756734187, - 3733110249, - 3204031479, - 2999351573, - 3329325298, - 3815920427, - 3391569614, - 3928383900, - 3515267271, - 566280711, - 3940187606, - 3454069534, - 4118630271, - 4000239992, - 116418474, - 1914138554, - 174292421, - 2731055270, - 289380356, - 3203993006, - 460393269, - 320620315, - 685471733, - 587496836, - 852142971, - 1086792851, - 1017036298, - 365543100, - 1126000580, - 2618297676, - 1288033470, - 3409855158, - 1501505948, - 4234509866, - 1607167915, - 987167468, - 1816402316, - 1246189591 - ]; - function crypto_hashblocks_hl(hh, hl, m, n) { - var wh = new Int32Array(16), wl = new Int32Array(16), bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, th, tl, i, j, h, l, a, b, c, d; - var ah0 = hh[0], ah1 = hh[1], ah2 = hh[2], ah3 = hh[3], ah4 = hh[4], ah5 = hh[5], ah6 = hh[6], ah7 = hh[7], al0 = hl[0], al1 = hl[1], al2 = hl[2], al3 = hl[3], al4 = hl[4], al5 = hl[5], al6 = hl[6], al7 = hl[7]; - var pos = 0; - while (n >= 128) { - for (i = 0; i < 16; i++) { - j = 8 * i + pos; - wh[i] = m[j + 0] << 24 | m[j + 1] << 16 | m[j + 2] << 8 | m[j + 3]; - wl[i] = m[j + 4] << 24 | m[j + 5] << 16 | m[j + 6] << 8 | m[j + 7]; - } - for (i = 0; i < 80; i++) { - bh0 = ah0; - bh1 = ah1; - bh2 = ah2; - bh3 = ah3; - bh4 = ah4; - bh5 = ah5; - bh6 = ah6; - bh7 = ah7; - bl0 = al0; - bl1 = al1; - bl2 = al2; - bl3 = al3; - bl4 = al4; - bl5 = al5; - bl6 = al6; - bl7 = al7; - h = ah7; - l = al7; - a = l & 65535; - b = l >>> 16; - c = h & 65535; - d = h >>> 16; - h = (ah4 >>> 14 | al4 << 32 - 14) ^ (ah4 >>> 18 | al4 << 32 - 18) ^ (al4 >>> 41 - 32 | ah4 << 32 - (41 - 32)); - l = (al4 >>> 14 | ah4 << 32 - 14) ^ (al4 >>> 18 | ah4 << 32 - 18) ^ (ah4 >>> 41 - 32 | al4 << 32 - (41 - 32)); - a += l & 65535; - b += l >>> 16; - c += h & 65535; - d += h >>> 16; - h = ah4 & ah5 ^ ~ah4 & ah6; - l = al4 & al5 ^ ~al4 & al6; - a += l & 65535; - b += l >>> 16; - c += h & 65535; - d += h >>> 16; - h = K[i * 2]; - l = K[i * 2 + 1]; - a += l & 65535; - b += l >>> 16; - c += h & 65535; - d += h >>> 16; - h = wh[i % 16]; - l = wl[i % 16]; - a += l & 65535; - b += l >>> 16; - c += h & 65535; - d += h >>> 16; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - th = c & 65535 | d << 16; - tl = a & 65535 | b << 16; - h = th; - l = tl; - a = l & 65535; - b = l >>> 16; - c = h & 65535; - d = h >>> 16; - h = (ah0 >>> 28 | al0 << 32 - 28) ^ (al0 >>> 34 - 32 | ah0 << 32 - (34 - 32)) ^ (al0 >>> 39 - 32 | ah0 << 32 - (39 - 32)); - l = (al0 >>> 28 | ah0 << 32 - 28) ^ (ah0 >>> 34 - 32 | al0 << 32 - (34 - 32)) ^ (ah0 >>> 39 - 32 | al0 << 32 - (39 - 32)); - a += l & 65535; - b += l >>> 16; - c += h & 65535; - d += h >>> 16; - h = ah0 & ah1 ^ ah0 & ah2 ^ ah1 & ah2; - l = al0 & al1 ^ al0 & al2 ^ al1 & al2; - a += l & 65535; - b += l >>> 16; - c += h & 65535; - d += h >>> 16; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - bh7 = c & 65535 | d << 16; - bl7 = a & 65535 | b << 16; - h = bh3; - l = bl3; - a = l & 65535; - b = l >>> 16; - c = h & 65535; - d = h >>> 16; - h = th; - l = tl; - a += l & 65535; - b += l >>> 16; - c += h & 65535; - d += h >>> 16; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - bh3 = c & 65535 | d << 16; - bl3 = a & 65535 | b << 16; - ah1 = bh0; - ah2 = bh1; - ah3 = bh2; - ah4 = bh3; - ah5 = bh4; - ah6 = bh5; - ah7 = bh6; - ah0 = bh7; - al1 = bl0; - al2 = bl1; - al3 = bl2; - al4 = bl3; - al5 = bl4; - al6 = bl5; - al7 = bl6; - al0 = bl7; - if (i % 16 === 15) { - for (j = 0; j < 16; j++) { - h = wh[j]; - l = wl[j]; - a = l & 65535; - b = l >>> 16; - c = h & 65535; - d = h >>> 16; - h = wh[(j + 9) % 16]; - l = wl[(j + 9) % 16]; - a += l & 65535; - b += l >>> 16; - c += h & 65535; - d += h >>> 16; - th = wh[(j + 1) % 16]; - tl = wl[(j + 1) % 16]; - h = (th >>> 1 | tl << 32 - 1) ^ (th >>> 8 | tl << 32 - 8) ^ th >>> 7; - l = (tl >>> 1 | th << 32 - 1) ^ (tl >>> 8 | th << 32 - 8) ^ (tl >>> 7 | th << 32 - 7); - a += l & 65535; - b += l >>> 16; - c += h & 65535; - d += h >>> 16; - th = wh[(j + 14) % 16]; - tl = wl[(j + 14) % 16]; - h = (th >>> 19 | tl << 32 - 19) ^ (tl >>> 61 - 32 | th << 32 - (61 - 32)) ^ th >>> 6; - l = (tl >>> 19 | th << 32 - 19) ^ (th >>> 61 - 32 | tl << 32 - (61 - 32)) ^ (tl >>> 6 | th << 32 - 6); - a += l & 65535; - b += l >>> 16; - c += h & 65535; - d += h >>> 16; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - wh[j] = c & 65535 | d << 16; - wl[j] = a & 65535 | b << 16; - } - } - } - h = ah0; - l = al0; - a = l & 65535; - b = l >>> 16; - c = h & 65535; - d = h >>> 16; - h = hh[0]; - l = hl[0]; - a += l & 65535; - b += l >>> 16; - c += h & 65535; - d += h >>> 16; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - hh[0] = ah0 = c & 65535 | d << 16; - hl[0] = al0 = a & 65535 | b << 16; - h = ah1; - l = al1; - a = l & 65535; - b = l >>> 16; - c = h & 65535; - d = h >>> 16; - h = hh[1]; - l = hl[1]; - a += l & 65535; - b += l >>> 16; - c += h & 65535; - d += h >>> 16; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - hh[1] = ah1 = c & 65535 | d << 16; - hl[1] = al1 = a & 65535 | b << 16; - h = ah2; - l = al2; - a = l & 65535; - b = l >>> 16; - c = h & 65535; - d = h >>> 16; - h = hh[2]; - l = hl[2]; - a += l & 65535; - b += l >>> 16; - c += h & 65535; - d += h >>> 16; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - hh[2] = ah2 = c & 65535 | d << 16; - hl[2] = al2 = a & 65535 | b << 16; - h = ah3; - l = al3; - a = l & 65535; - b = l >>> 16; - c = h & 65535; - d = h >>> 16; - h = hh[3]; - l = hl[3]; - a += l & 65535; - b += l >>> 16; - c += h & 65535; - d += h >>> 16; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - hh[3] = ah3 = c & 65535 | d << 16; - hl[3] = al3 = a & 65535 | b << 16; - h = ah4; - l = al4; - a = l & 65535; - b = l >>> 16; - c = h & 65535; - d = h >>> 16; - h = hh[4]; - l = hl[4]; - a += l & 65535; - b += l >>> 16; - c += h & 65535; - d += h >>> 16; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - hh[4] = ah4 = c & 65535 | d << 16; - hl[4] = al4 = a & 65535 | b << 16; - h = ah5; - l = al5; - a = l & 65535; - b = l >>> 16; - c = h & 65535; - d = h >>> 16; - h = hh[5]; - l = hl[5]; - a += l & 65535; - b += l >>> 16; - c += h & 65535; - d += h >>> 16; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - hh[5] = ah5 = c & 65535 | d << 16; - hl[5] = al5 = a & 65535 | b << 16; - h = ah6; - l = al6; - a = l & 65535; - b = l >>> 16; - c = h & 65535; - d = h >>> 16; - h = hh[6]; - l = hl[6]; - a += l & 65535; - b += l >>> 16; - c += h & 65535; - d += h >>> 16; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - hh[6] = ah6 = c & 65535 | d << 16; - hl[6] = al6 = a & 65535 | b << 16; - h = ah7; - l = al7; - a = l & 65535; - b = l >>> 16; - c = h & 65535; - d = h >>> 16; - h = hh[7]; - l = hl[7]; - a += l & 65535; - b += l >>> 16; - c += h & 65535; - d += h >>> 16; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - hh[7] = ah7 = c & 65535 | d << 16; - hl[7] = al7 = a & 65535 | b << 16; - pos += 128; - n -= 128; - } - return n; - } - function crypto_hash(out, m, n) { - var hh = new Int32Array(8), hl = new Int32Array(8), x = new Uint8Array(256), i, b = n; - hh[0] = 1779033703; - hh[1] = 3144134277; - hh[2] = 1013904242; - hh[3] = 2773480762; - hh[4] = 1359893119; - hh[5] = 2600822924; - hh[6] = 528734635; - hh[7] = 1541459225; - hl[0] = 4089235720; - hl[1] = 2227873595; - hl[2] = 4271175723; - hl[3] = 1595750129; - hl[4] = 2917565137; - hl[5] = 725511199; - hl[6] = 4215389547; - hl[7] = 327033209; - crypto_hashblocks_hl(hh, hl, m, n); - n %= 128; - for (i = 0; i < n; i++) x[i] = m[b - n + i]; - x[n] = 128; - n = 256 - 128 * (n < 112 ? 1 : 0); - x[n - 9] = 0; - ts64(x, n - 8, b / 536870912 | 0, b << 3); - crypto_hashblocks_hl(hh, hl, x, n); - for (i = 0; i < 8; i++) ts64(out, 8 * i, hh[i], hl[i]); - return 0; - } - function add(p, q) { - var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(), g = gf(), h = gf(), t = gf(); - Z(a, p[1], p[0]); - Z(t, q[1], q[0]); - M(a, a, t); - A(b, p[0], p[1]); - A(t, q[0], q[1]); - M(b, b, t); - M(c, p[3], q[3]); - M(c, c, D2); - M(d, p[2], q[2]); - A(d, d, d); - Z(e, b, a); - Z(f, d, c); - A(g, d, c); - A(h, b, a); - M(p[0], e, f); - M(p[1], h, g); - M(p[2], g, f); - M(p[3], e, h); - } - function cswap(p, q, b) { - var i; - for (i = 0; i < 4; i++) { - sel25519(p[i], q[i], b); - } - } - function pack2(r, p) { - var tx = gf(), ty = gf(), zi = gf(); - inv25519(zi, p[2]); - M(tx, p[0], zi); - M(ty, p[1], zi); - pack25519(r, ty); - r[31] ^= par25519(tx) << 7; - } - function scalarmult(p, q, s) { - var b, i; - set25519(p[0], gf0); - set25519(p[1], gf1); - set25519(p[2], gf1); - set25519(p[3], gf0); - for (i = 255; i >= 0; --i) { - b = s[i / 8 | 0] >> (i & 7) & 1; - cswap(p, q, b); - add(q, p); - add(p, p); - cswap(p, q, b); - } - } - function scalarbase(p, s) { - var q = [gf(), gf(), gf(), gf()]; - set25519(q[0], X); - set25519(q[1], Y); - set25519(q[2], gf1); - M(q[3], X, Y); - scalarmult(p, q, s); - } - function crypto_sign_keypair(pk, sk, seeded) { - var d = new Uint8Array(64); - var p = [gf(), gf(), gf(), gf()]; - var i; - if (!seeded) randombytes(sk, 32); - crypto_hash(d, sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; - scalarbase(p, d); - pack2(pk, p); - for (i = 0; i < 32; i++) sk[i + 32] = pk[i]; - return 0; - } - var L = new Float64Array([237, 211, 245, 92, 26, 99, 18, 88, 214, 156, 247, 162, 222, 249, 222, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16]); - function modL(r, x) { - var carry, i, j, k; - for (i = 63; i >= 32; --i) { - carry = 0; - for (j = i - 32, k = i - 12; j < k; ++j) { - x[j] += carry - 16 * x[i] * L[j - (i - 32)]; - carry = x[j] + 128 >> 8; - x[j] -= carry * 256; - } - x[j] += carry; - x[i] = 0; - } - carry = 0; - for (j = 0; j < 32; j++) { - x[j] += carry - (x[31] >> 4) * L[j]; - carry = x[j] >> 8; - x[j] &= 255; - } - for (j = 0; j < 32; j++) x[j] -= carry * L[j]; - for (i = 0; i < 32; i++) { - x[i + 1] += x[i] >> 8; - r[i] = x[i] & 255; - } - } - function reduce(r) { - var x = new Float64Array(64), i; - for (i = 0; i < 64; i++) x[i] = r[i]; - for (i = 0; i < 64; i++) r[i] = 0; - modL(r, x); - } - function crypto_sign(sm, m, n, sk) { - var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); - var i, j, x = new Float64Array(64); - var p = [gf(), gf(), gf(), gf()]; - crypto_hash(d, sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; - var smlen = n + 64; - for (i = 0; i < n; i++) sm[64 + i] = m[i]; - for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; - crypto_hash(r, sm.subarray(32), n + 32); - reduce(r); - scalarbase(p, r); - pack2(sm, p); - for (i = 32; i < 64; i++) sm[i] = sk[i]; - crypto_hash(h, sm, n + 64); - reduce(h); - for (i = 0; i < 64; i++) x[i] = 0; - for (i = 0; i < 32; i++) x[i] = r[i]; - for (i = 0; i < 32; i++) { - for (j = 0; j < 32; j++) { - x[i + j] += h[i] * d[j]; - } - } - modL(sm.subarray(32), x); - return smlen; - } - function unpackneg(r, p) { - var t = gf(), chk = gf(), num = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf(); - set25519(r[2], gf1); - unpack25519(r[1], p); - S(num, r[1]); - M(den, num, D); - Z(num, num, r[2]); - A(den, r[2], den); - S(den2, den); - S(den4, den2); - M(den6, den4, den2); - M(t, den6, num); - M(t, t, den); - pow2523(t, t); - M(t, t, num); - M(t, t, den); - M(t, t, den); - M(r[0], t, den); - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) M(r[0], r[0], I); - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) return -1; - if (par25519(r[0]) === p[31] >> 7) Z(r[0], gf0, r[0]); - M(r[3], r[0], r[1]); - return 0; - } - function crypto_sign_open(m, sm, n, pk) { - var i, mlen; - var t = new Uint8Array(32), h = new Uint8Array(64); - var p = [gf(), gf(), gf(), gf()], q = [gf(), gf(), gf(), gf()]; - mlen = -1; - if (n < 64) return -1; - if (unpackneg(q, pk)) return -1; - for (i = 0; i < n; i++) m[i] = sm[i]; - for (i = 0; i < 32; i++) m[i + 32] = pk[i]; - crypto_hash(h, m, n); - reduce(h); - scalarmult(p, q, h); - scalarbase(q, sm.subarray(32)); - add(p, q); - pack2(t, p); - n -= 64; - if (crypto_verify_32(sm, 0, t, 0)) { - for (i = 0; i < n; i++) m[i] = 0; - return -1; - } - for (i = 0; i < n; i++) m[i] = sm[i + 64]; - mlen = n; - return mlen; - } - var crypto_secretbox_KEYBYTES = 32, crypto_secretbox_NONCEBYTES = 24, crypto_secretbox_ZEROBYTES = 32, crypto_secretbox_BOXZEROBYTES = 16, crypto_scalarmult_BYTES = 32, crypto_scalarmult_SCALARBYTES = 32, crypto_box_PUBLICKEYBYTES = 32, crypto_box_SECRETKEYBYTES = 32, crypto_box_BEFORENMBYTES = 32, crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, crypto_sign_BYTES = 64, crypto_sign_PUBLICKEYBYTES = 32, crypto_sign_SECRETKEYBYTES = 64, crypto_sign_SEEDBYTES = 32, crypto_hash_BYTES = 64; - nacl.lowlevel = { - crypto_core_hsalsa20, - crypto_stream_xor, - crypto_stream, - crypto_stream_salsa20_xor, - crypto_stream_salsa20, - crypto_onetimeauth, - crypto_onetimeauth_verify, - crypto_verify_16, - crypto_verify_32, - crypto_secretbox, - crypto_secretbox_open, - crypto_scalarmult, - crypto_scalarmult_base, - crypto_box_beforenm, - crypto_box_afternm, - crypto_box, - crypto_box_open, - crypto_box_keypair, - crypto_hash, - crypto_sign, - crypto_sign_keypair, - crypto_sign_open, - crypto_secretbox_KEYBYTES, - crypto_secretbox_NONCEBYTES, - crypto_secretbox_ZEROBYTES, - crypto_secretbox_BOXZEROBYTES, - crypto_scalarmult_BYTES, - crypto_scalarmult_SCALARBYTES, - crypto_box_PUBLICKEYBYTES, - crypto_box_SECRETKEYBYTES, - crypto_box_BEFORENMBYTES, - crypto_box_NONCEBYTES, - crypto_box_ZEROBYTES, - crypto_box_BOXZEROBYTES, - crypto_sign_BYTES, - crypto_sign_PUBLICKEYBYTES, - crypto_sign_SECRETKEYBYTES, - crypto_sign_SEEDBYTES, - crypto_hash_BYTES - }; - function checkLengths(k, n) { - if (k.length !== crypto_secretbox_KEYBYTES) throw new Error("bad key size"); - if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error("bad nonce size"); - } - function checkBoxLengths(pk, sk) { - if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error("bad public key size"); - if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error("bad secret key size"); - } - function checkArrayTypes() { - var t, i; - for (i = 0; i < arguments.length; i++) { - if ((t = Object.prototype.toString.call(arguments[i])) !== "[object Uint8Array]") - throw new TypeError("unexpected type " + t + ", use Uint8Array"); - } - } - function cleanup(arr) { - for (var i = 0; i < arr.length; i++) arr[i] = 0; - } - if (!nacl.util) { - nacl.util = {}; - nacl.util.decodeUTF8 = nacl.util.encodeUTF8 = nacl.util.encodeBase64 = nacl.util.decodeBase64 = function() { - throw new Error("nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js"); - }; - } - nacl.randomBytes = function(n) { - var b = new Uint8Array(n); - randombytes(b, n); - return b; - }; - nacl.secretbox = function(msg, nonce, key) { - checkArrayTypes(msg, nonce, key); - checkLengths(key, nonce); - var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); - var c = new Uint8Array(m.length); - for (var i = 0; i < msg.length; i++) m[i + crypto_secretbox_ZEROBYTES] = msg[i]; - crypto_secretbox(c, m, m.length, nonce, key); - return c.subarray(crypto_secretbox_BOXZEROBYTES); - }; - nacl.secretbox.open = function(box, nonce, key) { - checkArrayTypes(box, nonce, key); - checkLengths(key, nonce); - var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); - var m = new Uint8Array(c.length); - for (var i = 0; i < box.length; i++) c[i + crypto_secretbox_BOXZEROBYTES] = box[i]; - if (c.length < 32) return false; - if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return false; - return m.subarray(crypto_secretbox_ZEROBYTES); - }; - nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES; - nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; - nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; - nacl.scalarMult = function(n, p) { - checkArrayTypes(n, p); - if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error("bad n size"); - if (p.length !== crypto_scalarmult_BYTES) throw new Error("bad p size"); - var q = new Uint8Array(crypto_scalarmult_BYTES); - crypto_scalarmult(q, n, p); - return q; - }; - nacl.scalarMult.base = function(n) { - checkArrayTypes(n); - if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error("bad n size"); - var q = new Uint8Array(crypto_scalarmult_BYTES); - crypto_scalarmult_base(q, n); - return q; - }; - nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; - nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES; - nacl.box = function(msg, nonce, publicKey, secretKey) { - var k = nacl.box.before(publicKey, secretKey); - return nacl.secretbox(msg, nonce, k); - }; - nacl.box.before = function(publicKey, secretKey) { - checkArrayTypes(publicKey, secretKey); - checkBoxLengths(publicKey, secretKey); - var k = new Uint8Array(crypto_box_BEFORENMBYTES); - crypto_box_beforenm(k, publicKey, secretKey); - return k; - }; - nacl.box.after = nacl.secretbox; - nacl.box.open = function(msg, nonce, publicKey, secretKey) { - var k = nacl.box.before(publicKey, secretKey); - return nacl.secretbox.open(msg, nonce, k); - }; - nacl.box.open.after = nacl.secretbox.open; - nacl.box.keyPair = function() { - var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); - crypto_box_keypair(pk, sk); - return { publicKey: pk, secretKey: sk }; - }; - nacl.box.keyPair.fromSecretKey = function(secretKey) { - checkArrayTypes(secretKey); - if (secretKey.length !== crypto_box_SECRETKEYBYTES) - throw new Error("bad secret key size"); - var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); - crypto_scalarmult_base(pk, secretKey); - return { publicKey: pk, secretKey: new Uint8Array(secretKey) }; - }; - nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES; - nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES; - nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES; - nacl.box.nonceLength = crypto_box_NONCEBYTES; - nacl.box.overheadLength = nacl.secretbox.overheadLength; - nacl.sign = function(msg, secretKey) { - checkArrayTypes(msg, secretKey); - if (secretKey.length !== crypto_sign_SECRETKEYBYTES) - throw new Error("bad secret key size"); - var signedMsg = new Uint8Array(crypto_sign_BYTES + msg.length); - crypto_sign(signedMsg, msg, msg.length, secretKey); - return signedMsg; - }; - nacl.sign.open = function(signedMsg, publicKey) { - if (arguments.length !== 2) - throw new Error("nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?"); - checkArrayTypes(signedMsg, publicKey); - if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) - throw new Error("bad public key size"); - var tmp = new Uint8Array(signedMsg.length); - var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); - if (mlen < 0) return null; - var m = new Uint8Array(mlen); - for (var i = 0; i < m.length; i++) m[i] = tmp[i]; - return m; - }; - nacl.sign.detached = function(msg, secretKey) { - var signedMsg = nacl.sign(msg, secretKey); - var sig = new Uint8Array(crypto_sign_BYTES); - for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; - return sig; - }; - nacl.sign.detached.verify = function(msg, sig, publicKey) { - checkArrayTypes(msg, sig, publicKey); - if (sig.length !== crypto_sign_BYTES) - throw new Error("bad signature size"); - if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) - throw new Error("bad public key size"); - var sm = new Uint8Array(crypto_sign_BYTES + msg.length); - var m = new Uint8Array(crypto_sign_BYTES + msg.length); - var i; - for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; - for (i = 0; i < msg.length; i++) sm[i + crypto_sign_BYTES] = msg[i]; - return crypto_sign_open(m, sm, sm.length, publicKey) >= 0; - }; - nacl.sign.keyPair = function() { - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); - crypto_sign_keypair(pk, sk); - return { publicKey: pk, secretKey: sk }; - }; - nacl.sign.keyPair.fromSecretKey = function(secretKey) { - checkArrayTypes(secretKey); - if (secretKey.length !== crypto_sign_SECRETKEYBYTES) - throw new Error("bad secret key size"); - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32 + i]; - return { publicKey: pk, secretKey: new Uint8Array(secretKey) }; - }; - nacl.sign.keyPair.fromSeed = function(seed) { - checkArrayTypes(seed); - if (seed.length !== crypto_sign_SEEDBYTES) - throw new Error("bad seed size"); - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); - for (var i = 0; i < 32; i++) sk[i] = seed[i]; - crypto_sign_keypair(pk, sk, true); - return { publicKey: pk, secretKey: sk }; - }; - nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; - nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; - nacl.sign.seedLength = crypto_sign_SEEDBYTES; - nacl.sign.signatureLength = crypto_sign_BYTES; - nacl.hash = function(msg) { - checkArrayTypes(msg); - var h = new Uint8Array(crypto_hash_BYTES); - crypto_hash(h, msg, msg.length); - return h; - }; - nacl.hash.hashLength = crypto_hash_BYTES; - nacl.verify = function(x, y) { - checkArrayTypes(x, y); - if (x.length === 0 || y.length === 0) return false; - if (x.length !== y.length) return false; - return vn(x, 0, y, 0, x.length) === 0 ? true : false; - }; - nacl.setPRNG = function(fn) { - randombytes = fn; - }; - (function() { - var crypto = typeof self !== "undefined" ? self.crypto || self.msCrypto : null; - if (crypto && crypto.getRandomValues) { - var QUOTA = 65536; - nacl.setPRNG(function(x, n) { - var i, v = new Uint8Array(n); - for (i = 0; i < n; i += QUOTA) { - crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); - } - for (i = 0; i < n; i++) x[i] = v[i]; - cleanup(v); - }); - } else if (typeof require !== "undefined") { - crypto = require("crypto"); - if (crypto && crypto.randomBytes) { - nacl.setPRNG(function(x, n) { - var i, v = crypto.randomBytes(n); - for (i = 0; i < n; i++) x[i] = v[i]; - cleanup(v); - }); - } - } - })(); - })(typeof module2 !== "undefined" && module2.exports ? module2.exports : self.nacl = self.nacl || {}); - } -}); - -// node_modules/bcrypt-pbkdf/index.js -var require_bcrypt_pbkdf = __commonJS({ - "node_modules/bcrypt-pbkdf/index.js"(exports2, module2) { - "use strict"; - var crypto_hash_sha512 = require_nacl_fast().lowlevel.crypto_hash; - var BLF_J = 0; - var Blowfish = function() { - this.S = [ - new Uint32Array([ - 3509652390, - 2564797868, - 805139163, - 3491422135, - 3101798381, - 1780907670, - 3128725573, - 4046225305, - 614570311, - 3012652279, - 134345442, - 2240740374, - 1667834072, - 1901547113, - 2757295779, - 4103290238, - 227898511, - 1921955416, - 1904987480, - 2182433518, - 2069144605, - 3260701109, - 2620446009, - 720527379, - 3318853667, - 677414384, - 3393288472, - 3101374703, - 2390351024, - 1614419982, - 1822297739, - 2954791486, - 3608508353, - 3174124327, - 2024746970, - 1432378464, - 3864339955, - 2857741204, - 1464375394, - 1676153920, - 1439316330, - 715854006, - 3033291828, - 289532110, - 2706671279, - 2087905683, - 3018724369, - 1668267050, - 732546397, - 1947742710, - 3462151702, - 2609353502, - 2950085171, - 1814351708, - 2050118529, - 680887927, - 999245976, - 1800124847, - 3300911131, - 1713906067, - 1641548236, - 4213287313, - 1216130144, - 1575780402, - 4018429277, - 3917837745, - 3693486850, - 3949271944, - 596196993, - 3549867205, - 258830323, - 2213823033, - 772490370, - 2760122372, - 1774776394, - 2652871518, - 566650946, - 4142492826, - 1728879713, - 2882767088, - 1783734482, - 3629395816, - 2517608232, - 2874225571, - 1861159788, - 326777828, - 3124490320, - 2130389656, - 2716951837, - 967770486, - 1724537150, - 2185432712, - 2364442137, - 1164943284, - 2105845187, - 998989502, - 3765401048, - 2244026483, - 1075463327, - 1455516326, - 1322494562, - 910128902, - 469688178, - 1117454909, - 936433444, - 3490320968, - 3675253459, - 1240580251, - 122909385, - 2157517691, - 634681816, - 4142456567, - 3825094682, - 3061402683, - 2540495037, - 79693498, - 3249098678, - 1084186820, - 1583128258, - 426386531, - 1761308591, - 1047286709, - 322548459, - 995290223, - 1845252383, - 2603652396, - 3431023940, - 2942221577, - 3202600964, - 3727903485, - 1712269319, - 422464435, - 3234572375, - 1170764815, - 3523960633, - 3117677531, - 1434042557, - 442511882, - 3600875718, - 1076654713, - 1738483198, - 4213154764, - 2393238008, - 3677496056, - 1014306527, - 4251020053, - 793779912, - 2902807211, - 842905082, - 4246964064, - 1395751752, - 1040244610, - 2656851899, - 3396308128, - 445077038, - 3742853595, - 3577915638, - 679411651, - 2892444358, - 2354009459, - 1767581616, - 3150600392, - 3791627101, - 3102740896, - 284835224, - 4246832056, - 1258075500, - 768725851, - 2589189241, - 3069724005, - 3532540348, - 1274779536, - 3789419226, - 2764799539, - 1660621633, - 3471099624, - 4011903706, - 913787905, - 3497959166, - 737222580, - 2514213453, - 2928710040, - 3937242737, - 1804850592, - 3499020752, - 2949064160, - 2386320175, - 2390070455, - 2415321851, - 4061277028, - 2290661394, - 2416832540, - 1336762016, - 1754252060, - 3520065937, - 3014181293, - 791618072, - 3188594551, - 3933548030, - 2332172193, - 3852520463, - 3043980520, - 413987798, - 3465142937, - 3030929376, - 4245938359, - 2093235073, - 3534596313, - 375366246, - 2157278981, - 2479649556, - 555357303, - 3870105701, - 2008414854, - 3344188149, - 4221384143, - 3956125452, - 2067696032, - 3594591187, - 2921233993, - 2428461, - 544322398, - 577241275, - 1471733935, - 610547355, - 4027169054, - 1432588573, - 1507829418, - 2025931657, - 3646575487, - 545086370, - 48609733, - 2200306550, - 1653985193, - 298326376, - 1316178497, - 3007786442, - 2064951626, - 458293330, - 2589141269, - 3591329599, - 3164325604, - 727753846, - 2179363840, - 146436021, - 1461446943, - 4069977195, - 705550613, - 3059967265, - 3887724982, - 4281599278, - 3313849956, - 1404054877, - 2845806497, - 146425753, - 1854211946 - ]), - new Uint32Array([ - 1266315497, - 3048417604, - 3681880366, - 3289982499, - 290971e4, - 1235738493, - 2632868024, - 2414719590, - 3970600049, - 1771706367, - 1449415276, - 3266420449, - 422970021, - 1963543593, - 2690192192, - 3826793022, - 1062508698, - 1531092325, - 1804592342, - 2583117782, - 2714934279, - 4024971509, - 1294809318, - 4028980673, - 1289560198, - 2221992742, - 1669523910, - 35572830, - 157838143, - 1052438473, - 1016535060, - 1802137761, - 1753167236, - 1386275462, - 3080475397, - 2857371447, - 1040679964, - 2145300060, - 2390574316, - 1461121720, - 2956646967, - 4031777805, - 4028374788, - 33600511, - 2920084762, - 1018524850, - 629373528, - 3691585981, - 3515945977, - 2091462646, - 2486323059, - 586499841, - 988145025, - 935516892, - 3367335476, - 2599673255, - 2839830854, - 265290510, - 3972581182, - 2759138881, - 3795373465, - 1005194799, - 847297441, - 406762289, - 1314163512, - 1332590856, - 1866599683, - 4127851711, - 750260880, - 613907577, - 1450815602, - 3165620655, - 3734664991, - 3650291728, - 3012275730, - 3704569646, - 1427272223, - 778793252, - 1343938022, - 2676280711, - 2052605720, - 1946737175, - 3164576444, - 3914038668, - 3967478842, - 3682934266, - 1661551462, - 3294938066, - 4011595847, - 840292616, - 3712170807, - 616741398, - 312560963, - 711312465, - 1351876610, - 322626781, - 1910503582, - 271666773, - 2175563734, - 1594956187, - 70604529, - 3617834859, - 1007753275, - 1495573769, - 4069517037, - 2549218298, - 2663038764, - 504708206, - 2263041392, - 3941167025, - 2249088522, - 1514023603, - 1998579484, - 1312622330, - 694541497, - 2582060303, - 2151582166, - 1382467621, - 776784248, - 2618340202, - 3323268794, - 2497899128, - 2784771155, - 503983604, - 4076293799, - 907881277, - 423175695, - 432175456, - 1378068232, - 4145222326, - 3954048622, - 3938656102, - 3820766613, - 2793130115, - 2977904593, - 26017576, - 3274890735, - 3194772133, - 1700274565, - 1756076034, - 4006520079, - 3677328699, - 720338349, - 1533947780, - 354530856, - 688349552, - 3973924725, - 1637815568, - 332179504, - 3949051286, - 53804574, - 2852348879, - 3044236432, - 1282449977, - 3583942155, - 3416972820, - 4006381244, - 1617046695, - 2628476075, - 3002303598, - 1686838959, - 431878346, - 2686675385, - 1700445008, - 1080580658, - 1009431731, - 832498133, - 3223435511, - 2605976345, - 2271191193, - 2516031870, - 1648197032, - 4164389018, - 2548247927, - 300782431, - 375919233, - 238389289, - 3353747414, - 2531188641, - 2019080857, - 1475708069, - 455242339, - 2609103871, - 448939670, - 3451063019, - 1395535956, - 2413381860, - 1841049896, - 1491858159, - 885456874, - 4264095073, - 4001119347, - 1565136089, - 3898914787, - 1108368660, - 540939232, - 1173283510, - 2745871338, - 3681308437, - 4207628240, - 3343053890, - 4016749493, - 1699691293, - 1103962373, - 3625875870, - 2256883143, - 3830138730, - 1031889488, - 3479347698, - 1535977030, - 4236805024, - 3251091107, - 2132092099, - 1774941330, - 1199868427, - 1452454533, - 157007616, - 2904115357, - 342012276, - 595725824, - 1480756522, - 206960106, - 497939518, - 591360097, - 863170706, - 2375253569, - 3596610801, - 1814182875, - 2094937945, - 3421402208, - 1082520231, - 3463918190, - 2785509508, - 435703966, - 3908032597, - 1641649973, - 2842273706, - 3305899714, - 1510255612, - 2148256476, - 2655287854, - 3276092548, - 4258621189, - 236887753, - 3681803219, - 274041037, - 1734335097, - 3815195456, - 3317970021, - 1899903192, - 1026095262, - 4050517792, - 356393447, - 2410691914, - 3873677099, - 3682840055 - ]), - new Uint32Array([ - 3913112168, - 2491498743, - 4132185628, - 2489919796, - 1091903735, - 1979897079, - 3170134830, - 3567386728, - 3557303409, - 857797738, - 1136121015, - 1342202287, - 507115054, - 2535736646, - 337727348, - 3213592640, - 1301675037, - 2528481711, - 1895095763, - 1721773893, - 3216771564, - 62756741, - 2142006736, - 835421444, - 2531993523, - 1442658625, - 3659876326, - 2882144922, - 676362277, - 1392781812, - 170690266, - 3921047035, - 1759253602, - 3611846912, - 1745797284, - 664899054, - 1329594018, - 3901205900, - 3045908486, - 2062866102, - 2865634940, - 3543621612, - 3464012697, - 1080764994, - 553557557, - 3656615353, - 3996768171, - 991055499, - 499776247, - 1265440854, - 648242737, - 3940784050, - 980351604, - 3713745714, - 1749149687, - 3396870395, - 4211799374, - 3640570775, - 1161844396, - 3125318951, - 1431517754, - 545492359, - 4268468663, - 3499529547, - 1437099964, - 2702547544, - 3433638243, - 2581715763, - 2787789398, - 1060185593, - 1593081372, - 2418618748, - 4260947970, - 69676912, - 2159744348, - 86519011, - 2512459080, - 3838209314, - 1220612927, - 3339683548, - 133810670, - 1090789135, - 1078426020, - 1569222167, - 845107691, - 3583754449, - 4072456591, - 1091646820, - 628848692, - 1613405280, - 3757631651, - 526609435, - 236106946, - 48312990, - 2942717905, - 3402727701, - 1797494240, - 859738849, - 992217954, - 4005476642, - 2243076622, - 3870952857, - 3732016268, - 765654824, - 3490871365, - 2511836413, - 1685915746, - 3888969200, - 1414112111, - 2273134842, - 3281911079, - 4080962846, - 172450625, - 2569994100, - 980381355, - 4109958455, - 2819808352, - 2716589560, - 2568741196, - 3681446669, - 3329971472, - 1835478071, - 660984891, - 3704678404, - 4045999559, - 3422617507, - 3040415634, - 1762651403, - 1719377915, - 3470491036, - 2693910283, - 3642056355, - 3138596744, - 1364962596, - 2073328063, - 1983633131, - 926494387, - 3423689081, - 2150032023, - 4096667949, - 1749200295, - 3328846651, - 309677260, - 2016342300, - 1779581495, - 3079819751, - 111262694, - 1274766160, - 443224088, - 298511866, - 1025883608, - 3806446537, - 1145181785, - 168956806, - 3641502830, - 3584813610, - 1689216846, - 3666258015, - 3200248200, - 1692713982, - 2646376535, - 4042768518, - 1618508792, - 1610833997, - 3523052358, - 4130873264, - 2001055236, - 3610705100, - 2202168115, - 4028541809, - 2961195399, - 1006657119, - 2006996926, - 3186142756, - 1430667929, - 3210227297, - 1314452623, - 4074634658, - 4101304120, - 2273951170, - 1399257539, - 3367210612, - 3027628629, - 1190975929, - 2062231137, - 2333990788, - 2221543033, - 2438960610, - 1181637006, - 548689776, - 2362791313, - 3372408396, - 3104550113, - 3145860560, - 296247880, - 1970579870, - 3078560182, - 3769228297, - 1714227617, - 3291629107, - 3898220290, - 166772364, - 1251581989, - 493813264, - 448347421, - 195405023, - 2709975567, - 677966185, - 3703036547, - 1463355134, - 2715995803, - 1338867538, - 1343315457, - 2802222074, - 2684532164, - 233230375, - 2599980071, - 2000651841, - 3277868038, - 1638401717, - 4028070440, - 3237316320, - 6314154, - 819756386, - 300326615, - 590932579, - 1405279636, - 3267499572, - 3150704214, - 2428286686, - 3959192993, - 3461946742, - 1862657033, - 1266418056, - 963775037, - 2089974820, - 2263052895, - 1917689273, - 448879540, - 3550394620, - 3981727096, - 150775221, - 3627908307, - 1303187396, - 508620638, - 2975983352, - 2726630617, - 1817252668, - 1876281319, - 1457606340, - 908771278, - 3720792119, - 3617206836, - 2455994898, - 1729034894, - 1080033504 - ]), - new Uint32Array([ - 976866871, - 3556439503, - 2881648439, - 1522871579, - 1555064734, - 1336096578, - 3548522304, - 2579274686, - 3574697629, - 3205460757, - 3593280638, - 3338716283, - 3079412587, - 564236357, - 2993598910, - 1781952180, - 1464380207, - 3163844217, - 3332601554, - 1699332808, - 1393555694, - 1183702653, - 3581086237, - 1288719814, - 691649499, - 2847557200, - 2895455976, - 3193889540, - 2717570544, - 1781354906, - 1676643554, - 2592534050, - 3230253752, - 1126444790, - 2770207658, - 2633158820, - 2210423226, - 2615765581, - 2414155088, - 3127139286, - 673620729, - 2805611233, - 1269405062, - 4015350505, - 3341807571, - 4149409754, - 1057255273, - 2012875353, - 2162469141, - 2276492801, - 2601117357, - 993977747, - 3918593370, - 2654263191, - 753973209, - 36408145, - 2530585658, - 25011837, - 3520020182, - 2088578344, - 530523599, - 2918365339, - 1524020338, - 1518925132, - 3760827505, - 3759777254, - 1202760957, - 3985898139, - 3906192525, - 674977740, - 4174734889, - 2031300136, - 2019492241, - 3983892565, - 4153806404, - 3822280332, - 352677332, - 2297720250, - 60907813, - 90501309, - 3286998549, - 1016092578, - 2535922412, - 2839152426, - 457141659, - 509813237, - 4120667899, - 652014361, - 1966332200, - 2975202805, - 55981186, - 2327461051, - 676427537, - 3255491064, - 2882294119, - 3433927263, - 1307055953, - 942726286, - 933058658, - 2468411793, - 3933900994, - 4215176142, - 1361170020, - 2001714738, - 2830558078, - 3274259782, - 1222529897, - 1679025792, - 2729314320, - 3714953764, - 1770335741, - 151462246, - 3013232138, - 1682292957, - 1483529935, - 471910574, - 1539241949, - 458788160, - 3436315007, - 1807016891, - 3718408830, - 978976581, - 1043663428, - 3165965781, - 1927990952, - 4200891579, - 2372276910, - 3208408903, - 3533431907, - 1412390302, - 2931980059, - 4132332400, - 1947078029, - 3881505623, - 4168226417, - 2941484381, - 1077988104, - 1320477388, - 886195818, - 18198404, - 3786409e3, - 2509781533, - 112762804, - 3463356488, - 1866414978, - 891333506, - 18488651, - 661792760, - 1628790961, - 3885187036, - 3141171499, - 876946877, - 2693282273, - 1372485963, - 791857591, - 2686433993, - 3759982718, - 3167212022, - 3472953795, - 2716379847, - 445679433, - 3561995674, - 3504004811, - 3574258232, - 54117162, - 3331405415, - 2381918588, - 3769707343, - 4154350007, - 1140177722, - 4074052095, - 668550556, - 3214352940, - 367459370, - 261225585, - 2610173221, - 4209349473, - 3468074219, - 3265815641, - 314222801, - 3066103646, - 3808782860, - 282218597, - 3406013506, - 3773591054, - 379116347, - 1285071038, - 846784868, - 2669647154, - 3771962079, - 3550491691, - 2305946142, - 453669953, - 1268987020, - 3317592352, - 3279303384, - 3744833421, - 2610507566, - 3859509063, - 266596637, - 3847019092, - 517658769, - 3462560207, - 3443424879, - 370717030, - 4247526661, - 2224018117, - 4143653529, - 4112773975, - 2788324899, - 2477274417, - 1456262402, - 2901442914, - 1517677493, - 1846949527, - 2295493580, - 3734397586, - 2176403920, - 1280348187, - 1908823572, - 3871786941, - 846861322, - 1172426758, - 3287448474, - 3383383037, - 1655181056, - 3139813346, - 901632758, - 1897031941, - 2986607138, - 3066810236, - 3447102507, - 1393639104, - 373351379, - 950779232, - 625454576, - 3124240540, - 4148612726, - 2007998917, - 544563296, - 2244738638, - 2330496472, - 2058025392, - 1291430526, - 424198748, - 50039436, - 29584100, - 3605783033, - 2429876329, - 2791104160, - 1057563949, - 3255363231, - 3075367218, - 3463963227, - 1469046755, - 985887462 - ]) - ]; - this.P = new Uint32Array([ - 608135816, - 2242054355, - 320440878, - 57701188, - 2752067618, - 698298832, - 137296536, - 3964562569, - 1160258022, - 953160567, - 3193202383, - 887688300, - 3232508343, - 3380367581, - 1065670069, - 3041331479, - 2450970073, - 2306472731 - ]); - }; - function F(S, x8, i) { - return (S[0][x8[i + 3]] + S[1][x8[i + 2]] ^ S[2][x8[i + 1]]) + S[3][x8[i]]; - } - Blowfish.prototype.encipher = function(x, x8) { - if (x8 === void 0) { - x8 = new Uint8Array(x.buffer); - if (x.byteOffset !== 0) - x8 = x8.subarray(x.byteOffset); - } - x[0] ^= this.P[0]; - for (var i = 1; i < 16; i += 2) { - x[1] ^= F(this.S, x8, 0) ^ this.P[i]; - x[0] ^= F(this.S, x8, 4) ^ this.P[i + 1]; - } - var t = x[0]; - x[0] = x[1] ^ this.P[17]; - x[1] = t; - }; - Blowfish.prototype.decipher = function(x) { - var x8 = new Uint8Array(x.buffer); - if (x.byteOffset !== 0) - x8 = x8.subarray(x.byteOffset); - x[0] ^= this.P[17]; - for (var i = 16; i > 0; i -= 2) { - x[1] ^= F(this.S, x8, 0) ^ this.P[i]; - x[0] ^= F(this.S, x8, 4) ^ this.P[i - 1]; - } - var t = x[0]; - x[0] = x[1] ^ this.P[0]; - x[1] = t; - }; - function stream2word(data, databytes) { - var i, temp = 0; - for (i = 0; i < 4; i++, BLF_J++) { - if (BLF_J >= databytes) BLF_J = 0; - temp = temp << 8 | data[BLF_J]; - } - return temp; - } - Blowfish.prototype.expand0state = function(key, keybytes) { - var d = new Uint32Array(2), i, k; - var d8 = new Uint8Array(d.buffer); - for (i = 0, BLF_J = 0; i < 18; i++) { - this.P[i] ^= stream2word(key, keybytes); - } - BLF_J = 0; - for (i = 0; i < 18; i += 2) { - this.encipher(d, d8); - this.P[i] = d[0]; - this.P[i + 1] = d[1]; - } - for (i = 0; i < 4; i++) { - for (k = 0; k < 256; k += 2) { - this.encipher(d, d8); - this.S[i][k] = d[0]; - this.S[i][k + 1] = d[1]; - } - } - }; - Blowfish.prototype.expandstate = function(data, databytes, key, keybytes) { - var d = new Uint32Array(2), i, k; - for (i = 0, BLF_J = 0; i < 18; i++) { - this.P[i] ^= stream2word(key, keybytes); - } - for (i = 0, BLF_J = 0; i < 18; i += 2) { - d[0] ^= stream2word(data, databytes); - d[1] ^= stream2word(data, databytes); - this.encipher(d); - this.P[i] = d[0]; - this.P[i + 1] = d[1]; - } - for (i = 0; i < 4; i++) { - for (k = 0; k < 256; k += 2) { - d[0] ^= stream2word(data, databytes); - d[1] ^= stream2word(data, databytes); - this.encipher(d); - this.S[i][k] = d[0]; - this.S[i][k + 1] = d[1]; - } - } - BLF_J = 0; - }; - Blowfish.prototype.enc = function(data, blocks) { - for (var i = 0; i < blocks; i++) { - this.encipher(data.subarray(i * 2)); - } - }; - Blowfish.prototype.dec = function(data, blocks) { - for (var i = 0; i < blocks; i++) { - this.decipher(data.subarray(i * 2)); - } - }; - var BCRYPT_BLOCKS = 8; - var BCRYPT_HASHSIZE = 32; - function bcrypt_hash(sha2pass, sha2salt, out) { - var state = new Blowfish(), cdata = new Uint32Array(BCRYPT_BLOCKS), i, ciphertext = new Uint8Array([ - 79, - 120, - 121, - 99, - 104, - 114, - 111, - 109, - 97, - 116, - 105, - 99, - 66, - 108, - 111, - 119, - 102, - 105, - 115, - 104, - 83, - 119, - 97, - 116, - 68, - 121, - 110, - 97, - 109, - 105, - 116, - 101 - ]); - state.expandstate(sha2salt, 64, sha2pass, 64); - for (i = 0; i < 64; i++) { - state.expand0state(sha2salt, 64); - state.expand0state(sha2pass, 64); - } - for (i = 0; i < BCRYPT_BLOCKS; i++) - cdata[i] = stream2word(ciphertext, ciphertext.byteLength); - for (i = 0; i < 64; i++) - state.enc(cdata, cdata.byteLength / 8); - for (i = 0; i < BCRYPT_BLOCKS; i++) { - out[4 * i + 3] = cdata[i] >>> 24; - out[4 * i + 2] = cdata[i] >>> 16; - out[4 * i + 1] = cdata[i] >>> 8; - out[4 * i + 0] = cdata[i]; - } - } - function bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) { - var sha2pass = new Uint8Array(64), sha2salt = new Uint8Array(64), out = new Uint8Array(BCRYPT_HASHSIZE), tmpout = new Uint8Array(BCRYPT_HASHSIZE), countsalt = new Uint8Array(saltlen + 4), i, j, amt, stride, dest, count, origkeylen = keylen; - if (rounds < 1) - return -1; - if (passlen === 0 || saltlen === 0 || keylen === 0 || keylen > out.byteLength * out.byteLength || saltlen > 1 << 20) - return -1; - stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength); - amt = Math.floor((keylen + stride - 1) / stride); - for (i = 0; i < saltlen; i++) - countsalt[i] = salt[i]; - crypto_hash_sha512(sha2pass, pass, passlen); - for (count = 1; keylen > 0; count++) { - countsalt[saltlen + 0] = count >>> 24; - countsalt[saltlen + 1] = count >>> 16; - countsalt[saltlen + 2] = count >>> 8; - countsalt[saltlen + 3] = count; - crypto_hash_sha512(sha2salt, countsalt, saltlen + 4); - bcrypt_hash(sha2pass, sha2salt, tmpout); - for (i = out.byteLength; i--; ) - out[i] = tmpout[i]; - for (i = 1; i < rounds; i++) { - crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength); - bcrypt_hash(sha2pass, sha2salt, tmpout); - for (j = 0; j < out.byteLength; j++) - out[j] ^= tmpout[j]; - } - amt = Math.min(amt, keylen); - for (i = 0; i < amt; i++) { - dest = i * stride + (count - 1); - if (dest >= origkeylen) - break; - key[dest] = out[i]; - } - keylen -= i; - } - return 0; - } - module2.exports = { - BLOCKS: BCRYPT_BLOCKS, - HASHSIZE: BCRYPT_HASHSIZE, - hash: bcrypt_hash, - pbkdf: bcrypt_pbkdf - }; - } -}); - -// node_modules/cpu-features/build/Release/cpufeatures.node -var require_cpufeatures = __commonJS({ - "node_modules/cpu-features/build/Release/cpufeatures.node"() { - } -}); - -// node_modules/cpu-features/lib/index.js -var require_lib4 = __commonJS({ - "node_modules/cpu-features/lib/index.js"(exports2, module2) { - "use strict"; - var binding = require_cpufeatures(); - module2.exports = binding.getCPUInfo; - } -}); - -// node_modules/ssh2/lib/protocol/constants.js -var require_constants6 = __commonJS({ - "node_modules/ssh2/lib/protocol/constants.js"(exports2, module2) { - "use strict"; - var crypto = require("crypto"); - var cpuInfo; - try { - cpuInfo = require_lib4()(); - } catch { - } - var { bindingAvailable, CIPHER_INFO, MAC_INFO } = require_crypto(); - var eddsaSupported = (() => { - if (typeof crypto.sign === "function" && typeof crypto.verify === "function") { - const key = "-----BEGIN PRIVATE KEY-----\r\nMC4CAQAwBQYDK2VwBCIEIHKj+sVa9WcD/q2DJUJaf43Kptc8xYuUQA4bOFj9vC8T\r\n-----END PRIVATE KEY-----"; - const data = Buffer.from("a"); - let sig; - let verified; - try { - sig = crypto.sign(null, data, key); - verified = crypto.verify(null, data, key, sig); - } catch { - } - return Buffer.isBuffer(sig) && sig.length === 64 && verified === true; - } - return false; - })(); - var curve25519Supported = typeof crypto.diffieHellman === "function" && typeof crypto.generateKeyPairSync === "function" && typeof crypto.createPublicKey === "function"; - var DEFAULT_KEX = [ - // https://tools.ietf.org/html/rfc5656#section-10.1 - "ecdh-sha2-nistp256", - "ecdh-sha2-nistp384", - "ecdh-sha2-nistp521", - // https://tools.ietf.org/html/rfc4419#section-4 - "diffie-hellman-group-exchange-sha256", - // https://tools.ietf.org/html/rfc8268 - "diffie-hellman-group14-sha256", - "diffie-hellman-group15-sha512", - "diffie-hellman-group16-sha512", - "diffie-hellman-group17-sha512", - "diffie-hellman-group18-sha512" - ]; - if (curve25519Supported) { - DEFAULT_KEX.unshift("curve25519-sha256"); - DEFAULT_KEX.unshift("curve25519-sha256@libssh.org"); - } - var SUPPORTED_KEX = DEFAULT_KEX.concat([ - // https://tools.ietf.org/html/rfc4419#section-4 - "diffie-hellman-group-exchange-sha1", - "diffie-hellman-group14-sha1", - // REQUIRED - "diffie-hellman-group1-sha1" - // REQUIRED - ]); - var DEFAULT_SERVER_HOST_KEY = [ - "ecdsa-sha2-nistp256", - "ecdsa-sha2-nistp384", - "ecdsa-sha2-nistp521", - "rsa-sha2-512", - // RFC 8332 - "rsa-sha2-256", - // RFC 8332 - "ssh-rsa" - ]; - if (eddsaSupported) - DEFAULT_SERVER_HOST_KEY.unshift("ssh-ed25519"); - var SUPPORTED_SERVER_HOST_KEY = DEFAULT_SERVER_HOST_KEY.concat([ - "ssh-dss" - ]); - var canUseCipher = (() => { - const ciphers = crypto.getCiphers(); - return (name) => ciphers.includes(CIPHER_INFO[name].sslName); - })(); - var DEFAULT_CIPHER = [ - // http://tools.ietf.org/html/rfc5647 - "aes128-gcm@openssh.com", - "aes256-gcm@openssh.com", - // http://tools.ietf.org/html/rfc4344#section-4 - "aes128-ctr", - "aes192-ctr", - "aes256-ctr" - ]; - if (cpuInfo && cpuInfo.flags && !cpuInfo.flags.aes) { - if (bindingAvailable) - DEFAULT_CIPHER.unshift("chacha20-poly1305@openssh.com"); - else - DEFAULT_CIPHER.push("chacha20-poly1305@openssh.com"); - } else if (bindingAvailable && cpuInfo && cpuInfo.arch === "x86") { - DEFAULT_CIPHER.splice(4, 0, "chacha20-poly1305@openssh.com"); - } else { - DEFAULT_CIPHER.push("chacha20-poly1305@openssh.com"); - } - DEFAULT_CIPHER = DEFAULT_CIPHER.filter(canUseCipher); - var SUPPORTED_CIPHER = DEFAULT_CIPHER.concat([ - "aes256-cbc", - "aes192-cbc", - "aes128-cbc", - "blowfish-cbc", - "3des-cbc", - "aes128-gcm", - "aes256-gcm", - // http://tools.ietf.org/html/rfc4345#section-4: - "arcfour256", - "arcfour128", - "cast128-cbc", - "arcfour" - ].filter(canUseCipher)); - var canUseMAC = (() => { - const hashes = crypto.getHashes(); - return (name) => hashes.includes(MAC_INFO[name].sslName); - })(); - var DEFAULT_MAC = [ - "hmac-sha2-256-etm@openssh.com", - "hmac-sha2-512-etm@openssh.com", - "hmac-sha1-etm@openssh.com", - "hmac-sha2-256", - "hmac-sha2-512", - "hmac-sha1" - ].filter(canUseMAC); - var SUPPORTED_MAC = DEFAULT_MAC.concat([ - "hmac-md5", - "hmac-sha2-256-96", - // first 96 bits of HMAC-SHA256 - "hmac-sha2-512-96", - // first 96 bits of HMAC-SHA512 - "hmac-ripemd160", - "hmac-sha1-96", - // first 96 bits of HMAC-SHA1 - "hmac-md5-96" - // first 96 bits of HMAC-MD5 - ].filter(canUseMAC)); - var DEFAULT_COMPRESSION = [ - "none", - "zlib@openssh.com", - // ZLIB (LZ77) compression, except - // compression/decompression does not start until after - // successful user authentication - "zlib" - // ZLIB (LZ77) compression - ]; - var SUPPORTED_COMPRESSION = DEFAULT_COMPRESSION.concat([]); - var COMPAT = { - BAD_DHGEX: 1 << 0, - OLD_EXIT: 1 << 1, - DYN_RPORT_BUG: 1 << 2, - BUG_DHGEX_LARGE: 1 << 3, - IMPLY_RSA_SHA2_SIGALGS: 1 << 4 - }; - module2.exports = { - MESSAGE: { - // Transport layer protocol -- generic (1-19) - DISCONNECT: 1, - IGNORE: 2, - UNIMPLEMENTED: 3, - DEBUG: 4, - SERVICE_REQUEST: 5, - SERVICE_ACCEPT: 6, - EXT_INFO: 7, - // RFC 8308 - // Transport layer protocol -- algorithm negotiation (20-29) - KEXINIT: 20, - NEWKEYS: 21, - // Transport layer protocol -- key exchange method-specific (30-49) - KEXDH_INIT: 30, - KEXDH_REPLY: 31, - KEXDH_GEX_GROUP: 31, - KEXDH_GEX_INIT: 32, - KEXDH_GEX_REPLY: 33, - KEXDH_GEX_REQUEST: 34, - KEXECDH_INIT: 30, - KEXECDH_REPLY: 31, - // User auth protocol -- generic (50-59) - USERAUTH_REQUEST: 50, - USERAUTH_FAILURE: 51, - USERAUTH_SUCCESS: 52, - USERAUTH_BANNER: 53, - // User auth protocol -- user auth method-specific (60-79) - USERAUTH_PASSWD_CHANGEREQ: 60, - USERAUTH_PK_OK: 60, - USERAUTH_INFO_REQUEST: 60, - USERAUTH_INFO_RESPONSE: 61, - // Connection protocol -- generic (80-89) - GLOBAL_REQUEST: 80, - REQUEST_SUCCESS: 81, - REQUEST_FAILURE: 82, - // Connection protocol -- channel-related (90-127) - CHANNEL_OPEN: 90, - CHANNEL_OPEN_CONFIRMATION: 91, - CHANNEL_OPEN_FAILURE: 92, - CHANNEL_WINDOW_ADJUST: 93, - CHANNEL_DATA: 94, - CHANNEL_EXTENDED_DATA: 95, - CHANNEL_EOF: 96, - CHANNEL_CLOSE: 97, - CHANNEL_REQUEST: 98, - CHANNEL_SUCCESS: 99, - CHANNEL_FAILURE: 100 - // Reserved for client protocols (128-191) - // Local extensions (192-155) - }, - DISCONNECT_REASON: { - HOST_NOT_ALLOWED_TO_CONNECT: 1, - PROTOCOL_ERROR: 2, - KEY_EXCHANGE_FAILED: 3, - RESERVED: 4, - MAC_ERROR: 5, - COMPRESSION_ERROR: 6, - SERVICE_NOT_AVAILABLE: 7, - PROTOCOL_VERSION_NOT_SUPPORTED: 8, - HOST_KEY_NOT_VERIFIABLE: 9, - CONNECTION_LOST: 10, - BY_APPLICATION: 11, - TOO_MANY_CONNECTIONS: 12, - AUTH_CANCELED_BY_USER: 13, - NO_MORE_AUTH_METHODS_AVAILABLE: 14, - ILLEGAL_USER_NAME: 15 - }, - DISCONNECT_REASON_STR: void 0, - CHANNEL_OPEN_FAILURE: { - ADMINISTRATIVELY_PROHIBITED: 1, - CONNECT_FAILED: 2, - UNKNOWN_CHANNEL_TYPE: 3, - RESOURCE_SHORTAGE: 4 - }, - TERMINAL_MODE: { - TTY_OP_END: 0, - // Indicates end of options. - VINTR: 1, - // Interrupt character; 255 if none. Similarly for the - // other characters. Not all of these characters are - // supported on all systems. - VQUIT: 2, - // The quit character (sends SIGQUIT signal on POSIX - // systems). - VERASE: 3, - // Erase the character to left of the cursor. - VKILL: 4, - // Kill the current input line. - VEOF: 5, - // End-of-file character (sends EOF from the - // terminal). - VEOL: 6, - // End-of-line character in addition to carriage - // return and/or linefeed. - VEOL2: 7, - // Additional end-of-line character. - VSTART: 8, - // Continues paused output (normally control-Q). - VSTOP: 9, - // Pauses output (normally control-S). - VSUSP: 10, - // Suspends the current program. - VDSUSP: 11, - // Another suspend character. - VREPRINT: 12, - // Reprints the current input line. - VWERASE: 13, - // Erases a word left of cursor. - VLNEXT: 14, - // Enter the next character typed literally, even if - // it is a special character - VFLUSH: 15, - // Character to flush output. - VSWTCH: 16, - // Switch to a different shell layer. - VSTATUS: 17, - // Prints system status line (load, command, pid, - // etc). - VDISCARD: 18, - // Toggles the flushing of terminal output. - IGNPAR: 30, - // The ignore parity flag. The parameter SHOULD be 0 - // if this flag is FALSE, and 1 if it is TRUE. - PARMRK: 31, - // Mark parity and framing errors. - INPCK: 32, - // Enable checking of parity errors. - ISTRIP: 33, - // Strip 8th bit off characters. - INLCR: 34, - // Map NL into CR on input. - IGNCR: 35, - // Ignore CR on input. - ICRNL: 36, - // Map CR to NL on input. - IUCLC: 37, - // Translate uppercase characters to lowercase. - IXON: 38, - // Enable output flow control. - IXANY: 39, - // Any char will restart after stop. - IXOFF: 40, - // Enable input flow control. - IMAXBEL: 41, - // Ring bell on input queue full. - ISIG: 50, - // Enable signals INTR, QUIT, [D]SUSP. - ICANON: 51, - // Canonicalize input lines. - XCASE: 52, - // Enable input and output of uppercase characters by - // preceding their lowercase equivalents with "\". - ECHO: 53, - // Enable echoing. - ECHOE: 54, - // Visually erase chars. - ECHOK: 55, - // Kill character discards current line. - ECHONL: 56, - // Echo NL even if ECHO is off. - NOFLSH: 57, - // Don't flush after interrupt. - TOSTOP: 58, - // Stop background jobs from output. - IEXTEN: 59, - // Enable extensions. - ECHOCTL: 60, - // Echo control characters as ^(Char). - ECHOKE: 61, - // Visual erase for line kill. - PENDIN: 62, - // Retype pending input. - OPOST: 70, - // Enable output processing. - OLCUC: 71, - // Convert lowercase to uppercase. - ONLCR: 72, - // Map NL to CR-NL. - OCRNL: 73, - // Translate carriage return to newline (output). - ONOCR: 74, - // Translate newline to carriage return-newline - // (output). - ONLRET: 75, - // Newline performs a carriage return (output). - CS7: 90, - // 7 bit mode. - CS8: 91, - // 8 bit mode. - PARENB: 92, - // Parity enable. - PARODD: 93, - // Odd parity, else even. - TTY_OP_ISPEED: 128, - // Specifies the input baud rate in bits per second. - TTY_OP_OSPEED: 129 - // Specifies the output baud rate in bits per second. - }, - CHANNEL_EXTENDED_DATATYPE: { - STDERR: 1 - }, - SIGNALS: [ - "ABRT", - "ALRM", - "FPE", - "HUP", - "ILL", - "INT", - "QUIT", - "SEGV", - "TERM", - "USR1", - "USR2", - "KILL", - "PIPE" - ].reduce((cur, val) => ({ ...cur, [val]: 1 }), {}), - COMPAT, - COMPAT_CHECKS: [ - ["Cisco-1.25", COMPAT.BAD_DHGEX], - [/^Cisco-1[.]/, COMPAT.BUG_DHGEX_LARGE], - [/^[0-9.]+$/, COMPAT.OLD_EXIT], - // old SSH.com implementations - [/^OpenSSH_5[.][0-9]+/, COMPAT.DYN_RPORT_BUG], - [/^OpenSSH_7[.]4/, COMPAT.IMPLY_RSA_SHA2_SIGALGS] - ], - // KEX proposal-related - DEFAULT_KEX, - SUPPORTED_KEX, - DEFAULT_SERVER_HOST_KEY, - SUPPORTED_SERVER_HOST_KEY, - DEFAULT_CIPHER, - SUPPORTED_CIPHER, - DEFAULT_MAC, - SUPPORTED_MAC, - DEFAULT_COMPRESSION, - SUPPORTED_COMPRESSION, - curve25519Supported, - eddsaSupported - }; - module2.exports.DISCONNECT_REASON_BY_VALUE = Array.from(Object.entries(module2.exports.DISCONNECT_REASON)).reduce((obj, [key, value]) => ({ ...obj, [value]: key }), {}); - } -}); - -// node_modules/ssh2/lib/protocol/utils.js -var require_utils4 = __commonJS({ - "node_modules/ssh2/lib/protocol/utils.js"(exports2, module2) { - "use strict"; - var Ber = require_lib3().Ber; - var DISCONNECT_REASON; - var FastBuffer = Buffer[Symbol.species]; - var TypedArrayFill = Object.getPrototypeOf(Uint8Array.prototype).fill; - function readUInt32BE(buf, offset) { - return buf[offset++] * 16777216 + buf[offset++] * 65536 + buf[offset++] * 256 + buf[offset]; - } - function bufferCopy(src, dest, srcStart, srcEnd, destStart) { - if (!destStart) - destStart = 0; - if (srcEnd > src.length) - srcEnd = src.length; - let nb = srcEnd - srcStart; - const destLeft = dest.length - destStart; - if (nb > destLeft) - nb = destLeft; - dest.set( - new Uint8Array(src.buffer, src.byteOffset + srcStart, nb), - destStart - ); - return nb; - } - function bufferSlice(buf, start, end) { - if (end === void 0) - end = buf.length; - return new FastBuffer(buf.buffer, buf.byteOffset + start, end - start); - } - function makeBufferParser() { - let pos = 0; - let buffer; - const self2 = { - init: (buf, start) => { - buffer = buf; - pos = typeof start === "number" ? start : 0; - }, - pos: () => pos, - length: () => buffer ? buffer.length : 0, - avail: () => buffer && pos < buffer.length ? buffer.length - pos : 0, - clear: () => { - buffer = void 0; - }, - readUInt32BE: () => { - if (!buffer || pos + 3 >= buffer.length) - return; - return buffer[pos++] * 16777216 + buffer[pos++] * 65536 + buffer[pos++] * 256 + buffer[pos++]; - }, - readUInt64BE: (behavior) => { - if (!buffer || pos + 7 >= buffer.length) - return; - switch (behavior) { - case "always": - return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`); - case "maybe": - if (buffer[pos] > 31) - return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`); - // FALLTHROUGH - default: - return buffer[pos++] * 72057594037927940 + buffer[pos++] * 281474976710656 + buffer[pos++] * 1099511627776 + buffer[pos++] * 4294967296 + buffer[pos++] * 16777216 + buffer[pos++] * 65536 + buffer[pos++] * 256 + buffer[pos++]; - } - }, - skip: (n) => { - if (buffer && n > 0) - pos += n; - }, - skipString: () => { - const len = self2.readUInt32BE(); - if (len === void 0) - return; - pos += len; - return pos <= buffer.length ? len : void 0; - }, - readByte: () => { - if (buffer && pos < buffer.length) - return buffer[pos++]; - }, - readBool: () => { - if (buffer && pos < buffer.length) - return !!buffer[pos++]; - }, - readList: () => { - const list = self2.readString(true); - if (list === void 0) - return; - return list ? list.split(",") : []; - }, - readString: (dest, maxLen) => { - if (typeof dest === "number") { - maxLen = dest; - dest = void 0; - } - const len = self2.readUInt32BE(); - if (len === void 0) - return; - if (buffer.length - pos < len || typeof maxLen === "number" && len > maxLen) { - return; - } - if (dest) { - if (Buffer.isBuffer(dest)) - return bufferCopy(buffer, dest, pos, pos += len); - return buffer.utf8Slice(pos, pos += len); - } - return bufferSlice(buffer, pos, pos += len); - }, - readRaw: (len) => { - if (!buffer) - return; - if (typeof len !== "number") - return bufferSlice(buffer, pos, pos += buffer.length - pos); - if (buffer.length - pos >= len) - return bufferSlice(buffer, pos, pos += len); - } - }; - return self2; - } - function makeError(msg, level, fatal) { - const err = new Error(msg); - if (typeof level === "boolean") { - fatal = level; - err.level = "protocol"; - } else { - err.level = level || "protocol"; - } - err.fatal = !!fatal; - return err; - } - function writeUInt32BE(buf, value, offset) { - buf[offset++] = value >>> 24; - buf[offset++] = value >>> 16; - buf[offset++] = value >>> 8; - buf[offset++] = value; - return offset; - } - var utilBufferParser = makeBufferParser(); - module2.exports = { - bufferCopy, - bufferSlice, - FastBuffer, - bufferFill: (buf, value, start, end) => { - return TypedArrayFill.call(buf, value, start, end); - }, - makeError, - doFatalError: (protocol, msg, level, reason) => { - let err; - if (DISCONNECT_REASON === void 0) - ({ DISCONNECT_REASON } = require_constants6()); - if (msg instanceof Error) { - err = msg; - if (typeof level !== "number") - reason = DISCONNECT_REASON.PROTOCOL_ERROR; - else - reason = level; - } else { - err = makeError(msg, level, true); - } - if (typeof reason !== "number") - reason = DISCONNECT_REASON.PROTOCOL_ERROR; - protocol.disconnect(reason); - protocol._destruct(); - protocol._onError(err); - return Infinity; - }, - readUInt32BE, - writeUInt32BE, - writeUInt32LE: (buf, value, offset) => { - buf[offset++] = value; - buf[offset++] = value >>> 8; - buf[offset++] = value >>> 16; - buf[offset++] = value >>> 24; - return offset; - }, - makeBufferParser, - bufferParser: makeBufferParser(), - readString: (buffer, start, dest, maxLen) => { - if (typeof dest === "number") { - maxLen = dest; - dest = void 0; - } - if (start === void 0) - start = 0; - const left = buffer.length - start; - if (start < 0 || start >= buffer.length || left < 4) - return; - const len = readUInt32BE(buffer, start); - if (left < 4 + len || typeof maxLen === "number" && len > maxLen) - return; - start += 4; - const end = start + len; - buffer._pos = end; - if (dest) { - if (Buffer.isBuffer(dest)) - return bufferCopy(buffer, dest, start, end); - return buffer.utf8Slice(start, end); - } - return bufferSlice(buffer, start, end); - }, - sigSSHToASN1: (sig, type) => { - switch (type) { - case "ssh-dss": { - if (sig.length > 40) - return sig; - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - let r = sig.slice(0, 20); - let s = sig.slice(20); - if (r[0] & 128) { - const rNew = Buffer.allocUnsafe(21); - rNew[0] = 0; - r.copy(rNew, 1); - r = rNew; - } else if (r[0] === 0 && !(r[1] & 128)) { - r = r.slice(1); - } - if (s[0] & 128) { - const sNew = Buffer.allocUnsafe(21); - sNew[0] = 0; - s.copy(sNew, 1); - s = sNew; - } else if (s[0] === 0 && !(s[1] & 128)) { - s = s.slice(1); - } - asnWriter.writeBuffer(r, Ber.Integer); - asnWriter.writeBuffer(s, Ber.Integer); - asnWriter.endSequence(); - return asnWriter.buffer; - } - case "ecdsa-sha2-nistp256": - case "ecdsa-sha2-nistp384": - case "ecdsa-sha2-nistp521": { - utilBufferParser.init(sig, 0); - const r = utilBufferParser.readString(); - const s = utilBufferParser.readString(); - utilBufferParser.clear(); - if (r === void 0 || s === void 0) - return; - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - asnWriter.writeBuffer(r, Ber.Integer); - asnWriter.writeBuffer(s, Ber.Integer); - asnWriter.endSequence(); - return asnWriter.buffer; - } - default: - return sig; - } - }, - convertSignature: (signature, keyType) => { - switch (keyType) { - case "ssh-dss": { - if (signature.length <= 40) - return signature; - const asnReader = new Ber.Reader(signature); - asnReader.readSequence(); - let r = asnReader.readString(Ber.Integer, true); - let s = asnReader.readString(Ber.Integer, true); - let rOffset = 0; - let sOffset = 0; - if (r.length < 20) { - const rNew = Buffer.allocUnsafe(20); - rNew.set(r, 1); - r = rNew; - r[0] = 0; - } - if (s.length < 20) { - const sNew = Buffer.allocUnsafe(20); - sNew.set(s, 1); - s = sNew; - s[0] = 0; - } - if (r.length > 20 && r[0] === 0) - rOffset = 1; - if (s.length > 20 && s[0] === 0) - sOffset = 1; - const newSig = Buffer.allocUnsafe(r.length - rOffset + (s.length - sOffset)); - bufferCopy(r, newSig, rOffset, r.length, 0); - bufferCopy(s, newSig, sOffset, s.length, r.length - rOffset); - return newSig; - } - case "ecdsa-sha2-nistp256": - case "ecdsa-sha2-nistp384": - case "ecdsa-sha2-nistp521": { - if (signature[0] === 0) - return signature; - const asnReader = new Ber.Reader(signature); - asnReader.readSequence(); - const r = asnReader.readString(Ber.Integer, true); - const s = asnReader.readString(Ber.Integer, true); - if (r === null || s === null) - return; - const newSig = Buffer.allocUnsafe(4 + r.length + 4 + s.length); - writeUInt32BE(newSig, r.length, 0); - newSig.set(r, 4); - writeUInt32BE(newSig, s.length, 4 + r.length); - newSig.set(s, 4 + 4 + r.length); - return newSig; - } - } - return signature; - }, - sendPacket: (proto, packet, bypass) => { - if (!bypass && proto._kexinit !== void 0) { - if (proto._queue === void 0) - proto._queue = []; - proto._queue.push(packet); - proto._debug && proto._debug("Outbound: ... packet queued"); - return false; - } - proto._cipher.encrypt(packet); - return true; - } - }; - } -}); - -// node_modules/ssh2/lib/protocol/crypto/build/Release/sshcrypto.node -var require_sshcrypto = __commonJS({ - "node_modules/ssh2/lib/protocol/crypto/build/Release/sshcrypto.node"() { - } -}); - -// node_modules/ssh2/lib/protocol/crypto/poly1305.js -var require_poly1305 = __commonJS({ - "node_modules/ssh2/lib/protocol/crypto/poly1305.js"(exports2, module2) { - var createPoly1305 = (function() { - var _scriptDir = typeof document !== "undefined" && document.currentScript ? document.currentScript.src : void 0; - if (typeof __filename !== "undefined") _scriptDir = _scriptDir || __filename; - return (function(createPoly13052) { - createPoly13052 = createPoly13052 || {}; - var b; - b || (b = typeof createPoly13052 !== "undefined" ? createPoly13052 : {}); - var q, r; - b.ready = new Promise(function(a, c) { - q = a; - r = c; - }); - var u = {}, w; - for (w in b) b.hasOwnProperty(w) && (u[w] = b[w]); - var x = "object" === typeof window, y = "function" === typeof importScripts, z = "object" === typeof process && "object" === typeof process.versions && "string" === typeof process.versions.node, B = "", C, D, E, F, G; - if (z) B = y ? require("path").dirname(B) + "/" : __dirname + "/", C = function(a, c) { - var d = H(a); - if (d) return c ? d : d.toString(); - F || (F = require("fs")); - G || (G = require("path")); - a = G.normalize(a); - return F.readFileSync(a, c ? null : "utf8"); - }, E = function(a) { - a = C(a, true); - a.buffer || (a = new Uint8Array(a)); - assert(a.buffer); - return a; - }, D = function(a, c, d) { - var e = H(a); - e && c(e); - F || (F = require("fs")); - G || (G = require("path")); - a = G.normalize(a); - F.readFile(a, function(f, l) { - f ? d(f) : c(l.buffer); - }); - }, 1 < process.argv.length && process.argv[1].replace(/\\/g, "/"), process.argv.slice(2), b.inspect = function() { - return "[Emscripten Module object]"; - }; - else if (x || y) y ? B = self.location.href : "undefined" !== typeof document && document.currentScript && (B = document.currentScript.src), _scriptDir && (B = _scriptDir), 0 !== B.indexOf("blob:") ? B = B.substr(0, B.lastIndexOf("/") + 1) : B = "", C = function(a) { - try { - var c = new XMLHttpRequest(); - c.open("GET", a, false); - c.send(null); - return c.responseText; - } catch (f) { - if (a = H(a)) { - c = []; - for (var d = 0; d < a.length; d++) { - var e = a[d]; - 255 < e && (ba && assert(false, "Character code " + e + " (" + String.fromCharCode(e) + ") at offset " + d + " not in 0x00-0xFF."), e &= 255); - c.push(String.fromCharCode(e)); - } - return c.join(""); - } - throw f; - } - }, y && (E = function(a) { - try { - var c = new XMLHttpRequest(); - c.open("GET", a, false); - c.responseType = "arraybuffer"; - c.send(null); - return new Uint8Array(c.response); - } catch (d) { - if (a = H(a)) return a; - throw d; - } - }), D = function(a, c, d) { - var e = new XMLHttpRequest(); - e.open("GET", a, true); - e.responseType = "arraybuffer"; - e.onload = function() { - if (200 == e.status || 0 == e.status && e.response) c(e.response); - else { - var f = H(a); - f ? c(f.buffer) : d(); - } - }; - e.onerror = d; - e.send(null); - }; - b.print || console.log.bind(console); - var I = b.printErr || console.warn.bind(console); - for (w in u) u.hasOwnProperty(w) && (b[w] = u[w]); - u = null; - var J; - b.wasmBinary && (J = b.wasmBinary); - var noExitRuntime = b.noExitRuntime || true; - "object" !== typeof WebAssembly && K("no native wasm support detected"); - var L, M = false; - function assert(a, c) { - a || K("Assertion failed: " + c); - } - function N(a) { - var c = b["_" + a]; - assert(c, "Cannot call unknown function " + a + ", make sure it is exported"); - return c; - } - function ca(a, c, d, e) { - var f = { string: function(g) { - var p = 0; - if (null !== g && void 0 !== g && 0 !== g) { - var n = (g.length << 2) + 1; - p = O(n); - var k = p, h = P; - if (0 < n) { - n = k + n - 1; - for (var v = 0; v < g.length; ++v) { - var m = g.charCodeAt(v); - if (55296 <= m && 57343 >= m) { - var oa = g.charCodeAt(++v); - m = 65536 + ((m & 1023) << 10) | oa & 1023; - } - if (127 >= m) { - if (k >= n) break; - h[k++] = m; - } else { - if (2047 >= m) { - if (k + 1 >= n) break; - h[k++] = 192 | m >> 6; - } else { - if (65535 >= m) { - if (k + 2 >= n) break; - h[k++] = 224 | m >> 12; - } else { - if (k + 3 >= n) break; - h[k++] = 240 | m >> 18; - h[k++] = 128 | m >> 12 & 63; - } - h[k++] = 128 | m >> 6 & 63; - } - h[k++] = 128 | m & 63; - } - } - h[k] = 0; - } - } - return p; - }, array: function(g) { - var p = O(g.length); - Q.set(g, p); - return p; - } }, l = N(a), A = []; - a = 0; - if (e) for (var t = 0; t < e.length; t++) { - var aa = f[d[t]]; - aa ? (0 === a && (a = da()), A[t] = aa(e[t])) : A[t] = e[t]; - } - d = l.apply(null, A); - d = (function(g) { - if ("string" === c) if (g) { - for (var p = P, n = g + NaN, k = g; p[k] && !(k >= n); ) ++k; - if (16 < k - g && p.subarray && ea) g = ea.decode(p.subarray(g, k)); - else { - for (n = ""; g < k; ) { - var h = p[g++]; - if (h & 128) { - var v = p[g++] & 63; - if (192 == (h & 224)) n += String.fromCharCode((h & 31) << 6 | v); - else { - var m = p[g++] & 63; - h = 224 == (h & 240) ? (h & 15) << 12 | v << 6 | m : (h & 7) << 18 | v << 12 | m << 6 | p[g++] & 63; - 65536 > h ? n += String.fromCharCode(h) : (h -= 65536, n += String.fromCharCode(55296 | h >> 10, 56320 | h & 1023)); - } - } else n += String.fromCharCode(h); - } - g = n; - } - } else g = ""; - else g = "boolean" === c ? !!g : g; - return g; - })(d); - 0 !== a && fa(a); - return d; - } - var ea = "undefined" !== typeof TextDecoder ? new TextDecoder("utf8") : void 0, ha, Q, P; - function ia() { - var a = L.buffer; - ha = a; - b.HEAP8 = Q = new Int8Array(a); - b.HEAP16 = new Int16Array(a); - b.HEAP32 = new Int32Array(a); - b.HEAPU8 = P = new Uint8Array(a); - b.HEAPU16 = new Uint16Array(a); - b.HEAPU32 = new Uint32Array(a); - b.HEAPF32 = new Float32Array(a); - b.HEAPF64 = new Float64Array(a); - } - var R, ja = [], ka = [], la = []; - function ma() { - var a = b.preRun.shift(); - ja.unshift(a); - } - var S = 0, T = null, U = null; - b.preloadedImages = {}; - b.preloadedAudios = {}; - function K(a) { - if (b.onAbort) b.onAbort(a); - I(a); - M = true; - a = new WebAssembly.RuntimeError("abort(" + a + "). Build with -s ASSERTIONS=1 for more info."); - r(a); - throw a; - } - var V = "data:application/octet-stream;base64,", W; - W = "data:application/octet-stream;base64,AGFzbQEAAAABIAZgAX8Bf2ADf39/AGABfwBgAABgAAF/YAZ/f39/f38AAgcBAWEBYQAAAwsKAAEDAQAAAgQFAgQFAXABAQEFBwEBgAKAgAIGCQF/AUGAjMACCwclCQFiAgABYwADAWQACQFlAAgBZgAHAWcABgFoAAUBaQAKAWoBAAqGTQpPAQJ/QYAIKAIAIgEgAEEDakF8cSICaiEAAkAgAkEAIAAgAU0bDQAgAD8AQRB0SwRAIAAQAEUNAQtBgAggADYCACABDwtBhAhBMDYCAEF/C4wFAg5+Cn8gACgCJCEUIAAoAiAhFSAAKAIcIREgACgCGCESIAAoAhQhEyACQRBPBEAgAC0ATEVBGHQhFyAAKAIEIhZBBWytIQ8gACgCCCIYQQVsrSENIAAoAgwiGUEFbK0hCyAAKAIQIhpBBWytIQkgADUCACEIIBqtIRAgGa0hDiAYrSEMIBatIQoDQCASIAEtAAMiEiABLQAEQQh0ciABLQAFQRB0ciABLQAGIhZBGHRyQQJ2Qf///x9xaq0iAyAOfiABLwAAIAEtAAJBEHRyIBNqIBJBGHRBgICAGHFqrSIEIBB+fCARIAEtAAdBCHQgFnIgAS0ACEEQdHIgAS0ACSIRQRh0ckEEdkH///8fcWqtIgUgDH58IAEtAApBCHQgEXIgAS0AC0EQdHIgAS0ADEEYdHJBBnYgFWqtIgYgCn58IBQgF2ogAS8ADSABLQAPQRB0cmqtIgcgCH58IAMgDH4gBCAOfnwgBSAKfnwgBiAIfnwgByAJfnwgAyAKfiAEIAx+fCAFIAh+fCAGIAl+fCAHIAt+fCADIAh+IAQgCn58IAUgCX58IAYgC358IAcgDX58IAMgCX4gBCAIfnwgBSALfnwgBiANfnwgByAPfnwiA0IaiEL/////D4N8IgRCGohC/////w+DfCIFQhqIQv////8Pg3wiBkIaiEL/////D4N8IgdCGoinQQVsIAOnQf///x9xaiITQRp2IASnQf///x9xaiESIAWnQf///x9xIREgBqdB////H3EhFSAHp0H///8fcSEUIBNB////H3EhEyABQRBqIQEgAkEQayICQQ9LDQALCyAAIBQ2AiQgACAVNgIgIAAgETYCHCAAIBI2AhggACATNgIUCwMAAQu2BAEGfwJAIAAoAjgiBARAIABBPGohBQJAIAJBECAEayIDIAIgA0kbIgZFDQAgBkEDcSEHAkAgBkEBa0EDSQRAQQAhAwwBCyAGQXxxIQhBACEDA0AgBSADIARqaiABIANqLQAAOgAAIAUgA0EBciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0ECciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0EDciIEIAAoAjhqaiABIARqLQAAOgAAIANBBGohAyAAKAI4IQQgCEEEayIIDQALCyAHRQ0AA0AgBSADIARqaiABIANqLQAAOgAAIANBAWohAyAAKAI4IQQgB0EBayIHDQALCyAAIAQgBmoiAzYCOCADQRBJDQEgACAFQRAQAiAAQQA2AjggAiAGayECIAEgBmohAQsgAkEQTwRAIAAgASACQXBxIgMQAiACQQ9xIQIgASADaiEBCyACRQ0AIAJBA3EhBCAAQTxqIQVBACEDIAJBAWtBA08EQCACQXxxIQcDQCAFIAAoAjggA2pqIAEgA2otAAA6AAAgBSADQQFyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQJyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQNyIgYgACgCOGpqIAEgBmotAAA6AAAgA0EEaiEDIAdBBGsiBw0ACwsgBARAA0AgBSAAKAI4IANqaiABIANqLQAAOgAAIANBAWohAyAEQQFrIgQNAAsLIAAgACgCOCACajYCOAsLoS0BDH8jAEEQayIMJAACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAEH0AU0EQEGICCgCACIFQRAgAEELakF4cSAAQQtJGyIIQQN2IgJ2IgFBA3EEQCABQX9zQQFxIAJqIgNBA3QiAUG4CGooAgAiBEEIaiEAAkAgBCgCCCICIAFBsAhqIgFGBEBBiAggBUF+IAN3cTYCAAwBCyACIAE2AgwgASACNgIICyAEIANBA3QiAUEDcjYCBCABIARqIgEgASgCBEEBcjYCBAwNCyAIQZAIKAIAIgpNDQEgAQRAAkBBAiACdCIAQQAgAGtyIAEgAnRxIgBBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2aiIDQQN0IgBBuAhqKAIAIgQoAggiASAAQbAIaiIARgRAQYgIIAVBfiADd3EiBTYCAAwBCyABIAA2AgwgACABNgIICyAEQQhqIQAgBCAIQQNyNgIEIAQgCGoiAiADQQN0IgEgCGsiA0EBcjYCBCABIARqIAM2AgAgCgRAIApBA3YiAUEDdEGwCGohB0GcCCgCACEEAn8gBUEBIAF0IgFxRQRAQYgIIAEgBXI2AgAgBwwBCyAHKAIICyEBIAcgBDYCCCABIAQ2AgwgBCAHNgIMIAQgATYCCAtBnAggAjYCAEGQCCADNgIADA0LQYwIKAIAIgZFDQEgBkEAIAZrcUEBayIAIABBDHZBEHEiAnYiAUEFdkEIcSIAIAJyIAEgAHYiAUECdkEEcSIAciABIAB2IgFBAXZBAnEiAHIgASAAdiIBQQF2QQFxIgByIAEgAHZqQQJ0QbgKaigCACIBKAIEQXhxIAhrIQMgASECA0ACQCACKAIQIgBFBEAgAigCFCIARQ0BCyAAKAIEQXhxIAhrIgIgAyACIANJIgIbIQMgACABIAIbIQEgACECDAELCyABIAhqIgkgAU0NAiABKAIYIQsgASABKAIMIgRHBEAgASgCCCIAQZgIKAIASRogACAENgIMIAQgADYCCAwMCyABQRRqIgIoAgAiAEUEQCABKAIQIgBFDQQgAUEQaiECCwNAIAIhByAAIgRBFGoiAigCACIADQAgBEEQaiECIAQoAhAiAA0ACyAHQQA2AgAMCwtBfyEIIABBv39LDQAgAEELaiIAQXhxIQhBjAgoAgAiCUUNAEEAIAhrIQMCQAJAAkACf0EAIAhBgAJJDQAaQR8gCEH///8HSw0AGiAAQQh2IgAgAEGA/j9qQRB2QQhxIgJ0IgAgAEGA4B9qQRB2QQRxIgF0IgAgAEGAgA9qQRB2QQJxIgB0QQ92IAEgAnIgAHJrIgBBAXQgCCAAQRVqdkEBcXJBHGoLIgVBAnRBuApqKAIAIgJFBEBBACEADAELQQAhACAIQQBBGSAFQQF2ayAFQR9GG3QhAQNAAkAgAigCBEF4cSAIayIHIANPDQAgAiEEIAciAw0AQQAhAyACIQAMAwsgACACKAIUIgcgByACIAFBHXZBBHFqKAIQIgJGGyAAIAcbIQAgAUEBdCEBIAINAAsLIAAgBHJFBEBBACEEQQIgBXQiAEEAIABrciAJcSIARQ0DIABBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2akECdEG4CmooAgAhAAsgAEUNAQsDQCAAKAIEQXhxIAhrIgEgA0khAiABIAMgAhshAyAAIAQgAhshBCAAKAIQIgEEfyABBSAAKAIUCyIADQALCyAERQ0AIANBkAgoAgAgCGtPDQAgBCAIaiIGIARNDQEgBCgCGCEFIAQgBCgCDCIBRwRAIAQoAggiAEGYCCgCAEkaIAAgATYCDCABIAA2AggMCgsgBEEUaiICKAIAIgBFBEAgBCgCECIARQ0EIARBEGohAgsDQCACIQcgACIBQRRqIgIoAgAiAA0AIAFBEGohAiABKAIQIgANAAsgB0EANgIADAkLIAhBkAgoAgAiAk0EQEGcCCgCACEDAkAgAiAIayIBQRBPBEBBkAggATYCAEGcCCADIAhqIgA2AgAgACABQQFyNgIEIAIgA2ogATYCACADIAhBA3I2AgQMAQtBnAhBADYCAEGQCEEANgIAIAMgAkEDcjYCBCACIANqIgAgACgCBEEBcjYCBAsgA0EIaiEADAsLIAhBlAgoAgAiBkkEQEGUCCAGIAhrIgE2AgBBoAhBoAgoAgAiAiAIaiIANgIAIAAgAUEBcjYCBCACIAhBA3I2AgQgAkEIaiEADAsLQQAhACAIQS9qIgkCf0HgCygCAARAQegLKAIADAELQewLQn83AgBB5AtCgKCAgICABDcCAEHgCyAMQQxqQXBxQdiq1aoFczYCAEH0C0EANgIAQcQLQQA2AgBBgCALIgFqIgVBACABayIHcSICIAhNDQpBwAsoAgAiBARAQbgLKAIAIgMgAmoiASADTQ0LIAEgBEsNCwtBxAstAABBBHENBQJAAkBBoAgoAgAiAwRAQcgLIQADQCADIAAoAgAiAU8EQCABIAAoAgRqIANLDQMLIAAoAggiAA0ACwtBABABIgFBf0YNBiACIQVB5AsoAgAiA0EBayIAIAFxBEAgAiABayAAIAFqQQAgA2txaiEFCyAFIAhNDQYgBUH+////B0sNBkHACygCACIEBEBBuAsoAgAiAyAFaiIAIANNDQcgACAESw0HCyAFEAEiACABRw0BDAgLIAUgBmsgB3EiBUH+////B0sNBSAFEAEiASAAKAIAIAAoAgRqRg0EIAEhAAsCQCAAQX9GDQAgCEEwaiAFTQ0AQegLKAIAIgEgCSAFa2pBACABa3EiAUH+////B0sEQCAAIQEMCAsgARABQX9HBEAgASAFaiEFIAAhAQwIC0EAIAVrEAEaDAULIAAiAUF/Rw0GDAQLAAtBACEEDAcLQQAhAQwFCyABQX9HDQILQcQLQcQLKAIAQQRyNgIACyACQf7///8HSw0BIAIQASEBQQAQASEAIAFBf0YNASAAQX9GDQEgACABTQ0BIAAgAWsiBSAIQShqTQ0BC0G4C0G4CygCACAFaiIANgIAQbwLKAIAIABJBEBBvAsgADYCAAsCQAJAAkBBoAgoAgAiBwRAQcgLIQADQCABIAAoAgAiAyAAKAIEIgJqRg0CIAAoAggiAA0ACwwCC0GYCCgCACIAQQAgACABTRtFBEBBmAggATYCAAtBACEAQcwLIAU2AgBByAsgATYCAEGoCEF/NgIAQawIQeALKAIANgIAQdQLQQA2AgADQCAAQQN0IgNBuAhqIANBsAhqIgI2AgAgA0G8CGogAjYCACAAQQFqIgBBIEcNAAtBlAggBUEoayIDQXggAWtBB3FBACABQQhqQQdxGyIAayICNgIAQaAIIAAgAWoiADYCACAAIAJBAXI2AgQgASADakEoNgIEQaQIQfALKAIANgIADAILIAAtAAxBCHENACADIAdLDQAgASAHTQ0AIAAgAiAFajYCBEGgCCAHQXggB2tBB3FBACAHQQhqQQdxGyIAaiICNgIAQZQIQZQIKAIAIAVqIgEgAGsiADYCACACIABBAXI2AgQgASAHakEoNgIEQaQIQfALKAIANgIADAELQZgIKAIAIAFLBEBBmAggATYCAAsgASAFaiECQcgLIQACQAJAAkACQAJAAkADQCACIAAoAgBHBEAgACgCCCIADQEMAgsLIAAtAAxBCHFFDQELQcgLIQADQCAHIAAoAgAiAk8EQCACIAAoAgRqIgQgB0sNAwsgACgCCCEADAALAAsgACABNgIAIAAgACgCBCAFajYCBCABQXggAWtBB3FBACABQQhqQQdxG2oiCSAIQQNyNgIEIAJBeCACa0EHcUEAIAJBCGpBB3EbaiIFIAggCWoiBmshAiAFIAdGBEBBoAggBjYCAEGUCEGUCCgCACACaiIANgIAIAYgAEEBcjYCBAwDCyAFQZwIKAIARgRAQZwIIAY2AgBBkAhBkAgoAgAgAmoiADYCACAGIABBAXI2AgQgACAGaiAANgIADAMLIAUoAgQiAEEDcUEBRgRAIABBeHEhBwJAIABB/wFNBEAgBSgCCCIDIABBA3YiAEEDdEGwCGpGGiADIAUoAgwiAUYEQEGICEGICCgCAEF+IAB3cTYCAAwCCyADIAE2AgwgASADNgIIDAELIAUoAhghCAJAIAUgBSgCDCIBRwRAIAUoAggiACABNgIMIAEgADYCCAwBCwJAIAVBFGoiACgCACIDDQAgBUEQaiIAKAIAIgMNAEEAIQEMAQsDQCAAIQQgAyIBQRRqIgAoAgAiAw0AIAFBEGohACABKAIQIgMNAAsgBEEANgIACyAIRQ0AAkAgBSAFKAIcIgNBAnRBuApqIgAoAgBGBEAgACABNgIAIAENAUGMCEGMCCgCAEF+IAN3cTYCAAwCCyAIQRBBFCAIKAIQIAVGG2ogATYCACABRQ0BCyABIAg2AhggBSgCECIABEAgASAANgIQIAAgATYCGAsgBSgCFCIARQ0AIAEgADYCFCAAIAE2AhgLIAUgB2ohBSACIAdqIQILIAUgBSgCBEF+cTYCBCAGIAJBAXI2AgQgAiAGaiACNgIAIAJB/wFNBEAgAkEDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwDC0EfIQAgAkH///8HTQRAIAJBCHYiACAAQYD+P2pBEHZBCHEiA3QiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASADciAAcmsiAEEBdCACIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQQCQEGMCCgCACIDQQEgAHQiAXFFBEBBjAggASADcjYCACAEIAY2AgAgBiAENgIYDAELIAJBAEEZIABBAXZrIABBH0YbdCEAIAQoAgAhAQNAIAEiAygCBEF4cSACRg0DIABBHXYhASAAQQF0IQAgAyABQQRxaiIEKAIQIgENAAsgBCAGNgIQIAYgAzYCGAsgBiAGNgIMIAYgBjYCCAwCC0GUCCAFQShrIgNBeCABa0EHcUEAIAFBCGpBB3EbIgBrIgI2AgBBoAggACABaiIANgIAIAAgAkEBcjYCBCABIANqQSg2AgRBpAhB8AsoAgA2AgAgByAEQScgBGtBB3FBACAEQSdrQQdxG2pBL2siACAAIAdBEGpJGyICQRs2AgQgAkHQCykCADcCECACQcgLKQIANwIIQdALIAJBCGo2AgBBzAsgBTYCAEHICyABNgIAQdQLQQA2AgAgAkEYaiEAA0AgAEEHNgIEIABBCGohASAAQQRqIQAgASAESQ0ACyACIAdGDQMgAiACKAIEQX5xNgIEIAcgAiAHayIEQQFyNgIEIAIgBDYCACAEQf8BTQRAIARBA3YiAEEDdEGwCGohAgJ/QYgIKAIAIgFBASAAdCIAcUUEQEGICCAAIAFyNgIAIAIMAQsgAigCCAshACACIAc2AgggACAHNgIMIAcgAjYCDCAHIAA2AggMBAtBHyEAIAdCADcCECAEQf///wdNBEAgBEEIdiIAIABBgP4/akEQdkEIcSICdCIAIABBgOAfakEQdkEEcSIBdCIAIABBgIAPakEQdkECcSIAdEEPdiABIAJyIAByayIAQQF0IAQgAEEVanZBAXFyQRxqIQALIAcgADYCHCAAQQJ0QbgKaiEDAkBBjAgoAgAiAkEBIAB0IgFxRQRAQYwIIAEgAnI2AgAgAyAHNgIAIAcgAzYCGAwBCyAEQQBBGSAAQQF2ayAAQR9GG3QhACADKAIAIQEDQCABIgIoAgRBeHEgBEYNBCAAQR12IQEgAEEBdCEAIAIgAUEEcWoiAygCECIBDQALIAMgBzYCECAHIAI2AhgLIAcgBzYCDCAHIAc2AggMAwsgAygCCCIAIAY2AgwgAyAGNgIIIAZBADYCGCAGIAM2AgwgBiAANgIICyAJQQhqIQAMBQsgAigCCCIAIAc2AgwgAiAHNgIIIAdBADYCGCAHIAI2AgwgByAANgIIC0GUCCgCACIAIAhNDQBBlAggACAIayIBNgIAQaAIQaAIKAIAIgIgCGoiADYCACAAIAFBAXI2AgQgAiAIQQNyNgIEIAJBCGohAAwDC0GECEEwNgIAQQAhAAwCCwJAIAVFDQACQCAEKAIcIgJBAnRBuApqIgAoAgAgBEYEQCAAIAE2AgAgAQ0BQYwIIAlBfiACd3EiCTYCAAwCCyAFQRBBFCAFKAIQIARGG2ogATYCACABRQ0BCyABIAU2AhggBCgCECIABEAgASAANgIQIAAgATYCGAsgBCgCFCIARQ0AIAEgADYCFCAAIAE2AhgLAkAgA0EPTQRAIAQgAyAIaiIAQQNyNgIEIAAgBGoiACAAKAIEQQFyNgIEDAELIAQgCEEDcjYCBCAGIANBAXI2AgQgAyAGaiADNgIAIANB/wFNBEAgA0EDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwBC0EfIQAgA0H///8HTQRAIANBCHYiACAAQYD+P2pBEHZBCHEiAnQiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASACciAAcmsiAEEBdCADIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQICQAJAIAlBASAAdCIBcUUEQEGMCCABIAlyNgIAIAIgBjYCACAGIAI2AhgMAQsgA0EAQRkgAEEBdmsgAEEfRht0IQAgAigCACEIA0AgCCIBKAIEQXhxIANGDQIgAEEddiECIABBAXQhACABIAJBBHFqIgIoAhAiCA0ACyACIAY2AhAgBiABNgIYCyAGIAY2AgwgBiAGNgIIDAELIAEoAggiACAGNgIMIAEgBjYCCCAGQQA2AhggBiABNgIMIAYgADYCCAsgBEEIaiEADAELAkAgC0UNAAJAIAEoAhwiAkECdEG4CmoiACgCACABRgRAIAAgBDYCACAEDQFBjAggBkF+IAJ3cTYCAAwCCyALQRBBFCALKAIQIAFGG2ogBDYCACAERQ0BCyAEIAs2AhggASgCECIABEAgBCAANgIQIAAgBDYCGAsgASgCFCIARQ0AIAQgADYCFCAAIAQ2AhgLAkAgA0EPTQRAIAEgAyAIaiIAQQNyNgIEIAAgAWoiACAAKAIEQQFyNgIEDAELIAEgCEEDcjYCBCAJIANBAXI2AgQgAyAJaiADNgIAIAoEQCAKQQN2IgBBA3RBsAhqIQRBnAgoAgAhAgJ/QQEgAHQiACAFcUUEQEGICCAAIAVyNgIAIAQMAQsgBCgCCAshACAEIAI2AgggACACNgIMIAIgBDYCDCACIAA2AggLQZwIIAk2AgBBkAggAzYCAAsgAUEIaiEACyAMQRBqJAAgAAsQACMAIABrQXBxIgAkACAACwYAIAAkAAsEACMAC4AJAgh/BH4jAEGQAWsiBiQAIAYgBS0AA0EYdEGAgIAYcSAFLwAAIAUtAAJBEHRycjYCACAGIAUoAANBAnZBg/7/H3E2AgQgBiAFKAAGQQR2Qf+B/x9xNgIIIAYgBSgACUEGdkH//8AfcTYCDCAFLwANIQggBS0ADyEJIAZCADcCFCAGQgA3AhwgBkEANgIkIAYgCCAJQRB0QYCAPHFyNgIQIAYgBSgAEDYCKCAGIAUoABQ2AiwgBiAFKAAYNgIwIAUoABwhBSAGQQA6AEwgBkEANgI4IAYgBTYCNCAGIAEgAhAEIAQEQCAGIAMgBBAECyAGKAI4IgEEQCAGQTxqIgIgAWpBAToAACABQQFqQQ9NBEAgASAGakE9aiEEAkBBDyABayIDRQ0AIAMgBGoiAUEBa0EAOgAAIARBADoAACADQQNJDQAgAUECa0EAOgAAIARBADoAASABQQNrQQA6AAAgBEEAOgACIANBB0kNACABQQRrQQA6AAAgBEEAOgADIANBCUkNACAEQQAgBGtBA3EiAWoiBEEANgIAIAQgAyABa0F8cSIBaiIDQQRrQQA2AgAgAUEJSQ0AIARBADYCCCAEQQA2AgQgA0EIa0EANgIAIANBDGtBADYCACABQRlJDQAgBEEANgIYIARBADYCFCAEQQA2AhAgBEEANgIMIANBEGtBADYCACADQRRrQQA2AgAgA0EYa0EANgIAIANBHGtBADYCACABIARBBHFBGHIiAWsiA0EgSQ0AIAEgBGohAQNAIAFCADcDGCABQgA3AxAgAUIANwMIIAFCADcDACABQSBqIQEgA0EgayIDQR9LDQALCwsgBkEBOgBMIAYgAkEQEAILIAY1AjQhECAGNQIwIREgBjUCLCEOIAAgBjUCKCAGKAIkIAYoAiAgBigCHCAGKAIYIgNBGnZqIgJBGnZqIgFBGnZqIgtBgICAYHIgAUH///8fcSINIAJB////H3EiCCAGKAIUIAtBGnZBBWxqIgFB////H3EiCUEFaiIFQRp2IANB////H3EgAUEadmoiA2oiAUEadmoiAkEadmoiBEEadmoiDEEfdSIHIANxIAEgDEEfdkEBayIDQf///x9xIgpxciIBQRp0IAUgCnEgByAJcXJyrXwiDzwAACAAIA9CGIg8AAMgACAPQhCIPAACIAAgD0IIiDwAASAAIA4gByAIcSACIApxciICQRR0IAFBBnZyrXwgD0IgiHwiDjwABCAAIA5CGIg8AAcgACAOQhCIPAAGIAAgDkIIiDwABSAAIBEgByANcSAEIApxciIBQQ50IAJBDHZyrXwgDkIgiHwiDjwACCAAIA5CGIg8AAsgACAOQhCIPAAKIAAgDkIIiDwACSAAIBAgAyAMcSAHIAtxckEIdCABQRJ2cq18IA5CIIh8Ig48AAwgACAOQhiIPAAPIAAgDkIQiDwADiAAIA5CCIg8AA0gBkIANwIwIAZCADcCKCAGQgA3AiAgBkIANwIYIAZCADcCECAGQgA3AgggBkIANwIAIAZBkAFqJAALpwwBB38CQCAARQ0AIABBCGsiAyAAQQRrKAIAIgFBeHEiAGohBQJAIAFBAXENACABQQNxRQ0BIAMgAygCACIBayIDQZgIKAIASQ0BIAAgAWohACADQZwIKAIARwRAIAFB/wFNBEAgAygCCCICIAFBA3YiBEEDdEGwCGpGGiACIAMoAgwiAUYEQEGICEGICCgCAEF+IAR3cTYCAAwDCyACIAE2AgwgASACNgIIDAILIAMoAhghBgJAIAMgAygCDCIBRwRAIAMoAggiAiABNgIMIAEgAjYCCAwBCwJAIANBFGoiAigCACIEDQAgA0EQaiICKAIAIgQNAEEAIQEMAQsDQCACIQcgBCIBQRRqIgIoAgAiBA0AIAFBEGohAiABKAIQIgQNAAsgB0EANgIACyAGRQ0BAkAgAyADKAIcIgJBAnRBuApqIgQoAgBGBEAgBCABNgIAIAENAUGMCEGMCCgCAEF+IAJ3cTYCAAwDCyAGQRBBFCAGKAIQIANGG2ogATYCACABRQ0CCyABIAY2AhggAygCECICBEAgASACNgIQIAIgATYCGAsgAygCFCICRQ0BIAEgAjYCFCACIAE2AhgMAQsgBSgCBCIBQQNxQQNHDQBBkAggADYCACAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAA8LIAMgBU8NACAFKAIEIgFBAXFFDQACQCABQQJxRQRAIAVBoAgoAgBGBEBBoAggAzYCAEGUCEGUCCgCACAAaiIANgIAIAMgAEEBcjYCBCADQZwIKAIARw0DQZAIQQA2AgBBnAhBADYCAA8LIAVBnAgoAgBGBEBBnAggAzYCAEGQCEGQCCgCACAAaiIANgIAIAMgAEEBcjYCBCAAIANqIAA2AgAPCyABQXhxIABqIQACQCABQf8BTQRAIAUoAggiAiABQQN2IgRBA3RBsAhqRhogAiAFKAIMIgFGBEBBiAhBiAgoAgBBfiAEd3E2AgAMAgsgAiABNgIMIAEgAjYCCAwBCyAFKAIYIQYCQCAFIAUoAgwiAUcEQCAFKAIIIgJBmAgoAgBJGiACIAE2AgwgASACNgIIDAELAkAgBUEUaiICKAIAIgQNACAFQRBqIgIoAgAiBA0AQQAhAQwBCwNAIAIhByAEIgFBFGoiAigCACIEDQAgAUEQaiECIAEoAhAiBA0ACyAHQQA2AgALIAZFDQACQCAFIAUoAhwiAkECdEG4CmoiBCgCAEYEQCAEIAE2AgAgAQ0BQYwIQYwIKAIAQX4gAndxNgIADAILIAZBEEEUIAYoAhAgBUYbaiABNgIAIAFFDQELIAEgBjYCGCAFKAIQIgIEQCABIAI2AhAgAiABNgIYCyAFKAIUIgJFDQAgASACNgIUIAIgATYCGAsgAyAAQQFyNgIEIAAgA2ogADYCACADQZwIKAIARw0BQZAIIAA2AgAPCyAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAAsgAEH/AU0EQCAAQQN2IgFBA3RBsAhqIQACf0GICCgCACICQQEgAXQiAXFFBEBBiAggASACcjYCACAADAELIAAoAggLIQIgACADNgIIIAIgAzYCDCADIAA2AgwgAyACNgIIDwtBHyECIANCADcCECAAQf///wdNBEAgAEEIdiIBIAFBgP4/akEQdkEIcSIBdCICIAJBgOAfakEQdkEEcSICdCIEIARBgIAPakEQdkECcSIEdEEPdiABIAJyIARyayIBQQF0IAAgAUEVanZBAXFyQRxqIQILIAMgAjYCHCACQQJ0QbgKaiEBAkACQAJAQYwIKAIAIgRBASACdCIHcUUEQEGMCCAEIAdyNgIAIAEgAzYCACADIAE2AhgMAQsgAEEAQRkgAkEBdmsgAkEfRht0IQIgASgCACEBA0AgASIEKAIEQXhxIABGDQIgAkEddiEBIAJBAXQhAiAEIAFBBHFqIgdBEGooAgAiAQ0ACyAHIAM2AhAgAyAENgIYCyADIAM2AgwgAyADNgIIDAELIAQoAggiACADNgIMIAQgAzYCCCADQQA2AhggAyAENgIMIAMgADYCCAtBqAhBqAgoAgBBAWsiAEF/IAAbNgIACwsLCQEAQYEICwIGUA=="; - if (!W.startsWith(V)) { - var na = W; - W = b.locateFile ? b.locateFile(na, B) : B + na; - } - function pa() { - var a = W; - try { - if (a == W && J) return new Uint8Array(J); - var c = H(a); - if (c) return c; - if (E) return E(a); - throw "both async and sync fetching of the wasm failed"; - } catch (d) { - K(d); - } - } - function qa() { - if (!J && (x || y)) { - if ("function" === typeof fetch && !W.startsWith("file://")) return fetch(W, { credentials: "same-origin" }).then(function(a) { - if (!a.ok) throw "failed to load wasm binary file at '" + W + "'"; - return a.arrayBuffer(); - }).catch(function() { - return pa(); - }); - if (D) return new Promise(function(a, c) { - D(W, function(d) { - a(new Uint8Array(d)); - }, c); - }); - } - return Promise.resolve().then(function() { - return pa(); - }); - } - function X(a) { - for (; 0 < a.length; ) { - var c = a.shift(); - if ("function" == typeof c) c(b); - else { - var d = c.m; - "number" === typeof d ? void 0 === c.l ? R.get(d)() : R.get(d)(c.l) : d(void 0 === c.l ? null : c.l); - } - } - } - var ba = false, ra = "function" === typeof atob ? atob : function(a) { - var c = "", d = 0; - a = a.replace(/[^A-Za-z0-9\+\/=]/g, ""); - do { - var e = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a.charAt(d++)); - var f = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a.charAt(d++)); - var l = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a.charAt(d++)); - var A = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a.charAt(d++)); - e = e << 2 | f >> 4; - f = (f & 15) << 4 | l >> 2; - var t = (l & 3) << 6 | A; - c += String.fromCharCode(e); - 64 !== l && (c += String.fromCharCode(f)); - 64 !== A && (c += String.fromCharCode(t)); - } while (d < a.length); - return c; - }; - function H(a) { - if (a.startsWith(V)) { - a = a.slice(V.length); - if ("boolean" === typeof z && z) { - var c = Buffer.from(a, "base64"); - c = new Uint8Array(c.buffer, c.byteOffset, c.byteLength); - } else try { - var d = ra(a), e = new Uint8Array(d.length); - for (a = 0; a < d.length; ++a) e[a] = d.charCodeAt(a); - c = e; - } catch (f) { - throw Error("Converting base64 string to bytes failed."); - } - return c; - } - } - var sa = { a: function(a) { - var c = P.length; - a >>>= 0; - if (2147483648 < a) return false; - for (var d = 1; 4 >= d; d *= 2) { - var e = c * (1 + 0.2 / d); - e = Math.min(e, a + 100663296); - e = Math.max(a, e); - 0 < e % 65536 && (e += 65536 - e % 65536); - a: { - try { - L.grow(Math.min(2147483648, e) - ha.byteLength + 65535 >>> 16); - ia(); - var f = 1; - break a; - } catch (l) { - } - f = void 0; - } - if (f) return true; - } - return false; - } }; - (function() { - function a(f) { - b.asm = f.exports; - L = b.asm.b; - ia(); - R = b.asm.j; - ka.unshift(b.asm.c); - S--; - b.monitorRunDependencies && b.monitorRunDependencies(S); - 0 == S && (null !== T && (clearInterval(T), T = null), U && (f = U, U = null, f())); - } - function c(f) { - a(f.instance); - } - function d(f) { - return qa().then(function(l) { - return WebAssembly.instantiate(l, e); - }).then(f, function(l) { - I("failed to asynchronously prepare wasm: " + l); - K(l); - }); - } - var e = { a: sa }; - S++; - b.monitorRunDependencies && b.monitorRunDependencies(S); - if (b.instantiateWasm) try { - return b.instantiateWasm( - e, - a - ); - } catch (f) { - return I("Module.instantiateWasm callback failed with error: " + f), false; - } - (function() { - return J || "function" !== typeof WebAssembly.instantiateStreaming || W.startsWith(V) || W.startsWith("file://") || "function" !== typeof fetch ? d(c) : fetch(W, { credentials: "same-origin" }).then(function(f) { - return WebAssembly.instantiateStreaming(f, e).then(c, function(l) { - I("wasm streaming compile failed: " + l); - I("falling back to ArrayBuffer instantiation"); - return d(c); - }); - }); - })().catch(r); - return {}; - })(); - b.___wasm_call_ctors = function() { - return (b.___wasm_call_ctors = b.asm.c).apply(null, arguments); - }; - b._poly1305_auth = function() { - return (b._poly1305_auth = b.asm.d).apply(null, arguments); - }; - var da = b.stackSave = function() { - return (da = b.stackSave = b.asm.e).apply(null, arguments); - }, fa = b.stackRestore = function() { - return (fa = b.stackRestore = b.asm.f).apply(null, arguments); - }, O = b.stackAlloc = function() { - return (O = b.stackAlloc = b.asm.g).apply(null, arguments); - }; - b._malloc = function() { - return (b._malloc = b.asm.h).apply(null, arguments); - }; - b._free = function() { - return (b._free = b.asm.i).apply(null, arguments); - }; - b.cwrap = function(a, c, d, e) { - d = d || []; - var f = d.every(function(l) { - return "number" === l; - }); - return "string" !== c && f && !e ? N(a) : function() { - return ca(a, c, d, arguments); - }; - }; - var Y; - U = function ta() { - Y || Z(); - Y || (U = ta); - }; - function Z() { - function a() { - if (!Y && (Y = true, b.calledRun = true, !M)) { - X(ka); - q(b); - if (b.onRuntimeInitialized) b.onRuntimeInitialized(); - if (b.postRun) for ("function" == typeof b.postRun && (b.postRun = [b.postRun]); b.postRun.length; ) { - var c = b.postRun.shift(); - la.unshift(c); - } - X(la); - } - } - if (!(0 < S)) { - if (b.preRun) for ("function" == typeof b.preRun && (b.preRun = [b.preRun]); b.preRun.length; ) ma(); - X(ja); - 0 < S || (b.setStatus ? (b.setStatus("Running..."), setTimeout(function() { - setTimeout(function() { - b.setStatus(""); - }, 1); - a(); - }, 1)) : a()); - } - } - b.run = Z; - if (b.preInit) for ("function" == typeof b.preInit && (b.preInit = [b.preInit]); 0 < b.preInit.length; ) b.preInit.pop()(); - Z(); - return createPoly13052.ready; - }); - })(); - if (typeof exports2 === "object" && typeof module2 === "object") - module2.exports = createPoly1305; - else if (typeof define === "function" && define["amd"]) - define([], function() { - return createPoly1305; - }); - else if (typeof exports2 === "object") - exports2["createPoly1305"] = createPoly1305; - } -}); - -// node_modules/ssh2/lib/protocol/crypto.js -var require_crypto = __commonJS({ - "node_modules/ssh2/lib/protocol/crypto.js"(exports2, module2) { - "use strict"; - var { - createCipheriv, - createDecipheriv, - createHmac, - randomFillSync, - timingSafeEqual - } = require("crypto"); - var { readUInt32BE, writeUInt32BE } = require_utils4(); - var FastBuffer = Buffer[Symbol.species]; - var MAX_SEQNO = 2 ** 32 - 1; - var EMPTY_BUFFER = Buffer.alloc(0); - var BUF_INT = Buffer.alloc(4); - var DISCARD_CACHE = /* @__PURE__ */ new Map(); - var MAX_PACKET_SIZE = 35e3; - var binding; - var AESGCMCipher; - var ChaChaPolyCipher; - var GenericCipher; - var AESGCMDecipher; - var ChaChaPolyDecipher; - var GenericDecipher; - try { - binding = require_sshcrypto(); - ({ - AESGCMCipher, - ChaChaPolyCipher, - GenericCipher, - AESGCMDecipher, - ChaChaPolyDecipher, - GenericDecipher - } = binding); - } catch { - } - var CIPHER_STREAM = 1 << 0; - var CIPHER_INFO = (() => { - function info8(sslName, blockLen, keyLen, ivLen, authLen, discardLen, flags) { - return { - sslName, - blockLen, - keyLen, - ivLen: ivLen !== 0 || flags & CIPHER_STREAM ? ivLen : blockLen, - authLen, - discardLen, - stream: !!(flags & CIPHER_STREAM) - }; - } - return { - "chacha20-poly1305@openssh.com": info8("chacha20", 8, 64, 0, 16, 0, CIPHER_STREAM), - "aes128-gcm": info8("aes-128-gcm", 16, 16, 12, 16, 0, CIPHER_STREAM), - "aes256-gcm": info8("aes-256-gcm", 16, 32, 12, 16, 0, CIPHER_STREAM), - "aes128-gcm@openssh.com": info8("aes-128-gcm", 16, 16, 12, 16, 0, CIPHER_STREAM), - "aes256-gcm@openssh.com": info8("aes-256-gcm", 16, 32, 12, 16, 0, CIPHER_STREAM), - "aes128-cbc": info8("aes-128-cbc", 16, 16, 0, 0, 0, 0), - "aes192-cbc": info8("aes-192-cbc", 16, 24, 0, 0, 0, 0), - "aes256-cbc": info8("aes-256-cbc", 16, 32, 0, 0, 0, 0), - "rijndael-cbc@lysator.liu.se": info8("aes-256-cbc", 16, 32, 0, 0, 0, 0), - "3des-cbc": info8("des-ede3-cbc", 8, 24, 0, 0, 0, 0), - "blowfish-cbc": info8("bf-cbc", 8, 16, 0, 0, 0, 0), - "idea-cbc": info8("idea-cbc", 8, 16, 0, 0, 0, 0), - "cast128-cbc": info8("cast-cbc", 8, 16, 0, 0, 0, 0), - "aes128-ctr": info8("aes-128-ctr", 16, 16, 16, 0, 0, CIPHER_STREAM), - "aes192-ctr": info8("aes-192-ctr", 16, 24, 16, 0, 0, CIPHER_STREAM), - "aes256-ctr": info8("aes-256-ctr", 16, 32, 16, 0, 0, CIPHER_STREAM), - "3des-ctr": info8("des-ede3", 8, 24, 8, 0, 0, CIPHER_STREAM), - "blowfish-ctr": info8("bf-ecb", 8, 16, 8, 0, 0, CIPHER_STREAM), - "cast128-ctr": info8("cast5-ecb", 8, 16, 8, 0, 0, CIPHER_STREAM), - /* The "arcfour128" algorithm is the RC4 cipher, as described in - [SCHNEIER], using a 128-bit key. The first 1536 bytes of keystream - generated by the cipher MUST be discarded, and the first byte of the - first encrypted packet MUST be encrypted using the 1537th byte of - keystream. - - -- http://tools.ietf.org/html/rfc4345#section-4 */ - "arcfour": info8("rc4", 8, 16, 0, 0, 1536, CIPHER_STREAM), - "arcfour128": info8("rc4", 8, 16, 0, 0, 1536, CIPHER_STREAM), - "arcfour256": info8("rc4", 8, 32, 0, 0, 1536, CIPHER_STREAM), - "arcfour512": info8("rc4", 8, 64, 0, 0, 1536, CIPHER_STREAM) - }; - })(); - var MAC_INFO = (() => { - function info8(sslName, len, actualLen, isETM) { - return { - sslName, - len, - actualLen, - isETM - }; - } - return { - "hmac-md5": info8("md5", 16, 16, false), - "hmac-md5-96": info8("md5", 16, 12, false), - "hmac-ripemd160": info8("ripemd160", 20, 20, false), - "hmac-sha1": info8("sha1", 20, 20, false), - "hmac-sha1-etm@openssh.com": info8("sha1", 20, 20, true), - "hmac-sha1-96": info8("sha1", 20, 12, false), - "hmac-sha2-256": info8("sha256", 32, 32, false), - "hmac-sha2-256-etm@openssh.com": info8("sha256", 32, 32, true), - "hmac-sha2-256-96": info8("sha256", 32, 12, false), - "hmac-sha2-512": info8("sha512", 64, 64, false), - "hmac-sha2-512-etm@openssh.com": info8("sha512", 64, 64, true), - "hmac-sha2-512-96": info8("sha512", 64, 12, false) - }; - })(); - var NullCipher = class { - constructor(seqno, onWrite) { - this.outSeqno = seqno; - this._onWrite = onWrite; - this._dead = false; - } - free() { - this._dead = true; - } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 8 - (pktLen & 8 - 1); - if (padLen < 4) - padLen += 8; - pktLen += padLen; - const packet = Buffer.allocUnsafe(pktLen); - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - randomFillSync(packet, 5 + payloadLen, padLen); - return packet; - } - encrypt(packet) { - if (this._dead) - return; - this._onWrite(packet); - this.outSeqno = this.outSeqno + 1 >>> 0; - } - }; - var POLY1305_ZEROS = Buffer.alloc(32); - var POLY1305_OUT_COMPUTE = Buffer.alloc(16); - var POLY1305_WASM_MODULE; - var POLY1305_RESULT_MALLOC; - var poly1305_auth; - var ChaChaPolyCipherNative = class { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._encKeyMain = enc.cipherKey.slice(0, 32); - this._encKeyPktLen = enc.cipherKey.slice(32); - this._dead = false; - } - free() { - this._dead = true; - } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 8 - (pktLen - 4 & 8 - 1); - if (padLen < 4) - padLen += 8; - pktLen += padLen; - const packet = Buffer.allocUnsafe(pktLen); - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - randomFillSync(packet, 5 + payloadLen, padLen); - return packet; - } - encrypt(packet) { - if (this._dead) - return; - POLY1305_OUT_COMPUTE[0] = 0; - writeUInt32BE(POLY1305_OUT_COMPUTE, this.outSeqno, 12); - const polyKey = createCipheriv("chacha20", this._encKeyMain, POLY1305_OUT_COMPUTE).update(POLY1305_ZEROS); - const pktLenEnc = createCipheriv("chacha20", this._encKeyPktLen, POLY1305_OUT_COMPUTE).update(packet.slice(0, 4)); - this._onWrite(pktLenEnc); - POLY1305_OUT_COMPUTE[0] = 1; - const payloadEnc = createCipheriv("chacha20", this._encKeyMain, POLY1305_OUT_COMPUTE).update(packet.slice(4)); - this._onWrite(payloadEnc); - poly1305_auth( - POLY1305_RESULT_MALLOC, - pktLenEnc, - pktLenEnc.length, - payloadEnc, - payloadEnc.length, - polyKey - ); - const mac = Buffer.allocUnsafe(16); - mac.set( - new Uint8Array( - POLY1305_WASM_MODULE.HEAPU8.buffer, - POLY1305_RESULT_MALLOC, - 16 - ), - 0 - ); - this._onWrite(mac); - this.outSeqno = this.outSeqno + 1 >>> 0; - } - }; - var ChaChaPolyCipherBinding = class { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._instance = new ChaChaPolyCipher(enc.cipherKey); - this._dead = false; - } - free() { - this._dead = true; - this._instance.free(); - } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 8 - (pktLen - 4 & 8 - 1); - if (padLen < 4) - padLen += 8; - pktLen += padLen; - const packet = Buffer.allocUnsafe( - pktLen + 16 - /* MAC */ - ); - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - randomFillSync(packet, 5 + payloadLen, padLen); - return packet; - } - encrypt(packet) { - if (this._dead) - return; - this._instance.encrypt(packet, this.outSeqno); - this._onWrite(packet); - this.outSeqno = this.outSeqno + 1 >>> 0; - } - }; - var AESGCMCipherNative = class { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._encSSLName = enc.cipherInfo.sslName; - this._encKey = enc.cipherKey; - this._encIV = enc.cipherIV; - this._dead = false; - } - free() { - this._dead = true; - } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 16 - (pktLen - 4 & 16 - 1); - if (padLen < 4) - padLen += 16; - pktLen += padLen; - const packet = Buffer.allocUnsafe(pktLen); - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - randomFillSync(packet, 5 + payloadLen, padLen); - return packet; - } - encrypt(packet) { - if (this._dead) - return; - const cipher = createCipheriv(this._encSSLName, this._encKey, this._encIV); - cipher.setAutoPadding(false); - const lenData = packet.slice(0, 4); - cipher.setAAD(lenData); - this._onWrite(lenData); - const encrypted = cipher.update(packet.slice(4)); - this._onWrite(encrypted); - const final = cipher.final(); - if (final.length) - this._onWrite(final); - const tag = cipher.getAuthTag(); - this._onWrite(tag); - ivIncrement(this._encIV); - this.outSeqno = this.outSeqno + 1 >>> 0; - } - }; - var AESGCMCipherBinding = class { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._instance = new AESGCMCipher( - enc.cipherInfo.sslName, - enc.cipherKey, - enc.cipherIV - ); - this._dead = false; - } - free() { - this._dead = true; - this._instance.free(); - } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 16 - (pktLen - 4 & 16 - 1); - if (padLen < 4) - padLen += 16; - pktLen += padLen; - const packet = Buffer.allocUnsafe( - pktLen + 16 - /* authTag */ - ); - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - randomFillSync(packet, 5 + payloadLen, padLen); - return packet; - } - encrypt(packet) { - if (this._dead) - return; - this._instance.encrypt(packet); - this._onWrite(packet); - this.outSeqno = this.outSeqno + 1 >>> 0; - } - }; - var GenericCipherNative = class { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._encBlockLen = enc.cipherInfo.blockLen; - this._cipherInstance = createCipheriv( - enc.cipherInfo.sslName, - enc.cipherKey, - enc.cipherIV - ); - this._macSSLName = enc.macInfo.sslName; - this._macKey = enc.macKey; - this._macActualLen = enc.macInfo.actualLen; - this._macETM = enc.macInfo.isETM; - this._aadLen = this._macETM ? 4 : 0; - this._dead = false; - const discardLen = enc.cipherInfo.discardLen; - if (discardLen) { - let discard = DISCARD_CACHE.get(discardLen); - if (discard === void 0) { - discard = Buffer.alloc(discardLen); - DISCARD_CACHE.set(discardLen, discard); - } - this._cipherInstance.update(discard); - } - } - free() { - this._dead = true; - } - allocPacket(payloadLen) { - const blockLen = this._encBlockLen; - let pktLen = 4 + 1 + payloadLen; - let padLen = blockLen - (pktLen - this._aadLen & blockLen - 1); - if (padLen < 4) - padLen += blockLen; - pktLen += padLen; - const packet = Buffer.allocUnsafe(pktLen); - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - randomFillSync(packet, 5 + payloadLen, padLen); - return packet; - } - encrypt(packet) { - if (this._dead) - return; - let mac; - if (this._macETM) { - const lenBytes = new Uint8Array(packet.buffer, packet.byteOffset, 4); - const encrypted = this._cipherInstance.update( - new Uint8Array( - packet.buffer, - packet.byteOffset + 4, - packet.length - 4 - ) - ); - this._onWrite(lenBytes); - this._onWrite(encrypted); - mac = createHmac(this._macSSLName, this._macKey); - writeUInt32BE(BUF_INT, this.outSeqno, 0); - mac.update(BUF_INT); - mac.update(lenBytes); - mac.update(encrypted); - } else { - const encrypted = this._cipherInstance.update(packet); - this._onWrite(encrypted); - mac = createHmac(this._macSSLName, this._macKey); - writeUInt32BE(BUF_INT, this.outSeqno, 0); - mac.update(BUF_INT); - mac.update(packet); - } - let digest = mac.digest(); - if (digest.length > this._macActualLen) - digest = digest.slice(0, this._macActualLen); - this._onWrite(digest); - this.outSeqno = this.outSeqno + 1 >>> 0; - } - }; - var GenericCipherBinding = class { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._encBlockLen = enc.cipherInfo.blockLen; - this._macLen = enc.macInfo.len; - this._macActualLen = enc.macInfo.actualLen; - this._aadLen = enc.macInfo.isETM ? 4 : 0; - this._instance = new GenericCipher( - enc.cipherInfo.sslName, - enc.cipherKey, - enc.cipherIV, - enc.macInfo.sslName, - enc.macKey, - enc.macInfo.isETM - ); - this._dead = false; - } - free() { - this._dead = true; - this._instance.free(); - } - allocPacket(payloadLen) { - const blockLen = this._encBlockLen; - let pktLen = 4 + 1 + payloadLen; - let padLen = blockLen - (pktLen - this._aadLen & blockLen - 1); - if (padLen < 4) - padLen += blockLen; - pktLen += padLen; - const packet = Buffer.allocUnsafe(pktLen + this._macLen); - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - randomFillSync(packet, 5 + payloadLen, padLen); - return packet; - } - encrypt(packet) { - if (this._dead) - return; - this._instance.encrypt(packet, this.outSeqno); - if (this._macActualLen < this._macLen) { - packet = new FastBuffer( - packet.buffer, - packet.byteOffset, - packet.length - (this._macLen - this._macActualLen) - ); - } - this._onWrite(packet); - this.outSeqno = this.outSeqno + 1 >>> 0; - } - }; - var NullDecipher = class { - constructor(seqno, onPayload) { - this.inSeqno = seqno; - this._onPayload = onPayload; - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._packetPos = 0; - } - free() { - } - decrypt(data, p, dataLen) { - while (p < dataLen) { - if (this._lenBytes < 4) { - let nb = Math.min(4 - this._lenBytes, dataLen - p); - this._lenBytes += nb; - while (nb--) - this._len = (this._len << 8) + data[p++]; - if (this._lenBytes < 4) - return; - if (this._len > MAX_PACKET_SIZE || this._len < 8 || (4 + this._len & 7) !== 0) { - throw new Error("Bad packet length"); - } - if (p >= dataLen) - return; - } - if (this._packetPos < this._len) { - const nb = Math.min(this._len - this._packetPos, dataLen - p); - let chunk; - if (p !== 0 || nb !== dataLen) - chunk = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - chunk = data; - if (nb === this._len) { - this._packet = chunk; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(chunk, this._packetPos); - } - p += nb; - this._packetPos += nb; - if (this._packetPos < this._len) - return; - } - const payload = !this._packet ? EMPTY_BUFFER : new FastBuffer( - this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - this._packet[0] - 1 - ); - this.inSeqno = this.inSeqno + 1 >>> 0; - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._packetPos = 0; - { - const ret = this._onPayload(payload); - if (ret !== void 0) - return ret === false ? p : ret; - } - } - } - }; - var ChaChaPolyDecipherNative = class { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._decKeyMain = dec.decipherKey.slice(0, 32); - this._decKeyPktLen = dec.decipherKey.slice(32); - this._len = 0; - this._lenBuf = Buffer.alloc(4); - this._lenPos = 0; - this._packet = null; - this._pktLen = 0; - this._mac = Buffer.allocUnsafe(16); - this._calcMac = Buffer.allocUnsafe(16); - this._macPos = 0; - } - free() { - } - decrypt(data, p, dataLen) { - while (p < dataLen) { - if (this._lenPos < 4) { - let nb = Math.min(4 - this._lenPos, dataLen - p); - while (nb--) - this._lenBuf[this._lenPos++] = data[p++]; - if (this._lenPos < 4) - return; - POLY1305_OUT_COMPUTE[0] = 0; - writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12); - const decLenBytes = createDecipheriv("chacha20", this._decKeyPktLen, POLY1305_OUT_COMPUTE).update(this._lenBuf); - this._len = readUInt32BE(decLenBytes, 0); - if (this._len > MAX_PACKET_SIZE || this._len < 8 || (this._len & 7) !== 0) { - throw new Error("Bad packet length"); - } - } - if (this._pktLen < this._len) { - if (p >= dataLen) - return; - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (nb === this._len) { - this._packet = encrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(encrypted, this._pktLen); - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } - { - const nb = Math.min(16 - this._macPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - this._mac.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._macPos - ); - } else { - this._mac.set(data, this._macPos); - } - p += nb; - this._macPos += nb; - if (this._macPos < 16) - return; - } - POLY1305_OUT_COMPUTE[0] = 0; - writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12); - const polyKey = createCipheriv("chacha20", this._decKeyMain, POLY1305_OUT_COMPUTE).update(POLY1305_ZEROS); - poly1305_auth( - POLY1305_RESULT_MALLOC, - this._lenBuf, - 4, - this._packet, - this._packet.length, - polyKey - ); - this._calcMac.set( - new Uint8Array( - POLY1305_WASM_MODULE.HEAPU8.buffer, - POLY1305_RESULT_MALLOC, - 16 - ), - 0 - ); - if (!timingSafeEqual(this._calcMac, this._mac)) - throw new Error("Invalid MAC"); - POLY1305_OUT_COMPUTE[0] = 1; - const packet = createDecipheriv("chacha20", this._decKeyMain, POLY1305_OUT_COMPUTE).update(this._packet); - const payload = new FastBuffer( - packet.buffer, - packet.byteOffset + 1, - packet.length - packet[0] - 1 - ); - this.inSeqno = this.inSeqno + 1 >>> 0; - this._len = 0; - this._lenPos = 0; - this._packet = null; - this._pktLen = 0; - this._macPos = 0; - { - const ret = this._onPayload(payload); - if (ret !== void 0) - return ret === false ? p : ret; - } - } - } - }; - var ChaChaPolyDecipherBinding = class { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._instance = new ChaChaPolyDecipher(dec.decipherKey); - this._len = 0; - this._lenBuf = Buffer.alloc(4); - this._lenPos = 0; - this._packet = null; - this._pktLen = 0; - this._mac = Buffer.allocUnsafe(16); - this._macPos = 0; - } - free() { - this._instance.free(); - } - decrypt(data, p, dataLen) { - while (p < dataLen) { - if (this._lenPos < 4) { - let nb = Math.min(4 - this._lenPos, dataLen - p); - while (nb--) - this._lenBuf[this._lenPos++] = data[p++]; - if (this._lenPos < 4) - return; - this._len = this._instance.decryptLen(this._lenBuf, this.inSeqno); - if (this._len > MAX_PACKET_SIZE || this._len < 8 || (this._len & 7) !== 0) { - throw new Error("Bad packet length"); - } - if (p >= dataLen) - return; - } - if (this._pktLen < this._len) { - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (nb === this._len) { - this._packet = encrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(encrypted, this._pktLen); - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } - { - const nb = Math.min(16 - this._macPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - this._mac.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._macPos - ); - } else { - this._mac.set(data, this._macPos); - } - p += nb; - this._macPos += nb; - if (this._macPos < 16) - return; - } - this._instance.decrypt(this._packet, this._mac, this.inSeqno); - const payload = new FastBuffer( - this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - this._packet[0] - 1 - ); - this.inSeqno = this.inSeqno + 1 >>> 0; - this._len = 0; - this._lenPos = 0; - this._packet = null; - this._pktLen = 0; - this._macPos = 0; - { - const ret = this._onPayload(payload); - if (ret !== void 0) - return ret === false ? p : ret; - } - } - } - }; - var AESGCMDecipherNative = class { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._decipherInstance = null; - this._decipherSSLName = dec.decipherInfo.sslName; - this._decipherKey = dec.decipherKey; - this._decipherIV = dec.decipherIV; - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._packetPos = 0; - this._pktLen = 0; - this._tag = Buffer.allocUnsafe(16); - this._tagPos = 0; - } - free() { - } - decrypt(data, p, dataLen) { - while (p < dataLen) { - if (this._lenBytes < 4) { - let nb = Math.min(4 - this._lenBytes, dataLen - p); - this._lenBytes += nb; - while (nb--) - this._len = (this._len << 8) + data[p++]; - if (this._lenBytes < 4) - return; - if (this._len + 20 > MAX_PACKET_SIZE || this._len < 16 || (this._len & 15) !== 0) { - throw new Error("Bad packet length"); - } - this._decipherInstance = createDecipheriv( - this._decipherSSLName, - this._decipherKey, - this._decipherIV - ); - this._decipherInstance.setAutoPadding(false); - this._decipherInstance.setAAD(intToBytes(this._len)); - } - if (this._pktLen < this._len) { - if (p >= dataLen) - return; - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let decrypted; - if (p !== 0 || nb !== dataLen) { - decrypted = this._decipherInstance.update( - new Uint8Array(data.buffer, data.byteOffset + p, nb) - ); - } else { - decrypted = this._decipherInstance.update(data); - } - if (decrypted.length) { - if (nb === this._len) { - this._packet = decrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(decrypted, this._packetPos); - } - this._packetPos += decrypted.length; - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } - { - const nb = Math.min(16 - this._tagPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - this._tag.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._tagPos - ); - } else { - this._tag.set(data, this._tagPos); - } - p += nb; - this._tagPos += nb; - if (this._tagPos < 16) - return; - } - { - this._decipherInstance.setAuthTag(this._tag); - const decrypted = this._decipherInstance.final(); - if (decrypted.length) { - if (this._packet) - this._packet.set(decrypted, this._packetPos); - else - this._packet = decrypted; - } - } - const payload = !this._packet ? EMPTY_BUFFER : new FastBuffer( - this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - this._packet[0] - 1 - ); - this.inSeqno = this.inSeqno + 1 >>> 0; - ivIncrement(this._decipherIV); - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._packetPos = 0; - this._pktLen = 0; - this._tagPos = 0; - { - const ret = this._onPayload(payload); - if (ret !== void 0) - return ret === false ? p : ret; - } - } - } - }; - var AESGCMDecipherBinding = class { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._instance = new AESGCMDecipher( - dec.decipherInfo.sslName, - dec.decipherKey, - dec.decipherIV - ); - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._pktLen = 0; - this._tag = Buffer.allocUnsafe(16); - this._tagPos = 0; - } - free() { - } - decrypt(data, p, dataLen) { - while (p < dataLen) { - if (this._lenBytes < 4) { - let nb = Math.min(4 - this._lenBytes, dataLen - p); - this._lenBytes += nb; - while (nb--) - this._len = (this._len << 8) + data[p++]; - if (this._lenBytes < 4) - return; - if (this._len + 20 > MAX_PACKET_SIZE || this._len < 16 || (this._len & 15) !== 0) { - throw new Error(`Bad packet length: ${this._len}`); - } - } - if (this._pktLen < this._len) { - if (p >= dataLen) - return; - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (nb === this._len) { - this._packet = encrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(encrypted, this._pktLen); - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } - { - const nb = Math.min(16 - this._tagPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - this._tag.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._tagPos - ); - } else { - this._tag.set(data, this._tagPos); - } - p += nb; - this._tagPos += nb; - if (this._tagPos < 16) - return; - } - this._instance.decrypt(this._packet, this._len, this._tag); - const payload = new FastBuffer( - this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - this._packet[0] - 1 - ); - this.inSeqno = this.inSeqno + 1 >>> 0; - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._pktLen = 0; - this._tagPos = 0; - { - const ret = this._onPayload(payload); - if (ret !== void 0) - return ret === false ? p : ret; - } - } - } - }; - var GenericDecipherNative = class { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._decipherInstance = createDecipheriv( - dec.decipherInfo.sslName, - dec.decipherKey, - dec.decipherIV - ); - this._decipherInstance.setAutoPadding(false); - this._block = Buffer.allocUnsafe( - dec.macInfo.isETM ? 4 : dec.decipherInfo.blockLen - ); - this._blockSize = dec.decipherInfo.blockLen; - this._blockPos = 0; - this._len = 0; - this._packet = null; - this._packetPos = 0; - this._pktLen = 0; - this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen); - this._macPos = 0; - this._macSSLName = dec.macInfo.sslName; - this._macKey = dec.macKey; - this._macActualLen = dec.macInfo.actualLen; - this._macETM = dec.macInfo.isETM; - this._macInstance = null; - const discardLen = dec.decipherInfo.discardLen; - if (discardLen) { - let discard = DISCARD_CACHE.get(discardLen); - if (discard === void 0) { - discard = Buffer.alloc(discardLen); - DISCARD_CACHE.set(discardLen, discard); - } - this._decipherInstance.update(discard); - } - } - free() { - } - decrypt(data, p, dataLen) { - while (p < dataLen) { - if (this._blockPos < this._block.length) { - const nb = Math.min(this._block.length - this._blockPos, dataLen - p); - if (p !== 0 || nb !== dataLen || nb < data.length) { - this._block.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._blockPos - ); - } else { - this._block.set(data, this._blockPos); - } - p += nb; - this._blockPos += nb; - if (this._blockPos < this._block.length) - return; - let decrypted; - let need; - if (this._macETM) { - this._len = need = readUInt32BE(this._block, 0); - } else { - decrypted = this._decipherInstance.update(this._block); - this._len = readUInt32BE(decrypted, 0); - need = 4 + this._len - this._blockSize; - } - if (this._len > MAX_PACKET_SIZE || this._len < 5 || (need & this._blockSize - 1) !== 0) { - throw new Error("Bad packet length"); - } - this._macInstance = createHmac(this._macSSLName, this._macKey); - writeUInt32BE(BUF_INT, this.inSeqno, 0); - this._macInstance.update(BUF_INT); - if (this._macETM) { - this._macInstance.update(this._block); - } else { - this._macInstance.update(new Uint8Array( - decrypted.buffer, - decrypted.byteOffset, - 4 - )); - this._pktLen = decrypted.length - 4; - this._packetPos = this._pktLen; - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set( - new Uint8Array( - decrypted.buffer, - decrypted.byteOffset + 4, - this._packetPos - ), - 0 - ); - } - if (p >= dataLen) - return; - } - if (this._pktLen < this._len) { - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (this._macETM) - this._macInstance.update(encrypted); - const decrypted = this._decipherInstance.update(encrypted); - if (decrypted.length) { - if (nb === this._len) { - this._packet = decrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(decrypted, this._packetPos); - } - this._packetPos += decrypted.length; - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } - { - const nb = Math.min(this._macActualLen - this._macPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - this._mac.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._macPos - ); - } else { - this._mac.set(data, this._macPos); - } - p += nb; - this._macPos += nb; - if (this._macPos < this._macActualLen) - return; - } - if (!this._macETM) - this._macInstance.update(this._packet); - let calculated = this._macInstance.digest(); - if (this._macActualLen < calculated.length) { - calculated = new Uint8Array( - calculated.buffer, - calculated.byteOffset, - this._macActualLen - ); - } - if (!timingSafeEquals(calculated, this._mac)) - throw new Error("Invalid MAC"); - const payload = new FastBuffer( - this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - this._packet[0] - 1 - ); - this.inSeqno = this.inSeqno + 1 >>> 0; - this._blockPos = 0; - this._len = 0; - this._packet = null; - this._packetPos = 0; - this._pktLen = 0; - this._macPos = 0; - this._macInstance = null; - { - const ret = this._onPayload(payload); - if (ret !== void 0) - return ret === false ? p : ret; - } - } - } - }; - var GenericDecipherBinding = class { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._instance = new GenericDecipher( - dec.decipherInfo.sslName, - dec.decipherKey, - dec.decipherIV, - dec.macInfo.sslName, - dec.macKey, - dec.macInfo.isETM, - dec.macInfo.actualLen - ); - this._block = Buffer.allocUnsafe( - dec.macInfo.isETM || dec.decipherInfo.stream ? 4 : dec.decipherInfo.blockLen - ); - this._blockPos = 0; - this._len = 0; - this._packet = null; - this._pktLen = 0; - this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen); - this._macPos = 0; - this._macActualLen = dec.macInfo.actualLen; - this._macETM = dec.macInfo.isETM; - } - free() { - this._instance.free(); - } - decrypt(data, p, dataLen) { - while (p < dataLen) { - if (this._blockPos < this._block.length) { - const nb = Math.min(this._block.length - this._blockPos, dataLen - p); - if (p !== 0 || nb !== dataLen || nb < data.length) { - this._block.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._blockPos - ); - } else { - this._block.set(data, this._blockPos); - } - p += nb; - this._blockPos += nb; - if (this._blockPos < this._block.length) - return; - let need; - if (this._macETM) { - this._len = need = readUInt32BE(this._block, 0); - } else { - this._instance.decryptBlock(this._block); - this._len = readUInt32BE(this._block, 0); - need = 4 + this._len - this._block.length; - } - if (this._len > MAX_PACKET_SIZE || this._len < 5 || (need & this._block.length - 1) !== 0) { - throw new Error("Bad packet length"); - } - if (!this._macETM) { - this._pktLen = this._block.length - 4; - if (this._pktLen) { - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set( - new Uint8Array( - this._block.buffer, - this._block.byteOffset + 4, - this._pktLen - ), - 0 - ); - } - } - if (p >= dataLen) - return; - } - if (this._pktLen < this._len) { - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (nb === this._len) { - this._packet = encrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(encrypted, this._pktLen); - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } - { - const nb = Math.min(this._macActualLen - this._macPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - this._mac.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._macPos - ); - } else { - this._mac.set(data, this._macPos); - } - p += nb; - this._macPos += nb; - if (this._macPos < this._macActualLen) - return; - } - this._instance.decrypt( - this._packet, - this.inSeqno, - this._block, - this._mac - ); - const payload = new FastBuffer( - this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - this._packet[0] - 1 - ); - this.inSeqno = this.inSeqno + 1 >>> 0; - this._blockPos = 0; - this._len = 0; - this._packet = null; - this._pktLen = 0; - this._macPos = 0; - this._macInstance = null; - { - const ret = this._onPayload(payload); - if (ret !== void 0) - return ret === false ? p : ret; - } - } - } - }; - function ivIncrement(iv) { - ++iv[11] >>> 8 && ++iv[10] >>> 8 && ++iv[9] >>> 8 && ++iv[8] >>> 8 && ++iv[7] >>> 8 && ++iv[6] >>> 8 && ++iv[5] >>> 8 && ++iv[4] >>> 8; - } - var intToBytes = (() => { - const ret = Buffer.alloc(4); - return (n) => { - ret[0] = n >>> 24; - ret[1] = n >>> 16; - ret[2] = n >>> 8; - ret[3] = n; - return ret; - }; - })(); - function timingSafeEquals(a, b) { - if (a.length !== b.length) { - timingSafeEqual(a, a); - return false; - } - return timingSafeEqual(a, b); - } - function createCipher(config) { - if (typeof config !== "object" || config === null) - throw new Error("Invalid config"); - if (typeof config.outbound !== "object" || config.outbound === null) - throw new Error("Invalid outbound"); - const outbound = config.outbound; - if (typeof outbound.onWrite !== "function") - throw new Error("Invalid outbound.onWrite"); - if (typeof outbound.cipherInfo !== "object" || outbound.cipherInfo === null) - throw new Error("Invalid outbound.cipherInfo"); - if (!Buffer.isBuffer(outbound.cipherKey) || outbound.cipherKey.length !== outbound.cipherInfo.keyLen) { - throw new Error("Invalid outbound.cipherKey"); - } - if (outbound.cipherInfo.ivLen && (!Buffer.isBuffer(outbound.cipherIV) || outbound.cipherIV.length !== outbound.cipherInfo.ivLen)) { - throw new Error("Invalid outbound.cipherIV"); - } - if (typeof outbound.seqno !== "number" || outbound.seqno < 0 || outbound.seqno > MAX_SEQNO) { - throw new Error("Invalid outbound.seqno"); - } - const forceNative = !!outbound.forceNative; - switch (outbound.cipherInfo.sslName) { - case "aes-128-gcm": - case "aes-256-gcm": - return AESGCMCipher && !forceNative ? new AESGCMCipherBinding(config) : new AESGCMCipherNative(config); - case "chacha20": - return ChaChaPolyCipher && !forceNative ? new ChaChaPolyCipherBinding(config) : new ChaChaPolyCipherNative(config); - default: { - if (typeof outbound.macInfo !== "object" || outbound.macInfo === null) - throw new Error("Invalid outbound.macInfo"); - if (!Buffer.isBuffer(outbound.macKey) || outbound.macKey.length !== outbound.macInfo.len) { - throw new Error("Invalid outbound.macKey"); - } - return GenericCipher && !forceNative ? new GenericCipherBinding(config) : new GenericCipherNative(config); - } - } - } - function createDecipher(config) { - if (typeof config !== "object" || config === null) - throw new Error("Invalid config"); - if (typeof config.inbound !== "object" || config.inbound === null) - throw new Error("Invalid inbound"); - const inbound = config.inbound; - if (typeof inbound.onPayload !== "function") - throw new Error("Invalid inbound.onPayload"); - if (typeof inbound.decipherInfo !== "object" || inbound.decipherInfo === null) { - throw new Error("Invalid inbound.decipherInfo"); - } - if (!Buffer.isBuffer(inbound.decipherKey) || inbound.decipherKey.length !== inbound.decipherInfo.keyLen) { - throw new Error("Invalid inbound.decipherKey"); - } - if (inbound.decipherInfo.ivLen && (!Buffer.isBuffer(inbound.decipherIV) || inbound.decipherIV.length !== inbound.decipherInfo.ivLen)) { - throw new Error("Invalid inbound.decipherIV"); - } - if (typeof inbound.seqno !== "number" || inbound.seqno < 0 || inbound.seqno > MAX_SEQNO) { - throw new Error("Invalid inbound.seqno"); - } - const forceNative = !!inbound.forceNative; - switch (inbound.decipherInfo.sslName) { - case "aes-128-gcm": - case "aes-256-gcm": - return AESGCMDecipher && !forceNative ? new AESGCMDecipherBinding(config) : new AESGCMDecipherNative(config); - case "chacha20": - return ChaChaPolyDecipher && !forceNative ? new ChaChaPolyDecipherBinding(config) : new ChaChaPolyDecipherNative(config); - default: { - if (typeof inbound.macInfo !== "object" || inbound.macInfo === null) - throw new Error("Invalid inbound.macInfo"); - if (!Buffer.isBuffer(inbound.macKey) || inbound.macKey.length !== inbound.macInfo.len) { - throw new Error("Invalid inbound.macKey"); - } - return GenericDecipher && !forceNative ? new GenericDecipherBinding(config) : new GenericDecipherNative(config); - } - } - } - module2.exports = { - CIPHER_INFO, - MAC_INFO, - bindingAvailable: !!binding, - init: (() => { - return new Promise(async (resolve, reject) => { - try { - POLY1305_WASM_MODULE = await require_poly1305()(); - POLY1305_RESULT_MALLOC = POLY1305_WASM_MODULE._malloc(16); - poly1305_auth = POLY1305_WASM_MODULE.cwrap( - "poly1305_auth", - null, - ["number", "array", "number", "array", "number", "array"] - ); - } catch (ex) { - return reject(ex); - } - resolve(); - }); - })(), - NullCipher, - createCipher, - NullDecipher, - createDecipher - }; - } -}); - -// node_modules/ssh2/lib/protocol/keyParser.js -var require_keyParser = __commonJS({ - "node_modules/ssh2/lib/protocol/keyParser.js"(exports2, module2) { - "use strict"; - var { - createDecipheriv, - createECDH, - createHash, - createHmac, - createSign, - createVerify, - getCiphers, - sign: sign_, - verify: verify_ - } = require("crypto"); - var supportedOpenSSLCiphers = getCiphers(); - var { Ber } = require_lib3(); - var bcrypt_pbkdf = require_bcrypt_pbkdf().pbkdf; - var { CIPHER_INFO } = require_crypto(); - var { eddsaSupported, SUPPORTED_CIPHER } = require_constants6(); - var { - bufferSlice, - makeBufferParser, - readString, - readUInt32BE, - writeUInt32BE - } = require_utils4(); - var SYM_HASH_ALGO = /* @__PURE__ */ Symbol("Hash Algorithm"); - var SYM_PRIV_PEM = /* @__PURE__ */ Symbol("Private key PEM"); - var SYM_PUB_PEM = /* @__PURE__ */ Symbol("Public key PEM"); - var SYM_PUB_SSH = /* @__PURE__ */ Symbol("Public key SSH"); - var SYM_DECRYPTED = /* @__PURE__ */ Symbol("Decrypted Key"); - var CIPHER_INFO_OPENSSL = /* @__PURE__ */ Object.create(null); - { - const keys = Object.keys(CIPHER_INFO); - for (let i = 0; i < keys.length; ++i) { - const cipherName = CIPHER_INFO[keys[i]].sslName; - if (!cipherName || CIPHER_INFO_OPENSSL[cipherName]) - continue; - CIPHER_INFO_OPENSSL[cipherName] = CIPHER_INFO[keys[i]]; - } - } - var binaryKeyParser = makeBufferParser(); - function makePEM(type, data) { - data = data.base64Slice(0, data.length); - let formatted = data.replace(/.{64}/g, "$&\n"); - if (data.length & 63) - formatted += "\n"; - return `-----BEGIN ${type} KEY----- -${formatted}-----END ${type} KEY-----`; - } - function combineBuffers(buf1, buf2) { - const result = Buffer.allocUnsafe(buf1.length + buf2.length); - result.set(buf1, 0); - result.set(buf2, buf1.length); - return result; - } - function skipFields(buf, nfields) { - const bufLen = buf.length; - let pos = buf._pos || 0; - for (let i = 0; i < nfields; ++i) { - const left = bufLen - pos; - if (pos >= bufLen || left < 4) - return false; - const len = readUInt32BE(buf, pos); - if (left < 4 + len) - return false; - pos += 4 + len; - } - buf._pos = pos; - return true; - } - function genOpenSSLRSAPub(n, e) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - asnWriter.startSequence(); - asnWriter.writeOID("1.2.840.113549.1.1.1"); - asnWriter.writeNull(); - asnWriter.endSequence(); - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0); - asnWriter.startSequence(); - asnWriter.writeBuffer(n, Ber.Integer); - asnWriter.writeBuffer(e, Ber.Integer); - asnWriter.endSequence(); - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM("PUBLIC", asnWriter.buffer); - } - function genOpenSSHRSAPub(n, e) { - const publicKey = Buffer.allocUnsafe(4 + 7 + 4 + e.length + 4 + n.length); - writeUInt32BE(publicKey, 7, 0); - publicKey.utf8Write("ssh-rsa", 4, 7); - let i = 4 + 7; - writeUInt32BE(publicKey, e.length, i); - publicKey.set(e, i += 4); - writeUInt32BE(publicKey, n.length, i += e.length); - publicKey.set(n, i + 4); - return publicKey; - } - var genOpenSSLRSAPriv = /* @__PURE__ */ (() => { - function genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - asnWriter.writeInt(0, Ber.Integer); - asnWriter.writeBuffer(n, Ber.Integer); - asnWriter.writeBuffer(e, Ber.Integer); - asnWriter.writeBuffer(d, Ber.Integer); - asnWriter.writeBuffer(p, Ber.Integer); - asnWriter.writeBuffer(q, Ber.Integer); - asnWriter.writeBuffer(dmp1, Ber.Integer); - asnWriter.writeBuffer(dmq1, Ber.Integer); - asnWriter.writeBuffer(iqmp, Ber.Integer); - asnWriter.endSequence(); - return asnWriter.buffer; - } - function bigIntFromBuffer(buf) { - return BigInt(`0x${buf.hexSlice(0, buf.length)}`); - } - function bigIntToBuffer(bn) { - let hex = bn.toString(16); - if ((hex.length & 1) !== 0) { - hex = `0${hex}`; - } else { - const sigbit = hex.charCodeAt(0); - if (sigbit === 56 || sigbit === 57 || sigbit >= 97 && sigbit <= 102) { - hex = `00${hex}`; - } - } - return Buffer.from(hex, "hex"); - } - return function genOpenSSLRSAPriv2(n, e, d, iqmp, p, q) { - const bn_d = bigIntFromBuffer(d); - const dmp1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(p) - 1n)); - const dmq1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(q) - 1n)); - return makePEM( - "RSA PRIVATE", - genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp) - ); - }; - })(); - function genOpenSSLDSAPub(p, q, g, y) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - asnWriter.startSequence(); - asnWriter.writeOID("1.2.840.10040.4.1"); - asnWriter.startSequence(); - asnWriter.writeBuffer(p, Ber.Integer); - asnWriter.writeBuffer(q, Ber.Integer); - asnWriter.writeBuffer(g, Ber.Integer); - asnWriter.endSequence(); - asnWriter.endSequence(); - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0); - asnWriter.writeBuffer(y, Ber.Integer); - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM("PUBLIC", asnWriter.buffer); - } - function genOpenSSHDSAPub(p, q, g, y) { - const publicKey = Buffer.allocUnsafe( - 4 + 7 + 4 + p.length + 4 + q.length + 4 + g.length + 4 + y.length - ); - writeUInt32BE(publicKey, 7, 0); - publicKey.utf8Write("ssh-dss", 4, 7); - let i = 4 + 7; - writeUInt32BE(publicKey, p.length, i); - publicKey.set(p, i += 4); - writeUInt32BE(publicKey, q.length, i += p.length); - publicKey.set(q, i += 4); - writeUInt32BE(publicKey, g.length, i += q.length); - publicKey.set(g, i += 4); - writeUInt32BE(publicKey, y.length, i += g.length); - publicKey.set(y, i + 4); - return publicKey; - } - function genOpenSSLDSAPriv(p, q, g, y, x) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - asnWriter.writeInt(0, Ber.Integer); - asnWriter.writeBuffer(p, Ber.Integer); - asnWriter.writeBuffer(q, Ber.Integer); - asnWriter.writeBuffer(g, Ber.Integer); - asnWriter.writeBuffer(y, Ber.Integer); - asnWriter.writeBuffer(x, Ber.Integer); - asnWriter.endSequence(); - return makePEM("DSA PRIVATE", asnWriter.buffer); - } - function genOpenSSLEdPub(pub) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - asnWriter.startSequence(); - asnWriter.writeOID("1.3.101.112"); - asnWriter.endSequence(); - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0); - asnWriter._ensure(pub.length); - asnWriter._buf.set(pub, asnWriter._offset); - asnWriter._offset += pub.length; - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM("PUBLIC", asnWriter.buffer); - } - function genOpenSSHEdPub(pub) { - const publicKey = Buffer.allocUnsafe(4 + 11 + 4 + pub.length); - writeUInt32BE(publicKey, 11, 0); - publicKey.utf8Write("ssh-ed25519", 4, 11); - writeUInt32BE(publicKey, pub.length, 15); - publicKey.set(pub, 19); - return publicKey; - } - function genOpenSSLEdPriv(priv) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - asnWriter.writeInt(0, Ber.Integer); - asnWriter.startSequence(); - asnWriter.writeOID("1.3.101.112"); - asnWriter.endSequence(); - asnWriter.startSequence(Ber.OctetString); - asnWriter.writeBuffer(priv, Ber.OctetString); - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM("PRIVATE", asnWriter.buffer); - } - function genOpenSSLECDSAPub(oid, Q) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - asnWriter.startSequence(); - asnWriter.writeOID("1.2.840.10045.2.1"); - asnWriter.writeOID(oid); - asnWriter.endSequence(); - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0); - asnWriter._ensure(Q.length); - asnWriter._buf.set(Q, asnWriter._offset); - asnWriter._offset += Q.length; - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM("PUBLIC", asnWriter.buffer); - } - function genOpenSSHECDSAPub(oid, Q) { - let curveName; - switch (oid) { - case "1.2.840.10045.3.1.7": - curveName = "nistp256"; - break; - case "1.3.132.0.34": - curveName = "nistp384"; - break; - case "1.3.132.0.35": - curveName = "nistp521"; - break; - default: - return; - } - const publicKey = Buffer.allocUnsafe(4 + 19 + 4 + 8 + 4 + Q.length); - writeUInt32BE(publicKey, 19, 0); - publicKey.utf8Write(`ecdsa-sha2-${curveName}`, 4, 19); - writeUInt32BE(publicKey, 8, 23); - publicKey.utf8Write(curveName, 27, 8); - writeUInt32BE(publicKey, Q.length, 35); - publicKey.set(Q, 39); - return publicKey; - } - function genOpenSSLECDSAPriv(oid, pub, priv) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - asnWriter.writeInt(1, Ber.Integer); - asnWriter.writeBuffer(priv, Ber.OctetString); - asnWriter.startSequence(160); - asnWriter.writeOID(oid); - asnWriter.endSequence(); - asnWriter.startSequence(161); - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0); - asnWriter._ensure(pub.length); - asnWriter._buf.set(pub, asnWriter._offset); - asnWriter._offset += pub.length; - asnWriter.endSequence(); - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM("EC PRIVATE", asnWriter.buffer); - } - function genOpenSSLECDSAPubFromPriv(curveName, priv) { - const tempECDH = createECDH(curveName); - tempECDH.setPrivateKey(priv); - return tempECDH.getPublicKey(); - } - var BaseKey = { - sign: (() => { - if (typeof sign_ === "function") { - return function sign(data, algo) { - const pem = this[SYM_PRIV_PEM]; - if (pem === null) - return new Error("No private key available"); - if (!algo || typeof algo !== "string") - algo = this[SYM_HASH_ALGO]; - try { - return sign_(algo, data, pem); - } catch (ex) { - return ex; - } - }; - } - return function sign(data, algo) { - const pem = this[SYM_PRIV_PEM]; - if (pem === null) - return new Error("No private key available"); - if (!algo || typeof algo !== "string") - algo = this[SYM_HASH_ALGO]; - const signature = createSign(algo); - signature.update(data); - try { - return signature.sign(pem); - } catch (ex) { - return ex; - } - }; - })(), - verify: (() => { - if (typeof verify_ === "function") { - return function verify(data, signature, algo) { - const pem = this[SYM_PUB_PEM]; - if (pem === null) - return new Error("No public key available"); - if (!algo || typeof algo !== "string") - algo = this[SYM_HASH_ALGO]; - try { - return verify_(algo, data, pem, signature); - } catch (ex) { - return ex; - } - }; - } - return function verify(data, signature, algo) { - const pem = this[SYM_PUB_PEM]; - if (pem === null) - return new Error("No public key available"); - if (!algo || typeof algo !== "string") - algo = this[SYM_HASH_ALGO]; - const verifier = createVerify(algo); - verifier.update(data); - try { - return verifier.verify(pem, signature); - } catch (ex) { - return ex; - } - }; - })(), - isPrivateKey: function isPrivateKey() { - return this[SYM_PRIV_PEM] !== null; - }, - getPrivatePEM: function getPrivatePEM() { - return this[SYM_PRIV_PEM]; - }, - getPublicPEM: function getPublicPEM() { - return this[SYM_PUB_PEM]; - }, - getPublicSSH: function getPublicSSH() { - return this[SYM_PUB_SSH]; - }, - equals: function equals(key) { - const parsed = parseKey(key); - if (parsed instanceof Error) - return false; - return this.type === parsed.type && this[SYM_PRIV_PEM] === parsed[SYM_PRIV_PEM] && this[SYM_PUB_PEM] === parsed[SYM_PUB_PEM] && this[SYM_PUB_SSH].equals(parsed[SYM_PUB_SSH]); - } - }; - function OpenSSH_Private(type, comment, privPEM, pubPEM, pubSSH, algo, decrypted) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = privPEM; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = decrypted; - } - OpenSSH_Private.prototype = BaseKey; - { - let parseOpenSSHPrivKeys = function(data, nkeys, decrypted) { - const keys = []; - if (data.length < 8) - return new Error("Malformed OpenSSH private key"); - const check1 = readUInt32BE(data, 0); - const check2 = readUInt32BE(data, 4); - if (check1 !== check2) { - if (decrypted) { - return new Error( - "OpenSSH key integrity check failed -- bad passphrase?" - ); - } - return new Error("OpenSSH key integrity check failed"); - } - data._pos = 8; - let i; - let oid; - for (i = 0; i < nkeys; ++i) { - let algo; - let privPEM; - let pubPEM; - let pubSSH; - const type = readString(data, data._pos, true); - if (type === void 0) - return new Error("Malformed OpenSSH private key"); - switch (type) { - case "ssh-rsa": { - const n = readString(data, data._pos); - if (n === void 0) - return new Error("Malformed OpenSSH private key"); - const e = readString(data, data._pos); - if (e === void 0) - return new Error("Malformed OpenSSH private key"); - const d = readString(data, data._pos); - if (d === void 0) - return new Error("Malformed OpenSSH private key"); - const iqmp = readString(data, data._pos); - if (iqmp === void 0) - return new Error("Malformed OpenSSH private key"); - const p = readString(data, data._pos); - if (p === void 0) - return new Error("Malformed OpenSSH private key"); - const q = readString(data, data._pos); - if (q === void 0) - return new Error("Malformed OpenSSH private key"); - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q); - algo = "sha1"; - break; - } - case "ssh-dss": { - const p = readString(data, data._pos); - if (p === void 0) - return new Error("Malformed OpenSSH private key"); - const q = readString(data, data._pos); - if (q === void 0) - return new Error("Malformed OpenSSH private key"); - const g = readString(data, data._pos); - if (g === void 0) - return new Error("Malformed OpenSSH private key"); - const y = readString(data, data._pos); - if (y === void 0) - return new Error("Malformed OpenSSH private key"); - const x = readString(data, data._pos); - if (x === void 0) - return new Error("Malformed OpenSSH private key"); - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - privPEM = genOpenSSLDSAPriv(p, q, g, y, x); - algo = "sha1"; - break; - } - case "ssh-ed25519": { - if (!eddsaSupported) - return new Error(`Unsupported OpenSSH private key type: ${type}`); - const edpub = readString(data, data._pos); - if (edpub === void 0 || edpub.length !== 32) - return new Error("Malformed OpenSSH private key"); - const edpriv = readString(data, data._pos); - if (edpriv === void 0 || edpriv.length !== 64) - return new Error("Malformed OpenSSH private key"); - pubPEM = genOpenSSLEdPub(edpub); - pubSSH = genOpenSSHEdPub(edpub); - privPEM = genOpenSSLEdPriv(bufferSlice(edpriv, 0, 32)); - algo = null; - break; - } - case "ecdsa-sha2-nistp256": - algo = "sha256"; - oid = "1.2.840.10045.3.1.7"; - // FALLTHROUGH - case "ecdsa-sha2-nistp384": - if (algo === void 0) { - algo = "sha384"; - oid = "1.3.132.0.34"; - } - // FALLTHROUGH - case "ecdsa-sha2-nistp521": { - if (algo === void 0) { - algo = "sha512"; - oid = "1.3.132.0.35"; - } - if (!skipFields(data, 1)) - return new Error("Malformed OpenSSH private key"); - const ecpub = readString(data, data._pos); - if (ecpub === void 0) - return new Error("Malformed OpenSSH private key"); - const ecpriv = readString(data, data._pos); - if (ecpriv === void 0) - return new Error("Malformed OpenSSH private key"); - pubPEM = genOpenSSLECDSAPub(oid, ecpub); - pubSSH = genOpenSSHECDSAPub(oid, ecpub); - privPEM = genOpenSSLECDSAPriv(oid, ecpub, ecpriv); - break; - } - default: - return new Error(`Unsupported OpenSSH private key type: ${type}`); - } - const privComment = readString(data, data._pos, true); - if (privComment === void 0) - return new Error("Malformed OpenSSH private key"); - keys.push( - new OpenSSH_Private( - type, - privComment, - privPEM, - pubPEM, - pubSSH, - algo, - decrypted - ) - ); - } - let cnt = 0; - for (i = data._pos; i < data.length; ++i) { - if (data[i] !== ++cnt % 255) - return new Error("Malformed OpenSSH private key"); - } - return keys; - }; - const regexp = /^-----BEGIN OPENSSH PRIVATE KEY-----(?:\r\n|\n)([\s\S]+)(?:\r\n|\n)-----END OPENSSH PRIVATE KEY-----$/; - OpenSSH_Private.parse = (str, passphrase) => { - const m = regexp.exec(str); - if (m === null) - return null; - let ret; - const data = Buffer.from(m[1], "base64"); - if (data.length < 31) - return new Error("Malformed OpenSSH private key"); - const magic = data.utf8Slice(0, 15); - if (magic !== "openssh-key-v1\0") - return new Error(`Unsupported OpenSSH key magic: ${magic}`); - const cipherName = readString(data, 15, true); - if (cipherName === void 0) - return new Error("Malformed OpenSSH private key"); - if (cipherName !== "none" && SUPPORTED_CIPHER.indexOf(cipherName) === -1) - return new Error(`Unsupported cipher for OpenSSH key: ${cipherName}`); - const kdfName = readString(data, data._pos, true); - if (kdfName === void 0) - return new Error("Malformed OpenSSH private key"); - if (kdfName !== "none") { - if (cipherName === "none") - return new Error("Malformed OpenSSH private key"); - if (kdfName !== "bcrypt") - return new Error(`Unsupported kdf name for OpenSSH key: ${kdfName}`); - if (!passphrase) { - return new Error( - "Encrypted private OpenSSH key detected, but no passphrase given" - ); - } - } else if (cipherName !== "none") { - return new Error("Malformed OpenSSH private key"); - } - let encInfo; - let cipherKey; - let cipherIV; - if (cipherName !== "none") - encInfo = CIPHER_INFO[cipherName]; - const kdfOptions = readString(data, data._pos); - if (kdfOptions === void 0) - return new Error("Malformed OpenSSH private key"); - if (kdfOptions.length) { - switch (kdfName) { - case "none": - return new Error("Malformed OpenSSH private key"); - case "bcrypt": { - const salt = readString(kdfOptions, 0); - if (salt === void 0 || kdfOptions._pos + 4 > kdfOptions.length) - return new Error("Malformed OpenSSH private key"); - const rounds = readUInt32BE(kdfOptions, kdfOptions._pos); - const gen = Buffer.allocUnsafe(encInfo.keyLen + encInfo.ivLen); - const r = bcrypt_pbkdf( - passphrase, - passphrase.length, - salt, - salt.length, - gen, - gen.length, - rounds - ); - if (r !== 0) - return new Error("Failed to generate information to decrypt key"); - cipherKey = bufferSlice(gen, 0, encInfo.keyLen); - cipherIV = bufferSlice(gen, encInfo.keyLen, gen.length); - break; - } - } - } else if (kdfName !== "none") { - return new Error("Malformed OpenSSH private key"); - } - if (data._pos + 3 >= data.length) - return new Error("Malformed OpenSSH private key"); - const keyCount = readUInt32BE(data, data._pos); - data._pos += 4; - if (keyCount > 0) { - for (let i = 0; i < keyCount; ++i) { - const pubData = readString(data, data._pos); - if (pubData === void 0) - return new Error("Malformed OpenSSH private key"); - const type = readString(pubData, 0, true); - if (type === void 0) - return new Error("Malformed OpenSSH private key"); - } - let privBlob = readString(data, data._pos); - if (privBlob === void 0) - return new Error("Malformed OpenSSH private key"); - if (cipherKey !== void 0) { - if (privBlob.length < encInfo.blockLen || privBlob.length % encInfo.blockLen !== 0) { - return new Error("Malformed OpenSSH private key"); - } - try { - const options = { authTagLength: encInfo.authLen }; - const decipher = createDecipheriv( - encInfo.sslName, - cipherKey, - cipherIV, - options - ); - decipher.setAutoPadding(false); - if (encInfo.authLen > 0) { - if (data.length - data._pos < encInfo.authLen) - return new Error("Malformed OpenSSH private key"); - decipher.setAuthTag( - bufferSlice(data, data._pos, data._pos += encInfo.authLen) - ); - } - privBlob = combineBuffers( - decipher.update(privBlob), - decipher.final() - ); - } catch (ex) { - return ex; - } - } - if (data._pos !== data.length) - return new Error("Malformed OpenSSH private key"); - ret = parseOpenSSHPrivKeys(privBlob, keyCount, cipherKey !== void 0); - } else { - ret = []; - } - if (ret instanceof Error) - return ret; - return ret[0]; - }; - } - function OpenSSH_Old_Private(type, comment, privPEM, pubPEM, pubSSH, algo, decrypted) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = privPEM; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = decrypted; - } - OpenSSH_Old_Private.prototype = BaseKey; - { - const regexp = /^-----BEGIN (RSA|DSA|EC) PRIVATE KEY-----(?:\r\n|\n)((?:[^:]+:\s*[\S].*(?:\r\n|\n))*)([\s\S]+)(?:\r\n|\n)-----END (RSA|DSA|EC) PRIVATE KEY-----$/; - OpenSSH_Old_Private.parse = (str, passphrase) => { - const m = regexp.exec(str); - if (m === null) - return null; - let privBlob = Buffer.from(m[3], "base64"); - let headers = m[2]; - let decrypted = false; - if (headers !== void 0) { - headers = headers.split(/\r\n|\n/g); - for (let i = 0; i < headers.length; ++i) { - const header = headers[i]; - let sepIdx = header.indexOf(":"); - if (header.slice(0, sepIdx) === "DEK-Info") { - const val = header.slice(sepIdx + 2); - sepIdx = val.indexOf(","); - if (sepIdx === -1) - continue; - const cipherName = val.slice(0, sepIdx).toLowerCase(); - if (supportedOpenSSLCiphers.indexOf(cipherName) === -1) { - return new Error( - `Cipher (${cipherName}) not supported for encrypted OpenSSH private key` - ); - } - const encInfo = CIPHER_INFO_OPENSSL[cipherName]; - if (!encInfo) { - return new Error( - `Cipher (${cipherName}) not supported for encrypted OpenSSH private key` - ); - } - const cipherIV = Buffer.from(val.slice(sepIdx + 1), "hex"); - if (cipherIV.length !== encInfo.ivLen) - return new Error("Malformed encrypted OpenSSH private key"); - if (!passphrase) { - return new Error( - "Encrypted OpenSSH private key detected, but no passphrase given" - ); - } - const ivSlice = bufferSlice(cipherIV, 0, 8); - let cipherKey = createHash("md5").update(passphrase).update(ivSlice).digest(); - while (cipherKey.length < encInfo.keyLen) { - cipherKey = combineBuffers( - cipherKey, - createHash("md5").update(cipherKey).update(passphrase).update(ivSlice).digest() - ); - } - if (cipherKey.length > encInfo.keyLen) - cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen); - try { - const decipher = createDecipheriv(cipherName, cipherKey, cipherIV); - decipher.setAutoPadding(false); - privBlob = combineBuffers( - decipher.update(privBlob), - decipher.final() - ); - decrypted = true; - } catch (ex) { - return ex; - } - } - } - } - let type; - let privPEM; - let pubPEM; - let pubSSH; - let algo; - let reader; - let errMsg = "Malformed OpenSSH private key"; - if (decrypted) - errMsg += ". Bad passphrase?"; - switch (m[1]) { - case "RSA": - type = "ssh-rsa"; - privPEM = makePEM("RSA PRIVATE", privBlob); - try { - reader = new Ber.Reader(privBlob); - reader.readSequence(); - reader.readInt(); - const n = reader.readString(Ber.Integer, true); - if (n === null) - return new Error(errMsg); - const e = reader.readString(Ber.Integer, true); - if (e === null) - return new Error(errMsg); - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - } catch { - return new Error(errMsg); - } - algo = "sha1"; - break; - case "DSA": - type = "ssh-dss"; - privPEM = makePEM("DSA PRIVATE", privBlob); - try { - reader = new Ber.Reader(privBlob); - reader.readSequence(); - reader.readInt(); - const p = reader.readString(Ber.Integer, true); - if (p === null) - return new Error(errMsg); - const q = reader.readString(Ber.Integer, true); - if (q === null) - return new Error(errMsg); - const g = reader.readString(Ber.Integer, true); - if (g === null) - return new Error(errMsg); - const y = reader.readString(Ber.Integer, true); - if (y === null) - return new Error(errMsg); - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - } catch { - return new Error(errMsg); - } - algo = "sha1"; - break; - case "EC": { - let ecSSLName; - let ecPriv; - let ecOID; - try { - reader = new Ber.Reader(privBlob); - reader.readSequence(); - reader.readInt(); - ecPriv = reader.readString(Ber.OctetString, true); - reader.readByte(); - const offset = reader.readLength(); - if (offset !== null) { - reader._offset = offset; - ecOID = reader.readOID(); - if (ecOID === null) - return new Error(errMsg); - switch (ecOID) { - case "1.2.840.10045.3.1.7": - ecSSLName = "prime256v1"; - type = "ecdsa-sha2-nistp256"; - algo = "sha256"; - break; - case "1.3.132.0.34": - ecSSLName = "secp384r1"; - type = "ecdsa-sha2-nistp384"; - algo = "sha384"; - break; - case "1.3.132.0.35": - ecSSLName = "secp521r1"; - type = "ecdsa-sha2-nistp521"; - algo = "sha512"; - break; - default: - return new Error(`Unsupported private key EC OID: ${ecOID}`); - } - } else { - return new Error(errMsg); - } - } catch { - return new Error(errMsg); - } - privPEM = makePEM("EC PRIVATE", privBlob); - const pubBlob = genOpenSSLECDSAPubFromPriv(ecSSLName, ecPriv); - pubPEM = genOpenSSLECDSAPub(ecOID, pubBlob); - pubSSH = genOpenSSHECDSAPub(ecOID, pubBlob); - break; - } - } - return new OpenSSH_Old_Private( - type, - "", - privPEM, - pubPEM, - pubSSH, - algo, - decrypted - ); - }; - } - function PPK_Private(type, comment, privPEM, pubPEM, pubSSH, algo, decrypted) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = privPEM; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = decrypted; - } - PPK_Private.prototype = BaseKey; - { - const EMPTY_PASSPHRASE = Buffer.alloc(0); - const PPK_IV = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - const PPK_PP1 = Buffer.from([0, 0, 0, 0]); - const PPK_PP2 = Buffer.from([0, 0, 0, 1]); - const regexp = /^PuTTY-User-Key-File-2: (ssh-(?:rsa|dss))\r?\nEncryption: (aes256-cbc|none)\r?\nComment: ([^\r\n]*)\r?\nPublic-Lines: \d+\r?\n([\s\S]+?)\r?\nPrivate-Lines: \d+\r?\n([\s\S]+?)\r?\nPrivate-MAC: ([^\r\n]+)/; - PPK_Private.parse = (str, passphrase) => { - const m = regexp.exec(str); - if (m === null) - return null; - const cipherName = m[2]; - const encrypted = cipherName !== "none"; - if (encrypted && !passphrase) { - return new Error( - "Encrypted PPK private key detected, but no passphrase given" - ); - } - let privBlob = Buffer.from(m[5], "base64"); - if (encrypted) { - const encInfo = CIPHER_INFO[cipherName]; - let cipherKey = combineBuffers( - createHash("sha1").update(PPK_PP1).update(passphrase).digest(), - createHash("sha1").update(PPK_PP2).update(passphrase).digest() - ); - if (cipherKey.length > encInfo.keyLen) - cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen); - try { - const decipher = createDecipheriv(encInfo.sslName, cipherKey, PPK_IV); - decipher.setAutoPadding(false); - privBlob = combineBuffers( - decipher.update(privBlob), - decipher.final() - ); - } catch (ex) { - return ex; - } - } - const type = m[1]; - const comment = m[3]; - const pubBlob = Buffer.from(m[4], "base64"); - const mac = m[6]; - const typeLen = type.length; - const cipherNameLen = cipherName.length; - const commentLen = Buffer.byteLength(comment); - const pubLen = pubBlob.length; - const privLen = privBlob.length; - const macData = Buffer.allocUnsafe(4 + typeLen + 4 + cipherNameLen + 4 + commentLen + 4 + pubLen + 4 + privLen); - let p = 0; - writeUInt32BE(macData, typeLen, p); - macData.utf8Write(type, p += 4, typeLen); - writeUInt32BE(macData, cipherNameLen, p += typeLen); - macData.utf8Write(cipherName, p += 4, cipherNameLen); - writeUInt32BE(macData, commentLen, p += cipherNameLen); - macData.utf8Write(comment, p += 4, commentLen); - writeUInt32BE(macData, pubLen, p += commentLen); - macData.set(pubBlob, p += 4); - writeUInt32BE(macData, privLen, p += pubLen); - macData.set(privBlob, p + 4); - if (!passphrase) - passphrase = EMPTY_PASSPHRASE; - const calcMAC = createHmac( - "sha1", - createHash("sha1").update("putty-private-key-file-mac-key").update(passphrase).digest() - ).update(macData).digest("hex"); - if (calcMAC !== mac) { - if (encrypted) { - return new Error( - "PPK private key integrity check failed -- bad passphrase?" - ); - } - return new Error("PPK private key integrity check failed"); - } - let pubPEM; - let pubSSH; - let privPEM; - pubBlob._pos = 0; - skipFields(pubBlob, 1); - switch (type) { - case "ssh-rsa": { - const e = readString(pubBlob, pubBlob._pos); - if (e === void 0) - return new Error("Malformed PPK public key"); - const n = readString(pubBlob, pubBlob._pos); - if (n === void 0) - return new Error("Malformed PPK public key"); - const d = readString(privBlob, 0); - if (d === void 0) - return new Error("Malformed PPK private key"); - const p2 = readString(privBlob, privBlob._pos); - if (p2 === void 0) - return new Error("Malformed PPK private key"); - const q = readString(privBlob, privBlob._pos); - if (q === void 0) - return new Error("Malformed PPK private key"); - const iqmp = readString(privBlob, privBlob._pos); - if (iqmp === void 0) - return new Error("Malformed PPK private key"); - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p2, q); - break; - } - case "ssh-dss": { - const p2 = readString(pubBlob, pubBlob._pos); - if (p2 === void 0) - return new Error("Malformed PPK public key"); - const q = readString(pubBlob, pubBlob._pos); - if (q === void 0) - return new Error("Malformed PPK public key"); - const g = readString(pubBlob, pubBlob._pos); - if (g === void 0) - return new Error("Malformed PPK public key"); - const y = readString(pubBlob, pubBlob._pos); - if (y === void 0) - return new Error("Malformed PPK public key"); - const x = readString(privBlob, 0); - if (x === void 0) - return new Error("Malformed PPK private key"); - pubPEM = genOpenSSLDSAPub(p2, q, g, y); - pubSSH = genOpenSSHDSAPub(p2, q, g, y); - privPEM = genOpenSSLDSAPriv(p2, q, g, y, x); - break; - } - } - return new PPK_Private( - type, - comment, - privPEM, - pubPEM, - pubSSH, - "sha1", - encrypted - ); - }; - } - function OpenSSH_Public(type, comment, pubPEM, pubSSH, algo) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = null; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = false; - } - OpenSSH_Public.prototype = BaseKey; - { - let regexp; - if (eddsaSupported) - regexp = /^(((?:ssh-(?:rsa|dss|ed25519))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\s+([\S].*)?)$/; - else - regexp = /^(((?:ssh-(?:rsa|dss))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\s+([\S].*)?)$/; - OpenSSH_Public.parse = (str) => { - const m = regexp.exec(str); - if (m === null) - return null; - const fullType = m[1]; - const baseType = m[2]; - const data = Buffer.from(m[3], "base64"); - const comment = m[4] || ""; - const type = readString(data, data._pos, true); - if (type === void 0 || type.indexOf(baseType) !== 0) - return new Error("Malformed OpenSSH public key"); - return parseDER(data, baseType, comment, fullType); - }; - } - function RFC4716_Public(type, comment, pubPEM, pubSSH, algo) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = null; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = false; - } - RFC4716_Public.prototype = BaseKey; - { - const regexp = /^---- BEGIN SSH2 PUBLIC KEY ----(?:\r?\n)((?:.{0,72}\r?\n)+)---- END SSH2 PUBLIC KEY ----$/; - const RE_DATA = /^[A-Z0-9a-z/+=\r\n]+$/; - const RE_HEADER = /^([\x21-\x39\x3B-\x7E]{1,64}): ((?:[^\\]*\\\r?\n)*[^\r\n]+)\r?\n/gm; - const RE_HEADER_ENDS = /\\\r?\n/g; - RFC4716_Public.parse = (str) => { - let m = regexp.exec(str); - if (m === null) - return null; - const body = m[1]; - let dataStart = 0; - let comment = ""; - while (m = RE_HEADER.exec(body)) { - const headerName = m[1]; - const headerValue = m[2].replace(RE_HEADER_ENDS, ""); - if (headerValue.length > 1024) { - RE_HEADER.lastIndex = 0; - return new Error("Malformed RFC4716 public key"); - } - dataStart = RE_HEADER.lastIndex; - if (headerName.toLowerCase() === "comment") { - comment = headerValue; - if (comment.length > 1 && comment.charCodeAt(0) === 34 && comment.charCodeAt(comment.length - 1) === 34) { - comment = comment.slice(1, -1); - } - } - } - let data = body.slice(dataStart); - if (!RE_DATA.test(data)) - return new Error("Malformed RFC4716 public key"); - data = Buffer.from(data, "base64"); - const type = readString(data, 0, true); - if (type === void 0) - return new Error("Malformed RFC4716 public key"); - let pubPEM = null; - let pubSSH = null; - switch (type) { - case "ssh-rsa": { - const e = readString(data, data._pos); - if (e === void 0) - return new Error("Malformed RFC4716 public key"); - const n = readString(data, data._pos); - if (n === void 0) - return new Error("Malformed RFC4716 public key"); - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - break; - } - case "ssh-dss": { - const p = readString(data, data._pos); - if (p === void 0) - return new Error("Malformed RFC4716 public key"); - const q = readString(data, data._pos); - if (q === void 0) - return new Error("Malformed RFC4716 public key"); - const g = readString(data, data._pos); - if (g === void 0) - return new Error("Malformed RFC4716 public key"); - const y = readString(data, data._pos); - if (y === void 0) - return new Error("Malformed RFC4716 public key"); - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - break; - } - default: - return new Error("Malformed RFC4716 public key"); - } - return new RFC4716_Public(type, comment, pubPEM, pubSSH, "sha1"); - }; - } - function parseDER(data, baseType, comment, fullType) { - if (!isSupportedKeyType(baseType)) - return new Error(`Unsupported OpenSSH public key type: ${baseType}`); - let algo; - let oid; - let pubPEM = null; - let pubSSH = null; - switch (baseType) { - case "ssh-rsa": { - const e = readString(data, data._pos || 0); - if (e === void 0) - return new Error("Malformed OpenSSH public key"); - const n = readString(data, data._pos); - if (n === void 0) - return new Error("Malformed OpenSSH public key"); - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - algo = "sha1"; - break; - } - case "ssh-dss": { - const p = readString(data, data._pos || 0); - if (p === void 0) - return new Error("Malformed OpenSSH public key"); - const q = readString(data, data._pos); - if (q === void 0) - return new Error("Malformed OpenSSH public key"); - const g = readString(data, data._pos); - if (g === void 0) - return new Error("Malformed OpenSSH public key"); - const y = readString(data, data._pos); - if (y === void 0) - return new Error("Malformed OpenSSH public key"); - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - algo = "sha1"; - break; - } - case "ssh-ed25519": { - const edpub = readString(data, data._pos || 0); - if (edpub === void 0 || edpub.length !== 32) - return new Error("Malformed OpenSSH public key"); - pubPEM = genOpenSSLEdPub(edpub); - pubSSH = genOpenSSHEdPub(edpub); - algo = null; - break; - } - case "ecdsa-sha2-nistp256": - algo = "sha256"; - oid = "1.2.840.10045.3.1.7"; - // FALLTHROUGH - case "ecdsa-sha2-nistp384": - if (algo === void 0) { - algo = "sha384"; - oid = "1.3.132.0.34"; - } - // FALLTHROUGH - case "ecdsa-sha2-nistp521": { - if (algo === void 0) { - algo = "sha512"; - oid = "1.3.132.0.35"; - } - if (!skipFields(data, 1)) - return new Error("Malformed OpenSSH public key"); - const ecpub = readString(data, data._pos || 0); - if (ecpub === void 0) - return new Error("Malformed OpenSSH public key"); - pubPEM = genOpenSSLECDSAPub(oid, ecpub); - pubSSH = genOpenSSHECDSAPub(oid, ecpub); - break; - } - default: - return new Error(`Unsupported OpenSSH public key type: ${baseType}`); - } - return new OpenSSH_Public(fullType, comment, pubPEM, pubSSH, algo); - } - function isSupportedKeyType(type) { - switch (type) { - case "ssh-rsa": - case "ssh-dss": - case "ecdsa-sha2-nistp256": - case "ecdsa-sha2-nistp384": - case "ecdsa-sha2-nistp521": - return true; - case "ssh-ed25519": - if (eddsaSupported) - return true; - // FALLTHROUGH - default: - return false; - } - } - function isParsedKey(val) { - if (!val) - return false; - return typeof val[SYM_DECRYPTED] === "boolean"; - } - function parseKey(data, passphrase) { - if (isParsedKey(data)) - return data; - let origBuffer; - if (Buffer.isBuffer(data)) { - origBuffer = data; - data = data.utf8Slice(0, data.length).trim(); - } else if (typeof data === "string") { - data = data.trim(); - } else { - return new Error("Key data must be a Buffer or string"); - } - if (passphrase != void 0) { - if (typeof passphrase === "string") - passphrase = Buffer.from(passphrase); - else if (!Buffer.isBuffer(passphrase)) - return new Error("Passphrase must be a string or Buffer when supplied"); - } - let ret; - if ((ret = OpenSSH_Private.parse(data, passphrase)) !== null) - return ret; - if ((ret = OpenSSH_Old_Private.parse(data, passphrase)) !== null) - return ret; - if ((ret = PPK_Private.parse(data, passphrase)) !== null) - return ret; - if ((ret = OpenSSH_Public.parse(data)) !== null) - return ret; - if ((ret = RFC4716_Public.parse(data)) !== null) - return ret; - if (origBuffer) { - binaryKeyParser.init(origBuffer, 0); - const type = binaryKeyParser.readString(true); - if (type !== void 0) { - data = binaryKeyParser.readRaw(); - if (data !== void 0) { - ret = parseDER(data, type, "", type); - if (ret instanceof Error) - ret = null; - } - } - binaryKeyParser.clear(); - } - if (ret) - return ret; - return new Error("Unsupported key format"); - } - module2.exports = { - isParsedKey, - isSupportedKeyType, - parseDERKey: (data, type) => parseDER(data, type, "", type), - parseKey - }; - } -}); - -// node_modules/ssh2/lib/agent.js -var require_agent2 = __commonJS({ - "node_modules/ssh2/lib/agent.js"(exports2, module2) { - "use strict"; - var { Socket } = require("net"); - var { Duplex } = require("stream"); - var { resolve } = require("path"); - var { readFile } = require("fs"); - var { execFile, spawn } = require("child_process"); - var { isParsedKey, parseKey } = require_keyParser(); - var { - makeBufferParser, - readUInt32BE, - writeUInt32BE, - writeUInt32LE - } = require_utils4(); - function once(cb) { - let called = false; - return (...args) => { - if (called) - return; - called = true; - cb(...args); - }; - } - function concat(buf1, buf2) { - const combined = Buffer.allocUnsafe(buf1.length + buf2.length); - buf1.copy(combined, 0); - buf2.copy(combined, buf1.length); - return combined; - } - function noop3() { - } - var EMPTY_BUF = Buffer.alloc(0); - var binaryParser = makeBufferParser(); - var BaseAgent = class { - getIdentities(cb) { - cb(new Error("Missing getIdentities() implementation")); - } - sign(pubKey, data, options, cb) { - if (typeof options === "function") - cb = options; - cb(new Error("Missing sign() implementation")); - } - }; - var OpenSSHAgent = class extends BaseAgent { - constructor(socketPath) { - super(); - this.socketPath = socketPath; - } - getStream(cb) { - cb = once(cb); - const sock = new Socket(); - sock.on("connect", () => { - cb(null, sock); - }); - sock.on("close", onFail).on("end", onFail).on("error", onFail); - sock.connect(this.socketPath); - function onFail() { - try { - sock.destroy(); - } catch { - } - cb(new Error("Failed to connect to agent")); - } - } - getIdentities(cb) { - cb = once(cb); - this.getStream((err, stream2) => { - function onFail(err2) { - if (stream2) { - try { - stream2.destroy(); - } catch { - } - } - if (!err2) - err2 = new Error("Failed to retrieve identities from agent"); - cb(err2); - } - if (err) - return onFail(err); - const protocol = new AgentProtocol(true); - protocol.on("error", onFail); - protocol.pipe(stream2).pipe(protocol); - stream2.on("close", onFail).on("end", onFail).on("error", onFail); - protocol.getIdentities((err2, keys) => { - if (err2) - return onFail(err2); - try { - stream2.destroy(); - } catch { - } - cb(null, keys); - }); - }); - } - sign(pubKey, data, options, cb) { - if (typeof options === "function") { - cb = options; - options = void 0; - } else if (typeof options !== "object" || options === null) { - options = void 0; - } - cb = once(cb); - this.getStream((err, stream2) => { - function onFail(err2) { - if (stream2) { - try { - stream2.destroy(); - } catch { - } - } - if (!err2) - err2 = new Error("Failed to sign data with agent"); - cb(err2); - } - if (err) - return onFail(err); - const protocol = new AgentProtocol(true); - protocol.on("error", onFail); - protocol.pipe(stream2).pipe(protocol); - stream2.on("close", onFail).on("end", onFail).on("error", onFail); - protocol.sign(pubKey, data, options, (err2, sig) => { - if (err2) - return onFail(err2); - try { - stream2.destroy(); - } catch { - } - cb(null, sig); - }); - }); - } - }; - var PageantAgent = (() => { - const RET_ERR_BADARGS = 10; - const RET_ERR_UNAVAILABLE = 11; - const RET_ERR_NOMAP = 12; - const RET_ERR_BINSTDIN = 13; - const RET_ERR_BINSTDOUT = 14; - const RET_ERR_BADLEN = 15; - const EXEPATH = resolve(__dirname, "..", "util/pagent.exe"); - const ERROR = { - [RET_ERR_BADARGS]: new Error("Invalid pagent.exe arguments"), - [RET_ERR_UNAVAILABLE]: new Error("Pageant is not running"), - [RET_ERR_NOMAP]: new Error("pagent.exe could not create an mmap"), - [RET_ERR_BINSTDIN]: new Error("pagent.exe could not set mode for stdin"), - [RET_ERR_BINSTDOUT]: new Error("pagent.exe could not set mode for stdout"), - [RET_ERR_BADLEN]: new Error("pagent.exe did not get expected input payload") - }; - function destroy(stream2) { - stream2.buffer = null; - if (stream2.proc) { - stream2.proc.kill(); - stream2.proc = void 0; - } - } - class PageantSocket extends Duplex { - constructor() { - super(); - this.proc = void 0; - this.buffer = null; - } - _read(n) { - } - _write(data, encoding, cb) { - if (this.buffer === null) { - this.buffer = data; - } else { - const newBuffer = Buffer.allocUnsafe(this.buffer.length + data.length); - this.buffer.copy(newBuffer, 0); - data.copy(newBuffer, this.buffer.length); - this.buffer = newBuffer; - } - if (this.buffer.length < 4) - return cb(); - const len = readUInt32BE(this.buffer, 0); - if (this.buffer.length - 4 < len) - return cb(); - data = this.buffer.slice(0, 4 + len); - if (this.buffer.length > 4 + len) - return cb(new Error("Unexpected multiple agent requests")); - this.buffer = null; - let error3; - const proc = this.proc = spawn(EXEPATH, [data.length]); - proc.stdout.on("data", (data2) => { - this.push(data2); - }); - proc.on("error", (err) => { - error3 = err; - cb(error3); - }); - proc.on("close", (code) => { - this.proc = void 0; - if (!error3) { - if (error3 = ERROR[code]) - return cb(error3); - cb(); - } - }); - proc.stdin.end(data); - } - _final(cb) { - destroy(this); - cb(); - } - _destroy(err, cb) { - destroy(this); - cb(); - } - } - return class PageantAgent extends OpenSSHAgent { - getStream(cb) { - cb(null, new PageantSocket()); - } - }; - })(); - var CygwinAgent = /* @__PURE__ */ (() => { - const RE_CYGWIN_SOCK = /^!(\d+) s ([A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8})/; - return class CygwinAgent extends OpenSSHAgent { - getStream(cb) { - cb = once(cb); - let socketPath = this.socketPath; - let triedCygpath = false; - readFile(socketPath, function readCygsocket(err, data) { - if (err) { - if (triedCygpath) - return cb(new Error("Invalid cygwin unix socket path")); - execFile("cygpath", ["-w", socketPath], (err2, stdout, stderr) => { - if (err2 || stdout.length === 0) - return cb(new Error("Invalid cygwin unix socket path")); - triedCygpath = true; - socketPath = stdout.toString().replace(/[\r\n]/g, ""); - readFile(socketPath, readCygsocket); - }); - return; - } - const m = RE_CYGWIN_SOCK.exec(data.toString("ascii")); - if (!m) - return cb(new Error("Malformed cygwin unix socket file")); - let state; - let bc = 0; - let isRetrying = false; - const inBuf = []; - let sock; - let credsBuf = Buffer.alloc(12); - const port = parseInt(m[1], 10); - const secret = m[2].replace(/-/g, ""); - const secretBuf = Buffer.allocUnsafe(16); - for (let i = 0, j = 0; j < 32; ++i, j += 2) - secretBuf[i] = parseInt(secret.substring(j, j + 2), 16); - for (let i = 0; i < 16; i += 4) - writeUInt32LE(secretBuf, readUInt32BE(secretBuf, i), i); - tryConnect(); - function _onconnect() { - bc = 0; - state = "secret"; - sock.write(secretBuf); - } - function _ondata(data2) { - bc += data2.length; - if (state === "secret") { - if (bc === 16) { - bc = 0; - state = "creds"; - sock.write(credsBuf); - } - return; - } - if (state === "creds") { - if (!isRetrying) - inBuf.push(data2); - if (bc === 12) { - sock.removeListener("connect", _onconnect); - sock.removeListener("data", _ondata); - sock.removeListener("error", onFail); - sock.removeListener("end", onFail); - sock.removeListener("close", onFail); - if (isRetrying) - return cb(null, sock); - isRetrying = true; - credsBuf = Buffer.concat(inBuf); - writeUInt32LE(credsBuf, process.pid, 0); - sock.on("error", () => { - }); - sock.destroy(); - tryConnect(); - } - } - } - function onFail() { - cb(new Error("Problem negotiating cygwin unix socket security")); - } - function tryConnect() { - sock = new Socket(); - sock.on("connect", _onconnect); - sock.on("data", _ondata); - sock.on("error", onFail); - sock.on("end", onFail); - sock.on("close", onFail); - sock.connect(port); - } - }); - } - }; - })(); - var WINDOWS_PIPE_REGEX = /^[/\\][/\\]\.[/\\]pipe[/\\].+/; - function createAgent(path) { - if (process.platform === "win32" && !WINDOWS_PIPE_REGEX.test(path)) { - return path === "pageant" ? new PageantAgent() : new CygwinAgent(path); - } - return new OpenSSHAgent(path); - } - var AgentProtocol = (() => { - const SSH_AGENTC_REQUEST_IDENTITIES = 11; - const SSH_AGENTC_SIGN_REQUEST = 13; - const SSH_AGENT_FAILURE = 5; - const SSH_AGENT_IDENTITIES_ANSWER = 12; - const SSH_AGENT_SIGN_RESPONSE = 14; - const SSH_AGENT_RSA_SHA2_256 = 1 << 1; - const SSH_AGENT_RSA_SHA2_512 = 1 << 2; - const ROLE_CLIENT = 0; - const ROLE_SERVER = 1; - function processResponses(protocol) { - let ret; - while (protocol[SYM_REQS].length) { - const nextResponse = protocol[SYM_REQS][0][SYM_RESP]; - if (nextResponse === void 0) - break; - protocol[SYM_REQS].shift(); - ret = protocol.push(nextResponse); - } - return ret; - } - const SYM_TYPE = /* @__PURE__ */ Symbol("Inbound Request Type"); - const SYM_RESP = /* @__PURE__ */ Symbol("Inbound Request Response"); - const SYM_CTX = /* @__PURE__ */ Symbol("Inbound Request Context"); - class AgentInboundRequest { - constructor(type, ctx) { - this[SYM_TYPE] = type; - this[SYM_RESP] = void 0; - this[SYM_CTX] = ctx; - } - hasResponded() { - return this[SYM_RESP] !== void 0; - } - getType() { - return this[SYM_TYPE]; - } - getContext() { - return this[SYM_CTX]; - } - } - function respond(protocol, req, data) { - req[SYM_RESP] = data; - return processResponses(protocol); - } - function cleanup(protocol) { - protocol[SYM_BUFFER] = null; - if (protocol[SYM_MODE] === ROLE_CLIENT) { - const reqs = protocol[SYM_REQS]; - if (reqs && reqs.length) { - protocol[SYM_REQS] = []; - for (const req of reqs) - req.cb(new Error("No reply from server")); - } - } - try { - protocol.end(); - } catch { - } - setImmediate(() => { - if (!protocol[SYM_ENDED]) - protocol.emit("end"); - if (!protocol[SYM_CLOSED]) - protocol.emit("close"); - }); - } - function onClose() { - this[SYM_CLOSED] = true; - } - function onEnd() { - this[SYM_ENDED] = true; - } - const SYM_REQS = /* @__PURE__ */ Symbol("Requests"); - const SYM_MODE = /* @__PURE__ */ Symbol("Agent Protocol Role"); - const SYM_BUFFER = /* @__PURE__ */ Symbol("Agent Protocol Buffer"); - const SYM_MSGLEN = /* @__PURE__ */ Symbol("Agent Protocol Current Message Length"); - const SYM_CLOSED = /* @__PURE__ */ Symbol("Agent Protocol Closed"); - const SYM_ENDED = /* @__PURE__ */ Symbol("Agent Protocol Ended"); - return class AgentProtocol extends Duplex { - /* - Notes: - - `constraint` type consists of: - byte constraint_type - byte[] constraint_data - where `constraint_type` is one of: - * SSH_AGENT_CONSTRAIN_LIFETIME - - `constraint_data` consists of: - uint32 seconds - * SSH_AGENT_CONSTRAIN_CONFIRM - - `constraint_data` N/A - * SSH_AGENT_CONSTRAIN_EXTENSION - - `constraint_data` consists of: - string extension name - byte[] extension-specific details - */ - constructor(isClient) { - super({ autoDestroy: true, emitClose: false }); - this[SYM_MODE] = isClient ? ROLE_CLIENT : ROLE_SERVER; - this[SYM_REQS] = []; - this[SYM_BUFFER] = null; - this[SYM_MSGLEN] = -1; - this.once("end", onEnd); - this.once("close", onClose); - } - _read(n) { - } - _write(data, encoding, cb) { - if (this[SYM_BUFFER] === null) - this[SYM_BUFFER] = data; - else - this[SYM_BUFFER] = concat(this[SYM_BUFFER], data); - let buffer = this[SYM_BUFFER]; - let bufferLen = buffer.length; - let p = 0; - while (p < bufferLen) { - if (bufferLen < 5) - break; - if (this[SYM_MSGLEN] === -1) - this[SYM_MSGLEN] = readUInt32BE(buffer, p); - if (bufferLen < 4 + this[SYM_MSGLEN]) - break; - const msgType = buffer[p += 4]; - ++p; - if (this[SYM_MODE] === ROLE_CLIENT) { - if (this[SYM_REQS].length === 0) - return cb(new Error("Received unexpected message from server")); - const req = this[SYM_REQS].shift(); - switch (msgType) { - case SSH_AGENT_FAILURE: - req.cb(new Error("Agent responded with failure")); - break; - case SSH_AGENT_IDENTITIES_ANSWER: { - if (req.type !== SSH_AGENTC_REQUEST_IDENTITIES) - return cb(new Error("Agent responded with wrong message type")); - binaryParser.init(buffer, p); - const numKeys = binaryParser.readUInt32BE(); - if (numKeys === void 0) { - binaryParser.clear(); - return cb(new Error("Malformed agent response")); - } - const keys = []; - for (let i = 0; i < numKeys; ++i) { - let pubKey = binaryParser.readString(); - if (pubKey === void 0) { - binaryParser.clear(); - return cb(new Error("Malformed agent response")); - } - const comment = binaryParser.readString(true); - if (comment === void 0) { - binaryParser.clear(); - return cb(new Error("Malformed agent response")); - } - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) - continue; - pubKey.comment = pubKey.comment || comment; - keys.push(pubKey); - } - p = binaryParser.pos(); - binaryParser.clear(); - req.cb(null, keys); - break; - } - case SSH_AGENT_SIGN_RESPONSE: { - if (req.type !== SSH_AGENTC_SIGN_REQUEST) - return cb(new Error("Agent responded with wrong message type")); - binaryParser.init(buffer, p); - let signature = binaryParser.readString(); - p = binaryParser.pos(); - binaryParser.clear(); - if (signature === void 0) - return cb(new Error("Malformed agent response")); - binaryParser.init(signature, 0); - binaryParser.readString(true); - signature = binaryParser.readString(); - binaryParser.clear(); - if (signature === void 0) - return cb(new Error("Malformed OpenSSH signature format")); - req.cb(null, signature); - break; - } - default: - return cb( - new Error("Agent responded with unsupported message type") - ); - } - } else { - switch (msgType) { - case SSH_AGENTC_REQUEST_IDENTITIES: { - const req = new AgentInboundRequest(msgType); - this[SYM_REQS].push(req); - this.emit("identities", req); - break; - } - case SSH_AGENTC_SIGN_REQUEST: { - binaryParser.init(buffer, p); - let pubKey = binaryParser.readString(); - const data2 = binaryParser.readString(); - const flagsVal = binaryParser.readUInt32BE(); - p = binaryParser.pos(); - binaryParser.clear(); - if (flagsVal === void 0) { - const req2 = new AgentInboundRequest(msgType); - this[SYM_REQS].push(req2); - return this.failureReply(req2); - } - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) { - const req2 = new AgentInboundRequest(msgType); - this[SYM_REQS].push(req2); - return this.failureReply(req2); - } - const flags = { - hash: void 0 - }; - let ctx; - if (pubKey.type === "ssh-rsa") { - if (flagsVal & SSH_AGENT_RSA_SHA2_256) { - ctx = "rsa-sha2-256"; - flags.hash = "sha256"; - } else if (flagsVal & SSH_AGENT_RSA_SHA2_512) { - ctx = "rsa-sha2-512"; - flags.hash = "sha512"; - } - } - if (ctx === void 0) - ctx = pubKey.type; - const req = new AgentInboundRequest(msgType, ctx); - this[SYM_REQS].push(req); - this.emit("sign", req, pubKey, data2, flags); - break; - } - default: { - const req = new AgentInboundRequest(msgType); - this[SYM_REQS].push(req); - this.failureReply(req); - } - } - } - this[SYM_MSGLEN] = -1; - if (p === bufferLen) { - this[SYM_BUFFER] = null; - break; - } else { - this[SYM_BUFFER] = buffer = buffer.slice(p); - bufferLen = buffer.length; - p = 0; - } - } - cb(); - } - _destroy(err, cb) { - cleanup(this); - cb(); - } - _final(cb) { - cleanup(this); - cb(); - } - // Client->Server messages ================================================= - sign(pubKey, data, options, cb) { - if (this[SYM_MODE] !== ROLE_CLIENT) - throw new Error("Client-only method called with server role"); - if (typeof options === "function") { - cb = options; - options = void 0; - } else if (typeof options !== "object" || options === null) { - options = void 0; - } - let flags = 0; - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) - throw new Error("Invalid public key argument"); - if (pubKey.type === "ssh-rsa" && options) { - switch (options.hash) { - case "sha256": - flags = SSH_AGENT_RSA_SHA2_256; - break; - case "sha512": - flags = SSH_AGENT_RSA_SHA2_512; - break; - } - } - pubKey = pubKey.getPublicSSH(); - const type = SSH_AGENTC_SIGN_REQUEST; - const keyLen = pubKey.length; - const dataLen = data.length; - let p = 0; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + keyLen + 4 + dataLen + 4); - writeUInt32BE(buf, buf.length - 4, p); - buf[p += 4] = type; - writeUInt32BE(buf, keyLen, ++p); - pubKey.copy(buf, p += 4); - writeUInt32BE(buf, dataLen, p += keyLen); - data.copy(buf, p += 4); - writeUInt32BE(buf, flags, p += dataLen); - if (typeof cb !== "function") - cb = noop3; - this[SYM_REQS].push({ type, cb }); - return this.push(buf); - } - getIdentities(cb) { - if (this[SYM_MODE] !== ROLE_CLIENT) - throw new Error("Client-only method called with server role"); - const type = SSH_AGENTC_REQUEST_IDENTITIES; - let p = 0; - const buf = Buffer.allocUnsafe(4 + 1); - writeUInt32BE(buf, buf.length - 4, p); - buf[p += 4] = type; - if (typeof cb !== "function") - cb = noop3; - this[SYM_REQS].push({ type, cb }); - return this.push(buf); - } - // Server->Client messages ================================================= - failureReply(req) { - if (this[SYM_MODE] !== ROLE_SERVER) - throw new Error("Server-only method called with client role"); - if (!(req instanceof AgentInboundRequest)) - throw new Error("Wrong request argument"); - if (req.hasResponded()) - return true; - let p = 0; - const buf = Buffer.allocUnsafe(4 + 1); - writeUInt32BE(buf, buf.length - 4, p); - buf[p += 4] = SSH_AGENT_FAILURE; - return respond(this, req, buf); - } - getIdentitiesReply(req, keys) { - if (this[SYM_MODE] !== ROLE_SERVER) - throw new Error("Server-only method called with client role"); - if (!(req instanceof AgentInboundRequest)) - throw new Error("Wrong request argument"); - if (req.hasResponded()) - return true; - if (req.getType() !== SSH_AGENTC_REQUEST_IDENTITIES) - throw new Error("Invalid response to request"); - if (!Array.isArray(keys)) - throw new Error("Keys argument must be an array"); - let totalKeysLen = 4; - const newKeys = []; - for (let i = 0; i < keys.length; ++i) { - const entry = keys[i]; - if (typeof entry !== "object" || entry === null) - throw new Error(`Invalid key entry: ${entry}`); - let pubKey; - let comment; - if (isParsedKey(entry)) { - pubKey = entry; - } else if (isParsedKey(entry.pubKey)) { - pubKey = entry.pubKey; - } else { - if (typeof entry.pubKey !== "object" || entry.pubKey === null) - continue; - ({ pubKey, comment } = entry.pubKey); - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) - continue; - } - comment = pubKey.comment || comment; - pubKey = pubKey.getPublicSSH(); - totalKeysLen += 4 + pubKey.length; - if (comment && typeof comment === "string") - comment = Buffer.from(comment); - else if (!Buffer.isBuffer(comment)) - comment = EMPTY_BUF; - totalKeysLen += 4 + comment.length; - newKeys.push({ pubKey, comment }); - } - let p = 0; - const buf = Buffer.allocUnsafe(4 + 1 + totalKeysLen); - writeUInt32BE(buf, buf.length - 4, p); - buf[p += 4] = SSH_AGENT_IDENTITIES_ANSWER; - writeUInt32BE(buf, newKeys.length, ++p); - p += 4; - for (let i = 0; i < newKeys.length; ++i) { - const { pubKey, comment } = newKeys[i]; - writeUInt32BE(buf, pubKey.length, p); - pubKey.copy(buf, p += 4); - writeUInt32BE(buf, comment.length, p += pubKey.length); - p += 4; - if (comment.length) { - comment.copy(buf, p); - p += comment.length; - } - } - return respond(this, req, buf); - } - signReply(req, signature) { - if (this[SYM_MODE] !== ROLE_SERVER) - throw new Error("Server-only method called with client role"); - if (!(req instanceof AgentInboundRequest)) - throw new Error("Wrong request argument"); - if (req.hasResponded()) - return true; - if (req.getType() !== SSH_AGENTC_SIGN_REQUEST) - throw new Error("Invalid response to request"); - if (!Buffer.isBuffer(signature)) - throw new Error("Signature argument must be a Buffer"); - if (signature.length === 0) - throw new Error("Signature argument must be non-empty"); - let p = 0; - const sigFormat = req.getContext(); - const sigFormatLen = Buffer.byteLength(sigFormat); - const buf = Buffer.allocUnsafe( - 4 + 1 + 4 + 4 + sigFormatLen + 4 + signature.length - ); - writeUInt32BE(buf, buf.length - 4, p); - buf[p += 4] = SSH_AGENT_SIGN_RESPONSE; - writeUInt32BE(buf, 4 + sigFormatLen + 4 + signature.length, ++p); - writeUInt32BE(buf, sigFormatLen, p += 4); - buf.utf8Write(sigFormat, p += 4, sigFormatLen); - writeUInt32BE(buf, signature.length, p += sigFormatLen); - signature.copy(buf, p += 4); - return respond(this, req, buf); - } - }; - })(); - var SYM_AGENT = /* @__PURE__ */ Symbol("Agent"); - var SYM_AGENT_KEYS = /* @__PURE__ */ Symbol("Agent Keys"); - var SYM_AGENT_KEYS_IDX = /* @__PURE__ */ Symbol("Agent Keys Index"); - var SYM_AGENT_CBS = /* @__PURE__ */ Symbol("Agent Init Callbacks"); - var AgentContext = class { - constructor(agent) { - if (typeof agent === "string") - agent = createAgent(agent); - else if (!isAgent(agent)) - throw new Error("Invalid agent argument"); - this[SYM_AGENT] = agent; - this[SYM_AGENT_KEYS] = null; - this[SYM_AGENT_KEYS_IDX] = -1; - this[SYM_AGENT_CBS] = null; - } - init(cb) { - if (typeof cb !== "function") - cb = noop3; - if (this[SYM_AGENT_KEYS] === null) { - if (this[SYM_AGENT_CBS] === null) { - this[SYM_AGENT_CBS] = [cb]; - const doCbs = (...args) => { - process.nextTick(() => { - const cbs = this[SYM_AGENT_CBS]; - this[SYM_AGENT_CBS] = null; - for (const cb2 of cbs) - cb2(...args); - }); - }; - this[SYM_AGENT].getIdentities(once((err, keys) => { - if (err) - return doCbs(err); - if (!Array.isArray(keys)) { - return doCbs(new Error( - "Agent implementation failed to provide keys" - )); - } - const newKeys = []; - for (let key of keys) { - key = parseKey(key); - if (key instanceof Error) { - continue; - } - newKeys.push(key); - } - this[SYM_AGENT_KEYS] = newKeys; - this[SYM_AGENT_KEYS_IDX] = -1; - doCbs(); - })); - } else { - this[SYM_AGENT_CBS].push(cb); - } - } else { - process.nextTick(cb); - } - } - nextKey() { - if (this[SYM_AGENT_KEYS] === null || ++this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { - return false; - } - return this[SYM_AGENT_KEYS][this[SYM_AGENT_KEYS_IDX]]; - } - currentKey() { - if (this[SYM_AGENT_KEYS] === null || this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { - return null; - } - return this[SYM_AGENT_KEYS][this[SYM_AGENT_KEYS_IDX]]; - } - pos() { - if (this[SYM_AGENT_KEYS] === null || this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { - return -1; - } - return this[SYM_AGENT_KEYS_IDX]; - } - reset() { - this[SYM_AGENT_KEYS_IDX] = -1; - } - sign(...args) { - this[SYM_AGENT].sign(...args); - } - }; - function isAgent(val) { - return val instanceof BaseAgent; - } - module2.exports = { - AgentContext, - AgentProtocol, - BaseAgent, - createAgent, - CygwinAgent, - isAgent, - OpenSSHAgent, - PageantAgent - }; - } -}); - -// node_modules/ssh2/lib/protocol/zlib.js -var require_zlib = __commonJS({ - "node_modules/ssh2/lib/protocol/zlib.js"(exports2, module2) { - "use strict"; - var { kMaxLength } = require("buffer"); - var { - createInflate, - constants: { - DEFLATE, - INFLATE, - Z_DEFAULT_CHUNK, - Z_DEFAULT_COMPRESSION, - Z_DEFAULT_MEMLEVEL, - Z_DEFAULT_STRATEGY, - Z_DEFAULT_WINDOWBITS, - Z_PARTIAL_FLUSH - } - } = require("zlib"); - var ZlibHandle = createInflate()._handle.constructor; - function processCallback() { - throw new Error("Should not get here"); - } - function zlibOnError(message, errno, code) { - const self2 = this._owner; - const error3 = new Error(message); - error3.errno = errno; - error3.code = code; - self2._err = error3; - } - function _close(engine) { - if (!engine._handle) - return; - engine._handle.close(); - engine._handle = null; - } - var Zlib = class { - constructor(mode) { - const windowBits = Z_DEFAULT_WINDOWBITS; - const level = Z_DEFAULT_COMPRESSION; - const memLevel = Z_DEFAULT_MEMLEVEL; - const strategy = Z_DEFAULT_STRATEGY; - const dictionary = void 0; - this._err = void 0; - this._writeState = new Uint32Array(2); - this._chunkSize = Z_DEFAULT_CHUNK; - this._maxOutputLength = kMaxLength; - this._outBuffer = Buffer.allocUnsafe(this._chunkSize); - this._outOffset = 0; - this._handle = new ZlibHandle(mode); - this._handle._owner = this; - this._handle.onerror = zlibOnError; - this._handle.init( - windowBits, - level, - memLevel, - strategy, - this._writeState, - processCallback, - dictionary - ); - } - writeSync(chunk, retChunks) { - const handle = this._handle; - if (!handle) - throw new Error("Invalid Zlib instance"); - let availInBefore = chunk.length; - let availOutBefore = this._chunkSize - this._outOffset; - let inOff = 0; - let availOutAfter; - let availInAfter; - let buffers; - let nread = 0; - const state = this._writeState; - let buffer = this._outBuffer; - let offset = this._outOffset; - const chunkSize = this._chunkSize; - while (true) { - handle.writeSync( - Z_PARTIAL_FLUSH, - chunk, - // in - inOff, - // in_off - availInBefore, - // in_len - buffer, - // out - offset, - // out_off - availOutBefore - ); - if (this._err) - throw this._err; - availOutAfter = state[0]; - availInAfter = state[1]; - const inDelta = availInBefore - availInAfter; - const have = availOutBefore - availOutAfter; - if (have > 0) { - const out = offset === 0 && have === buffer.length ? buffer : buffer.slice(offset, offset + have); - offset += have; - if (!buffers) - buffers = out; - else if (buffers.push === void 0) - buffers = [buffers, out]; - else - buffers.push(out); - nread += out.byteLength; - if (nread > this._maxOutputLength) { - _close(this); - throw new Error( - `Output length exceeded maximum of ${this._maxOutputLength}` - ); - } - } else if (have !== 0) { - throw new Error("have should not go down"); - } - if (availOutAfter === 0 || offset >= chunkSize) { - availOutBefore = chunkSize; - offset = 0; - buffer = Buffer.allocUnsafe(chunkSize); - } - if (availOutAfter === 0) { - inOff += inDelta; - availInBefore = availInAfter; - } else { - break; - } - } - this._outBuffer = buffer; - this._outOffset = offset; - if (nread === 0) - buffers = Buffer.alloc(0); - if (retChunks) { - buffers.totalLen = nread; - return buffers; - } - if (buffers.push === void 0) - return buffers; - const output = Buffer.allocUnsafe(nread); - for (let i = 0, p = 0; i < buffers.length; ++i) { - const buf = buffers[i]; - output.set(buf, p); - p += buf.length; - } - return output; - } - }; - var ZlibPacketWriter = class { - constructor(protocol) { - this.allocStart = 0; - this.allocStartKEX = 0; - this._protocol = protocol; - this._zlib = new Zlib(DEFLATE); - } - cleanup() { - if (this._zlib) - _close(this._zlib); - } - alloc(payloadSize, force) { - return Buffer.allocUnsafe(payloadSize); - } - finalize(payload, force) { - if (this._protocol._kexinit === void 0 || force) { - const output = this._zlib.writeSync(payload, true); - const packet = this._protocol._cipher.allocPacket(output.totalLen); - if (output.push === void 0) { - packet.set(output, 5); - } else { - for (let i = 0, p = 5; i < output.length; ++i) { - const chunk = output[i]; - packet.set(chunk, p); - p += chunk.length; - } - } - return packet; - } - return payload; - } - }; - var PacketWriter = class { - constructor(protocol) { - this.allocStart = 5; - this.allocStartKEX = 5; - this._protocol = protocol; - } - cleanup() { - } - alloc(payloadSize, force) { - if (this._protocol._kexinit === void 0 || force) - return this._protocol._cipher.allocPacket(payloadSize); - return Buffer.allocUnsafe(payloadSize); - } - finalize(packet, force) { - return packet; - } - }; - var ZlibPacketReader = class { - constructor() { - this._zlib = new Zlib(INFLATE); - } - cleanup() { - if (this._zlib) - _close(this._zlib); - } - read(data) { - return this._zlib.writeSync(data, false); - } - }; - var PacketReader = class { - cleanup() { - } - read(data) { - return data; - } - }; - module2.exports = { - PacketReader, - PacketWriter, - ZlibPacketReader, - ZlibPacketWriter - }; - } -}); - -// node_modules/ssh2/lib/protocol/handlers.misc.js -var require_handlers_misc = __commonJS({ - "node_modules/ssh2/lib/protocol/handlers.misc.js"(exports2, module2) { - "use strict"; - var { - bufferSlice, - bufferParser, - doFatalError, - sigSSHToASN1, - writeUInt32BE - } = require_utils4(); - var { - CHANNEL_OPEN_FAILURE, - COMPAT, - MESSAGE, - TERMINAL_MODE - } = require_constants6(); - var { - parseKey - } = require_keyParser(); - var TERMINAL_MODE_BY_VALUE = Array.from(Object.entries(TERMINAL_MODE)).reduce((obj, [key, value]) => ({ ...obj, [key]: value }), {}); - module2.exports = { - // Transport layer protocol ================================================== - [MESSAGE.DISCONNECT]: (self2, payload) => { - bufferParser.init(payload, 1); - const reason = bufferParser.readUInt32BE(); - const desc = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); - if (lang === void 0) { - return doFatalError( - self2, - "Inbound: Malformed DISCONNECT packet" - ); - } - self2._debug && self2._debug( - `Inbound: Received DISCONNECT (${reason}, "${desc}")` - ); - const handler2 = self2._handlers.DISCONNECT; - handler2 && handler2(self2, reason, desc); - }, - [MESSAGE.IGNORE]: (self2, payload) => { - self2._debug && self2._debug("Inbound: Received IGNORE"); - }, - [MESSAGE.UNIMPLEMENTED]: (self2, payload) => { - bufferParser.init(payload, 1); - const seqno = bufferParser.readUInt32BE(); - bufferParser.clear(); - if (seqno === void 0) { - return doFatalError( - self2, - "Inbound: Malformed UNIMPLEMENTED packet" - ); - } - self2._debug && self2._debug(`Inbound: Received UNIMPLEMENTED (seqno ${seqno})`); - }, - [MESSAGE.DEBUG]: (self2, payload) => { - bufferParser.init(payload, 1); - const display = bufferParser.readBool(); - const msg = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); - if (lang === void 0) { - return doFatalError( - self2, - "Inbound: Malformed DEBUG packet" - ); - } - self2._debug && self2._debug("Inbound: Received DEBUG"); - const handler2 = self2._handlers.DEBUG; - handler2 && handler2(self2, display, msg); - }, - [MESSAGE.SERVICE_REQUEST]: (self2, payload) => { - bufferParser.init(payload, 1); - const name = bufferParser.readString(true); - bufferParser.clear(); - if (name === void 0) { - return doFatalError( - self2, - "Inbound: Malformed SERVICE_REQUEST packet" - ); - } - self2._debug && self2._debug(`Inbound: Received SERVICE_REQUEST (${name})`); - const handler2 = self2._handlers.SERVICE_REQUEST; - handler2 && handler2(self2, name); - }, - [MESSAGE.SERVICE_ACCEPT]: (self2, payload) => { - bufferParser.init(payload, 1); - const name = bufferParser.readString(true); - bufferParser.clear(); - if (name === void 0) { - return doFatalError( - self2, - "Inbound: Malformed SERVICE_ACCEPT packet" - ); - } - self2._debug && self2._debug(`Inbound: Received SERVICE_ACCEPT (${name})`); - const handler2 = self2._handlers.SERVICE_ACCEPT; - handler2 && handler2(self2, name); - }, - [MESSAGE.EXT_INFO]: (self2, payload) => { - bufferParser.init(payload, 1); - const numExts = bufferParser.readUInt32BE(); - let exts; - if (numExts !== void 0) { - exts = []; - for (let i = 0; i < numExts; ++i) { - const name = bufferParser.readString(true); - const data = bufferParser.readString(); - if (data !== void 0) { - switch (name) { - case "server-sig-algs": { - const algs = data.latin1Slice(0, data.length).split(","); - exts.push({ name, algs }); - continue; - } - default: - continue; - } - } - exts = void 0; - break; - } - } - bufferParser.clear(); - if (exts === void 0) - return doFatalError(self2, "Inbound: Malformed EXT_INFO packet"); - self2._debug && self2._debug("Inbound: Received EXT_INFO"); - const handler2 = self2._handlers.EXT_INFO; - handler2 && handler2(self2, exts); - }, - // User auth protocol -- generic ============================================= - [MESSAGE.USERAUTH_REQUEST]: (self2, payload) => { - bufferParser.init(payload, 1); - const user = bufferParser.readString(true); - const service = bufferParser.readString(true); - const method = bufferParser.readString(true); - let methodData; - let methodDesc; - switch (method) { - case "none": - methodData = null; - break; - case "password": { - const isChange = bufferParser.readBool(); - if (isChange !== void 0) { - methodData = bufferParser.readString(true); - if (methodData !== void 0 && isChange) { - const newPassword = bufferParser.readString(true); - if (newPassword !== void 0) - methodData = { oldPassword: methodData, newPassword }; - else - methodData = void 0; - } - } - break; - } - case "publickey": { - const hasSig = bufferParser.readBool(); - if (hasSig !== void 0) { - const keyAlgo = bufferParser.readString(true); - let realKeyAlgo = keyAlgo; - const key = bufferParser.readString(); - let hashAlgo; - switch (keyAlgo) { - case "rsa-sha2-256": - realKeyAlgo = "ssh-rsa"; - hashAlgo = "sha256"; - break; - case "rsa-sha2-512": - realKeyAlgo = "ssh-rsa"; - hashAlgo = "sha512"; - break; - } - if (hasSig) { - const blobEnd = bufferParser.pos(); - let signature = bufferParser.readString(); - if (signature !== void 0) { - if (signature.length > 4 + keyAlgo.length + 4 && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) { - signature = bufferSlice(signature, 4 + keyAlgo.length + 4); - } - signature = sigSSHToASN1(signature, realKeyAlgo); - if (signature) { - const sessionID = self2._kex.sessionID; - const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd); - writeUInt32BE(blob, sessionID.length, 0); - blob.set(sessionID, 4); - blob.set( - new Uint8Array(payload.buffer, payload.byteOffset, blobEnd), - 4 + sessionID.length - ); - methodData = { - keyAlgo: realKeyAlgo, - key, - signature, - blob, - hashAlgo - }; - } - } - } else { - methodData = { keyAlgo: realKeyAlgo, key, hashAlgo }; - methodDesc = "publickey -- check"; - } - } - break; - } - case "hostbased": { - const keyAlgo = bufferParser.readString(true); - let realKeyAlgo = keyAlgo; - const key = bufferParser.readString(); - const localHostname = bufferParser.readString(true); - const localUsername = bufferParser.readString(true); - let hashAlgo; - switch (keyAlgo) { - case "rsa-sha2-256": - realKeyAlgo = "ssh-rsa"; - hashAlgo = "sha256"; - break; - case "rsa-sha2-512": - realKeyAlgo = "ssh-rsa"; - hashAlgo = "sha512"; - break; - } - const blobEnd = bufferParser.pos(); - let signature = bufferParser.readString(); - if (signature !== void 0) { - if (signature.length > 4 + keyAlgo.length + 4 && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) { - signature = bufferSlice(signature, 4 + keyAlgo.length + 4); - } - signature = sigSSHToASN1(signature, realKeyAlgo); - if (signature !== void 0) { - const sessionID = self2._kex.sessionID; - const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd); - writeUInt32BE(blob, sessionID.length, 0); - blob.set(sessionID, 4); - blob.set( - new Uint8Array(payload.buffer, payload.byteOffset, blobEnd), - 4 + sessionID.length - ); - methodData = { - keyAlgo: realKeyAlgo, - key, - signature, - blob, - localHostname, - localUsername, - hashAlgo - }; - } - } - break; - } - case "keyboard-interactive": - bufferParser.skipString(); - methodData = bufferParser.readList(); - break; - default: - if (method !== void 0) - methodData = bufferParser.readRaw(); - } - bufferParser.clear(); - if (methodData === void 0) { - return doFatalError( - self2, - "Inbound: Malformed USERAUTH_REQUEST packet" - ); - } - if (methodDesc === void 0) - methodDesc = method; - self2._authsQueue.push(method); - self2._debug && self2._debug(`Inbound: Received USERAUTH_REQUEST (${methodDesc})`); - const handler2 = self2._handlers.USERAUTH_REQUEST; - handler2 && handler2(self2, user, service, method, methodData); - }, - [MESSAGE.USERAUTH_FAILURE]: (self2, payload) => { - bufferParser.init(payload, 1); - const authMethods = bufferParser.readList(); - const partialSuccess = bufferParser.readBool(); - bufferParser.clear(); - if (partialSuccess === void 0) { - return doFatalError( - self2, - "Inbound: Malformed USERAUTH_FAILURE packet" - ); - } - self2._debug && self2._debug(`Inbound: Received USERAUTH_FAILURE (${authMethods})`); - self2._authsQueue.shift(); - const handler2 = self2._handlers.USERAUTH_FAILURE; - handler2 && handler2(self2, authMethods, partialSuccess); - }, - [MESSAGE.USERAUTH_SUCCESS]: (self2, payload) => { - self2._debug && self2._debug("Inbound: Received USERAUTH_SUCCESS"); - self2._authsQueue.shift(); - const handler2 = self2._handlers.USERAUTH_SUCCESS; - handler2 && handler2(self2); - }, - [MESSAGE.USERAUTH_BANNER]: (self2, payload) => { - bufferParser.init(payload, 1); - const msg = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); - if (lang === void 0) { - return doFatalError( - self2, - "Inbound: Malformed USERAUTH_BANNER packet" - ); - } - self2._debug && self2._debug("Inbound: Received USERAUTH_BANNER"); - const handler2 = self2._handlers.USERAUTH_BANNER; - handler2 && handler2(self2, msg); - }, - // User auth protocol -- method-specific ===================================== - 60: (self2, payload) => { - if (!self2._authsQueue.length) { - self2._debug && self2._debug("Inbound: Received payload type 60 without auth"); - return; - } - switch (self2._authsQueue[0]) { - case "password": { - bufferParser.init(payload, 1); - const prompt = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); - if (lang === void 0) { - return doFatalError( - self2, - "Inbound: Malformed USERAUTH_PASSWD_CHANGEREQ packet" - ); - } - self2._debug && self2._debug("Inbound: Received USERAUTH_PASSWD_CHANGEREQ"); - const handler2 = self2._handlers.USERAUTH_PASSWD_CHANGEREQ; - handler2 && handler2(self2, prompt); - break; - } - case "publickey": { - bufferParser.init(payload, 1); - const keyAlgo = bufferParser.readString(true); - const key = bufferParser.readString(); - bufferParser.clear(); - if (key === void 0) { - return doFatalError( - self2, - "Inbound: Malformed USERAUTH_PK_OK packet" - ); - } - self2._debug && self2._debug("Inbound: Received USERAUTH_PK_OK"); - self2._authsQueue.shift(); - const handler2 = self2._handlers.USERAUTH_PK_OK; - handler2 && handler2(self2, keyAlgo, key); - break; - } - case "keyboard-interactive": { - bufferParser.init(payload, 1); - const name = bufferParser.readString(true); - const instructions = bufferParser.readString(true); - bufferParser.readString(); - const numPrompts = bufferParser.readUInt32BE(); - let prompts; - if (numPrompts !== void 0) { - prompts = new Array(numPrompts); - let i; - for (i = 0; i < numPrompts; ++i) { - const prompt = bufferParser.readString(true); - const echo = bufferParser.readBool(); - if (echo === void 0) - break; - prompts[i] = { prompt, echo }; - } - if (i !== numPrompts) - prompts = void 0; - } - bufferParser.clear(); - if (prompts === void 0) { - return doFatalError( - self2, - "Inbound: Malformed USERAUTH_INFO_REQUEST packet" - ); - } - self2._debug && self2._debug("Inbound: Received USERAUTH_INFO_REQUEST"); - const handler2 = self2._handlers.USERAUTH_INFO_REQUEST; - handler2 && handler2(self2, name, instructions, prompts); - break; - } - default: - self2._debug && self2._debug("Inbound: Received unexpected payload type 60"); - } - }, - 61: (self2, payload) => { - if (!self2._authsQueue.length) { - self2._debug && self2._debug("Inbound: Received payload type 61 without auth"); - return; - } - if (self2._authsQueue[0] !== "keyboard-interactive") { - return doFatalError( - self2, - "Inbound: Received unexpected payload type 61" - ); - } - bufferParser.init(payload, 1); - const numResponses = bufferParser.readUInt32BE(); - let responses; - if (numResponses !== void 0) { - responses = new Array(numResponses); - let i; - for (i = 0; i < numResponses; ++i) { - const response = bufferParser.readString(true); - if (response === void 0) - break; - responses[i] = response; - } - if (i !== numResponses) - responses = void 0; - } - bufferParser.clear(); - if (responses === void 0) { - return doFatalError( - self2, - "Inbound: Malformed USERAUTH_INFO_RESPONSE packet" - ); - } - self2._debug && self2._debug("Inbound: Received USERAUTH_INFO_RESPONSE"); - const handler2 = self2._handlers.USERAUTH_INFO_RESPONSE; - handler2 && handler2(self2, responses); - }, - // Connection protocol -- generic ============================================ - [MESSAGE.GLOBAL_REQUEST]: (self2, payload) => { - bufferParser.init(payload, 1); - const name = bufferParser.readString(true); - const wantReply = bufferParser.readBool(); - let data; - if (wantReply !== void 0) { - switch (name) { - case "tcpip-forward": - case "cancel-tcpip-forward": { - const bindAddr = bufferParser.readString(true); - const bindPort = bufferParser.readUInt32BE(); - if (bindPort !== void 0) - data = { bindAddr, bindPort }; - break; - } - case "streamlocal-forward@openssh.com": - case "cancel-streamlocal-forward@openssh.com": { - const socketPath = bufferParser.readString(true); - if (socketPath !== void 0) - data = { socketPath }; - break; - } - case "no-more-sessions@openssh.com": - data = null; - break; - case "hostkeys-00@openssh.com": { - data = []; - while (bufferParser.avail() > 0) { - const keyRaw = bufferParser.readString(); - if (keyRaw === void 0) { - data = void 0; - break; - } - const key = parseKey(keyRaw); - if (!(key instanceof Error)) - data.push(key); - } - break; - } - default: - data = bufferParser.readRaw(); - } - } - bufferParser.clear(); - if (data === void 0) { - return doFatalError( - self2, - "Inbound: Malformed GLOBAL_REQUEST packet" - ); - } - self2._debug && self2._debug(`Inbound: GLOBAL_REQUEST (${name})`); - const handler2 = self2._handlers.GLOBAL_REQUEST; - if (handler2) - handler2(self2, name, wantReply, data); - else - self2.requestFailure(); - }, - [MESSAGE.REQUEST_SUCCESS]: (self2, payload) => { - const data = payload.length > 1 ? bufferSlice(payload, 1) : null; - self2._debug && self2._debug("Inbound: REQUEST_SUCCESS"); - const handler2 = self2._handlers.REQUEST_SUCCESS; - handler2 && handler2(self2, data); - }, - [MESSAGE.REQUEST_FAILURE]: (self2, payload) => { - self2._debug && self2._debug("Inbound: Received REQUEST_FAILURE"); - const handler2 = self2._handlers.REQUEST_FAILURE; - handler2 && handler2(self2); - }, - // Connection protocol -- channel-related ==================================== - [MESSAGE.CHANNEL_OPEN]: (self2, payload) => { - bufferParser.init(payload, 1); - const type = bufferParser.readString(true); - const sender = bufferParser.readUInt32BE(); - const window2 = bufferParser.readUInt32BE(); - const packetSize = bufferParser.readUInt32BE(); - let channelInfo; - switch (type) { - case "forwarded-tcpip": - // S->C - case "direct-tcpip": { - const destIP = bufferParser.readString(true); - const destPort = bufferParser.readUInt32BE(); - const srcIP = bufferParser.readString(true); - const srcPort = bufferParser.readUInt32BE(); - if (srcPort !== void 0) { - channelInfo = { - type, - sender, - window: window2, - packetSize, - data: { destIP, destPort, srcIP, srcPort } - }; - } - break; - } - case "forwarded-streamlocal@openssh.com": - // S->C - case "direct-streamlocal@openssh.com": { - const socketPath = bufferParser.readString(true); - if (socketPath !== void 0) { - channelInfo = { - type, - sender, - window: window2, - packetSize, - data: { socketPath } - }; - } - break; - } - case "x11": { - const srcIP = bufferParser.readString(true); - const srcPort = bufferParser.readUInt32BE(); - if (srcPort !== void 0) { - channelInfo = { - type, - sender, - window: window2, - packetSize, - data: { srcIP, srcPort } - }; - } - break; - } - default: - channelInfo = { - type, - sender, - window: window2, - packetSize, - data: {} - }; - } - bufferParser.clear(); - if (channelInfo === void 0) { - return doFatalError( - self2, - "Inbound: Malformed CHANNEL_OPEN packet" - ); - } - self2._debug && self2._debug(`Inbound: CHANNEL_OPEN (s:${sender}, ${type})`); - const handler2 = self2._handlers.CHANNEL_OPEN; - if (handler2) { - handler2(self2, channelInfo); - } else { - self2.channelOpenFail( - channelInfo.sender, - CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED, - "", - "" - ); - } - }, - [MESSAGE.CHANNEL_OPEN_CONFIRMATION]: (self2, payload) => { - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const sender = bufferParser.readUInt32BE(); - const window2 = bufferParser.readUInt32BE(); - const packetSize = bufferParser.readUInt32BE(); - const data = bufferParser.avail() ? bufferParser.readRaw() : void 0; - bufferParser.clear(); - if (packetSize === void 0) { - return doFatalError( - self2, - "Inbound: Malformed CHANNEL_OPEN_CONFIRMATION packet" - ); - } - self2._debug && self2._debug( - `Inbound: CHANNEL_OPEN_CONFIRMATION (r:${recipient}, s:${sender})` - ); - const handler2 = self2._handlers.CHANNEL_OPEN_CONFIRMATION; - if (handler2) - handler2(self2, { recipient, sender, window: window2, packetSize, data }); - }, - [MESSAGE.CHANNEL_OPEN_FAILURE]: (self2, payload) => { - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const reason = bufferParser.readUInt32BE(); - const description = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); - if (lang === void 0) { - return doFatalError( - self2, - "Inbound: Malformed CHANNEL_OPEN_FAILURE packet" - ); - } - self2._debug && self2._debug(`Inbound: CHANNEL_OPEN_FAILURE (r:${recipient})`); - const handler2 = self2._handlers.CHANNEL_OPEN_FAILURE; - handler2 && handler2(self2, recipient, reason, description); - }, - [MESSAGE.CHANNEL_WINDOW_ADJUST]: (self2, payload) => { - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const bytesToAdd = bufferParser.readUInt32BE(); - bufferParser.clear(); - if (bytesToAdd === void 0) { - return doFatalError( - self2, - "Inbound: Malformed CHANNEL_WINDOW_ADJUST packet" - ); - } - self2._debug && self2._debug( - `Inbound: CHANNEL_WINDOW_ADJUST (r:${recipient}, ${bytesToAdd})` - ); - const handler2 = self2._handlers.CHANNEL_WINDOW_ADJUST; - handler2 && handler2(self2, recipient, bytesToAdd); - }, - [MESSAGE.CHANNEL_DATA]: (self2, payload) => { - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const data = bufferParser.readString(); - bufferParser.clear(); - if (data === void 0) { - return doFatalError( - self2, - "Inbound: Malformed CHANNEL_DATA packet" - ); - } - self2._debug && self2._debug(`Inbound: CHANNEL_DATA (r:${recipient}, ${data.length})`); - const handler2 = self2._handlers.CHANNEL_DATA; - handler2 && handler2(self2, recipient, data); - }, - [MESSAGE.CHANNEL_EXTENDED_DATA]: (self2, payload) => { - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const type = bufferParser.readUInt32BE(); - const data = bufferParser.readString(); - bufferParser.clear(); - if (data === void 0) { - return doFatalError( - self2, - "Inbound: Malformed CHANNEL_EXTENDED_DATA packet" - ); - } - self2._debug && self2._debug( - `Inbound: CHANNEL_EXTENDED_DATA (r:${recipient}, ${data.length})` - ); - const handler2 = self2._handlers.CHANNEL_EXTENDED_DATA; - handler2 && handler2(self2, recipient, data, type); - }, - [MESSAGE.CHANNEL_EOF]: (self2, payload) => { - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - bufferParser.clear(); - if (recipient === void 0) { - return doFatalError( - self2, - "Inbound: Malformed CHANNEL_EOF packet" - ); - } - self2._debug && self2._debug(`Inbound: CHANNEL_EOF (r:${recipient})`); - const handler2 = self2._handlers.CHANNEL_EOF; - handler2 && handler2(self2, recipient); - }, - [MESSAGE.CHANNEL_CLOSE]: (self2, payload) => { - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - bufferParser.clear(); - if (recipient === void 0) { - return doFatalError( - self2, - "Inbound: Malformed CHANNEL_CLOSE packet" - ); - } - self2._debug && self2._debug(`Inbound: CHANNEL_CLOSE (r:${recipient})`); - const handler2 = self2._handlers.CHANNEL_CLOSE; - handler2 && handler2(self2, recipient); - }, - [MESSAGE.CHANNEL_REQUEST]: (self2, payload) => { - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const type = bufferParser.readString(true); - const wantReply = bufferParser.readBool(); - let data; - if (wantReply !== void 0) { - switch (type) { - case "exit-status": - data = bufferParser.readUInt32BE(); - self2._debug && self2._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case "exit-signal": { - let signal; - let coreDumped; - if (self2._compatFlags & COMPAT.OLD_EXIT) { - const num = bufferParser.readUInt32BE(); - switch (num) { - case 1: - signal = "HUP"; - break; - case 2: - signal = "INT"; - break; - case 3: - signal = "QUIT"; - break; - case 6: - signal = "ABRT"; - break; - case 9: - signal = "KILL"; - break; - case 14: - signal = "ALRM"; - break; - case 15: - signal = "TERM"; - break; - default: - if (num !== void 0) { - signal = `UNKNOWN (${num})`; - } - } - coreDumped = false; - } else { - signal = bufferParser.readString(true); - coreDumped = bufferParser.readBool(); - if (coreDumped === void 0) - signal = void 0; - } - const errorMessage = bufferParser.readString(true); - if (bufferParser.skipString() !== void 0) - data = { signal, coreDumped, errorMessage }; - self2._debug && self2._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${signal})` - ); - break; - } - case "pty-req": { - const term = bufferParser.readString(true); - const cols = bufferParser.readUInt32BE(); - const rows = bufferParser.readUInt32BE(); - const width = bufferParser.readUInt32BE(); - const height = bufferParser.readUInt32BE(); - const modesBinary = bufferParser.readString(); - if (modesBinary !== void 0) { - bufferParser.init(modesBinary, 1); - let modes = {}; - while (bufferParser.avail()) { - const opcode = bufferParser.readByte(); - if (opcode === TERMINAL_MODE.TTY_OP_END) - break; - const name = TERMINAL_MODE_BY_VALUE[opcode]; - const value = bufferParser.readUInt32BE(); - if (opcode === void 0 || name === void 0 || value === void 0) { - modes = void 0; - break; - } - modes[name] = value; - } - if (modes !== void 0) - data = { term, cols, rows, width, height, modes }; - } - self2._debug && self2._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - } - case "window-change": { - const cols = bufferParser.readUInt32BE(); - const rows = bufferParser.readUInt32BE(); - const width = bufferParser.readUInt32BE(); - const height = bufferParser.readUInt32BE(); - if (height !== void 0) - data = { cols, rows, width, height }; - self2._debug && self2._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - } - case "x11-req": { - const single = bufferParser.readBool(); - const protocol = bufferParser.readString(true); - const cookie = bufferParser.readString(); - const screen = bufferParser.readUInt32BE(); - if (screen !== void 0) - data = { single, protocol, cookie, screen }; - self2._debug && self2._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - } - case "env": { - const name = bufferParser.readString(true); - const value = bufferParser.readString(true); - if (value !== void 0) - data = { name, value }; - if (self2._debug) { - self2._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${name}=${value})` - ); - } - break; - } - case "shell": - data = null; - self2._debug && self2._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - case "exec": - data = bufferParser.readString(true); - self2._debug && self2._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case "subsystem": - data = bufferParser.readString(true); - self2._debug && self2._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case "signal": - data = bufferParser.readString(true); - self2._debug && self2._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case "xon-xoff": - data = bufferParser.readBool(); - self2._debug && self2._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case "auth-agent-req@openssh.com": - data = null; - self2._debug && self2._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - default: - data = bufferParser.avail() ? bufferParser.readRaw() : null; - self2._debug && self2._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - } - } - bufferParser.clear(); - if (data === void 0) { - return doFatalError( - self2, - "Inbound: Malformed CHANNEL_REQUEST packet" - ); - } - const handler2 = self2._handlers.CHANNEL_REQUEST; - handler2 && handler2(self2, recipient, type, wantReply, data); - }, - [MESSAGE.CHANNEL_SUCCESS]: (self2, payload) => { - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - bufferParser.clear(); - if (recipient === void 0) { - return doFatalError( - self2, - "Inbound: Malformed CHANNEL_SUCCESS packet" - ); - } - self2._debug && self2._debug(`Inbound: CHANNEL_SUCCESS (r:${recipient})`); - const handler2 = self2._handlers.CHANNEL_SUCCESS; - handler2 && handler2(self2, recipient); - }, - [MESSAGE.CHANNEL_FAILURE]: (self2, payload) => { - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - bufferParser.clear(); - if (recipient === void 0) { - return doFatalError( - self2, - "Inbound: Malformed CHANNEL_FAILURE packet" - ); - } - self2._debug && self2._debug(`Inbound: CHANNEL_FAILURE (r:${recipient})`); - const handler2 = self2._handlers.CHANNEL_FAILURE; - handler2 && handler2(self2, recipient); - } - }; - } -}); - -// node_modules/ssh2/lib/protocol/handlers.js -var require_handlers = __commonJS({ - "node_modules/ssh2/lib/protocol/handlers.js"(exports2, module2) { - "use strict"; - var MESSAGE_HANDLERS = new Array(256); - [ - require_kex().HANDLERS, - require_handlers_misc() - ].forEach((handlers) => { - for (let [type, handler2] of Object.entries(handlers)) { - type = +type; - if (isFinite(type) && type >= 0 && type < MESSAGE_HANDLERS.length) - MESSAGE_HANDLERS[type] = handler2; - } - }); - module2.exports = MESSAGE_HANDLERS; - } -}); - -// node_modules/ssh2/lib/protocol/kex.js -var require_kex = __commonJS({ - "node_modules/ssh2/lib/protocol/kex.js"(exports2, module2) { - "use strict"; - var { - createDiffieHellman, - createDiffieHellmanGroup, - createECDH, - createHash, - createPublicKey, - diffieHellman, - generateKeyPairSync, - randomFillSync - } = require("crypto"); - var { Ber } = require_lib3(); - var { - COMPAT, - curve25519Supported, - DEFAULT_KEX, - DEFAULT_SERVER_HOST_KEY, - DEFAULT_CIPHER, - DEFAULT_MAC, - DEFAULT_COMPRESSION, - DISCONNECT_REASON, - MESSAGE - } = require_constants6(); - var { - CIPHER_INFO, - createCipher, - createDecipher, - MAC_INFO - } = require_crypto(); - var { parseDERKey } = require_keyParser(); - var { - bufferFill, - bufferParser, - convertSignature, - doFatalError, - FastBuffer, - sigSSHToASN1, - writeUInt32BE - } = require_utils4(); - var { - PacketReader, - PacketWriter, - ZlibPacketReader, - ZlibPacketWriter - } = require_zlib(); - var MESSAGE_HANDLERS; - var GEX_MIN_BITS = 2048; - var GEX_MAX_BITS = 8192; - var EMPTY_BUFFER = Buffer.alloc(0); - function kexinit(self2) { - let payload; - if (self2._compatFlags & COMPAT.BAD_DHGEX) { - const entry = self2._offer.lists.kex; - let kex = entry.array; - let found = false; - for (let i = 0; i < kex.length; ++i) { - if (kex[i].includes("group-exchange")) { - if (!found) { - found = true; - kex = kex.slice(); - } - kex.splice(i--, 1); - } - } - if (found) { - let len = 1 + 16 + self2._offer.totalSize + 1 + 4; - const newKexBuf = Buffer.from(kex.join(",")); - len -= entry.buffer.length - newKexBuf.length; - const all = self2._offer.lists.all; - const rest = new Uint8Array( - all.buffer, - all.byteOffset + 4 + entry.buffer.length, - all.length - (4 + entry.buffer.length) - ); - payload = Buffer.allocUnsafe(len); - writeUInt32BE(payload, newKexBuf.length, 17); - payload.set(newKexBuf, 17 + 4); - payload.set(rest, 17 + 4 + newKexBuf.length); - } - } - if (payload === void 0) { - payload = Buffer.allocUnsafe(1 + 16 + self2._offer.totalSize + 1 + 4); - self2._offer.copyAllTo(payload, 17); - } - self2._debug && self2._debug("Outbound: Sending KEXINIT"); - payload[0] = MESSAGE.KEXINIT; - randomFillSync(payload, 1, 16); - bufferFill(payload, 0, payload.length - 5); - self2._kexinit = payload; - self2._packetRW.write.allocStart = 0; - { - const p = self2._packetRW.write.allocStartKEX; - const packet = self2._packetRW.write.alloc(payload.length, true); - packet.set(payload, p); - self2._cipher.encrypt(self2._packetRW.write.finalize(packet, true)); - } - } - function handleKexInit(self2, payload) { - const init = { - kex: void 0, - serverHostKey: void 0, - cs: { - cipher: void 0, - mac: void 0, - compress: void 0, - lang: void 0 - }, - sc: { - cipher: void 0, - mac: void 0, - compress: void 0, - lang: void 0 - } - }; - bufferParser.init(payload, 17); - if ((init.kex = bufferParser.readList()) === void 0 || (init.serverHostKey = bufferParser.readList()) === void 0 || (init.cs.cipher = bufferParser.readList()) === void 0 || (init.sc.cipher = bufferParser.readList()) === void 0 || (init.cs.mac = bufferParser.readList()) === void 0 || (init.sc.mac = bufferParser.readList()) === void 0 || (init.cs.compress = bufferParser.readList()) === void 0 || (init.sc.compress = bufferParser.readList()) === void 0 || (init.cs.lang = bufferParser.readList()) === void 0 || (init.sc.lang = bufferParser.readList()) === void 0) { - bufferParser.clear(); - return doFatalError( - self2, - "Received malformed KEXINIT", - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - const pos = bufferParser.pos(); - const firstFollows = pos < payload.length && payload[pos] === 1; - bufferParser.clear(); - const local = self2._offer; - const remote = init; - let localKex = local.lists.kex.array; - if (self2._compatFlags & COMPAT.BAD_DHGEX) { - let found = false; - for (let i2 = 0; i2 < localKex.length; ++i2) { - if (localKex[i2].indexOf("group-exchange") !== -1) { - if (!found) { - found = true; - localKex = localKex.slice(); - } - localKex.splice(i2--, 1); - } - } - } - let clientList; - let serverList; - let i; - const debug2 = self2._debug; - debug2 && debug2("Inbound: Handshake in progress"); - debug2 && debug2(`Handshake: (local) KEX method: ${localKex}`); - debug2 && debug2(`Handshake: (remote) KEX method: ${remote.kex}`); - let remoteExtInfoEnabled; - if (self2._server) { - serverList = localKex; - clientList = remote.kex; - remoteExtInfoEnabled = clientList.indexOf("ext-info-c") !== -1; - } else { - serverList = remote.kex; - clientList = localKex; - remoteExtInfoEnabled = serverList.indexOf("ext-info-s") !== -1; - } - if (self2._strictMode === void 0) { - if (self2._server) { - self2._strictMode = clientList.indexOf("kex-strict-c-v00@openssh.com") !== -1; - } else { - self2._strictMode = serverList.indexOf("kex-strict-s-v00@openssh.com") !== -1; - } - if (self2._strictMode) { - debug2 && debug2("Handshake: strict KEX mode enabled"); - if (self2._decipher.inSeqno !== 1) { - if (debug2) - debug2("Handshake: KEXINIT not first packet in strict KEX mode"); - return doFatalError( - self2, - "Handshake failed: KEXINIT not first packet in strict KEX mode", - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - } - } - for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i) ; - if (i === clientList.length) { - debug2 && debug2("Handshake: no matching key exchange algorithm"); - return doFatalError( - self2, - "Handshake failed: no matching key exchange algorithm", - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.kex = clientList[i]; - debug2 && debug2(`Handshake: KEX algorithm: ${clientList[i]}`); - if (firstFollows && (!remote.kex.length || clientList[i] !== remote.kex[0])) { - self2._skipNextInboundPacket = true; - } - const localSrvHostKey = local.lists.serverHostKey.array; - debug2 && debug2(`Handshake: (local) Host key format: ${localSrvHostKey}`); - debug2 && debug2( - `Handshake: (remote) Host key format: ${remote.serverHostKey}` - ); - if (self2._server) { - serverList = localSrvHostKey; - clientList = remote.serverHostKey; - } else { - serverList = remote.serverHostKey; - clientList = localSrvHostKey; - } - for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i) ; - if (i === clientList.length) { - debug2 && debug2("Handshake: No matching host key format"); - return doFatalError( - self2, - "Handshake failed: no matching host key format", - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.serverHostKey = clientList[i]; - debug2 && debug2(`Handshake: Host key format: ${clientList[i]}`); - const localCSCipher = local.lists.cs.cipher.array; - debug2 && debug2(`Handshake: (local) C->S cipher: ${localCSCipher}`); - debug2 && debug2(`Handshake: (remote) C->S cipher: ${remote.cs.cipher}`); - if (self2._server) { - serverList = localCSCipher; - clientList = remote.cs.cipher; - } else { - serverList = remote.cs.cipher; - clientList = localCSCipher; - } - for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i) ; - if (i === clientList.length) { - debug2 && debug2("Handshake: No matching C->S cipher"); - return doFatalError( - self2, - "Handshake failed: no matching C->S cipher", - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.cs.cipher = clientList[i]; - debug2 && debug2(`Handshake: C->S Cipher: ${clientList[i]}`); - const localSCCipher = local.lists.sc.cipher.array; - debug2 && debug2(`Handshake: (local) S->C cipher: ${localSCCipher}`); - debug2 && debug2(`Handshake: (remote) S->C cipher: ${remote.sc.cipher}`); - if (self2._server) { - serverList = localSCCipher; - clientList = remote.sc.cipher; - } else { - serverList = remote.sc.cipher; - clientList = localSCCipher; - } - for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i) ; - if (i === clientList.length) { - debug2 && debug2("Handshake: No matching S->C cipher"); - return doFatalError( - self2, - "Handshake failed: no matching S->C cipher", - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.sc.cipher = clientList[i]; - debug2 && debug2(`Handshake: S->C cipher: ${clientList[i]}`); - const localCSMAC = local.lists.cs.mac.array; - debug2 && debug2(`Handshake: (local) C->S MAC: ${localCSMAC}`); - debug2 && debug2(`Handshake: (remote) C->S MAC: ${remote.cs.mac}`); - if (CIPHER_INFO[init.cs.cipher].authLen > 0) { - init.cs.mac = ""; - debug2 && debug2("Handshake: C->S MAC: "); - } else { - if (self2._server) { - serverList = localCSMAC; - clientList = remote.cs.mac; - } else { - serverList = remote.cs.mac; - clientList = localCSMAC; - } - for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i) ; - if (i === clientList.length) { - debug2 && debug2("Handshake: No matching C->S MAC"); - return doFatalError( - self2, - "Handshake failed: no matching C->S MAC", - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.cs.mac = clientList[i]; - debug2 && debug2(`Handshake: C->S MAC: ${clientList[i]}`); - } - const localSCMAC = local.lists.sc.mac.array; - debug2 && debug2(`Handshake: (local) S->C MAC: ${localSCMAC}`); - debug2 && debug2(`Handshake: (remote) S->C MAC: ${remote.sc.mac}`); - if (CIPHER_INFO[init.sc.cipher].authLen > 0) { - init.sc.mac = ""; - debug2 && debug2("Handshake: S->C MAC: "); - } else { - if (self2._server) { - serverList = localSCMAC; - clientList = remote.sc.mac; - } else { - serverList = remote.sc.mac; - clientList = localSCMAC; - } - for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i) ; - if (i === clientList.length) { - debug2 && debug2("Handshake: No matching S->C MAC"); - return doFatalError( - self2, - "Handshake failed: no matching S->C MAC", - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.sc.mac = clientList[i]; - debug2 && debug2(`Handshake: S->C MAC: ${clientList[i]}`); - } - const localCSCompress = local.lists.cs.compress.array; - debug2 && debug2(`Handshake: (local) C->S compression: ${localCSCompress}`); - debug2 && debug2(`Handshake: (remote) C->S compression: ${remote.cs.compress}`); - if (self2._server) { - serverList = localCSCompress; - clientList = remote.cs.compress; - } else { - serverList = remote.cs.compress; - clientList = localCSCompress; - } - for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i) ; - if (i === clientList.length) { - debug2 && debug2("Handshake: No matching C->S compression"); - return doFatalError( - self2, - "Handshake failed: no matching C->S compression", - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.cs.compress = clientList[i]; - debug2 && debug2(`Handshake: C->S compression: ${clientList[i]}`); - const localSCCompress = local.lists.sc.compress.array; - debug2 && debug2(`Handshake: (local) S->C compression: ${localSCCompress}`); - debug2 && debug2(`Handshake: (remote) S->C compression: ${remote.sc.compress}`); - if (self2._server) { - serverList = localSCCompress; - clientList = remote.sc.compress; - } else { - serverList = remote.sc.compress; - clientList = localSCCompress; - } - for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i) ; - if (i === clientList.length) { - debug2 && debug2("Handshake: No matching S->C compression"); - return doFatalError( - self2, - "Handshake failed: no matching S->C compression", - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.sc.compress = clientList[i]; - debug2 && debug2(`Handshake: S->C compression: ${clientList[i]}`); - init.cs.lang = ""; - init.sc.lang = ""; - if (self2._kex) { - if (!self2._kexinit) { - kexinit(self2); - } - self2._decipher._onPayload = onKEXPayload.bind(self2, { firstPacket: false }); - } - self2._kex = createKeyExchange(init, self2, payload); - self2._kex.remoteExtInfoEnabled = remoteExtInfoEnabled; - self2._kex.start(); - } - var createKeyExchange = /* @__PURE__ */ (() => { - function convertToMpint(buf) { - let idx = 0; - let length = buf.length; - while (buf[idx] === 0) { - ++idx; - --length; - } - let newBuf; - if (buf[idx] & 128) { - newBuf = Buffer.allocUnsafe(1 + length); - newBuf[0] = 0; - buf.copy(newBuf, 1, idx); - buf = newBuf; - } else if (length !== buf.length) { - newBuf = Buffer.allocUnsafe(length); - buf.copy(newBuf, 0, idx); - buf = newBuf; - } - return buf; - } - class KeyExchange { - constructor(negotiated, protocol, remoteKexinit) { - this._protocol = protocol; - this.sessionID = protocol._kex ? protocol._kex.sessionID : void 0; - this.negotiated = negotiated; - this.remoteExtInfoEnabled = false; - this._step = 1; - this._public = null; - this._dh = null; - this._sentNEWKEYS = false; - this._receivedNEWKEYS = false; - this._finished = false; - this._hostVerified = false; - this._kexinit = protocol._kexinit; - this._remoteKexinit = remoteKexinit; - this._identRaw = protocol._identRaw; - this._remoteIdentRaw = protocol._remoteIdentRaw; - this._hostKey = void 0; - this._dhData = void 0; - this._sig = void 0; - } - finish(scOnly) { - if (this._finished) - return false; - this._finished = true; - const isServer = this._protocol._server; - const negotiated = this.negotiated; - const pubKey = this.convertPublicKey(this._dhData); - let secret = this.computeSecret(this._dhData); - if (secret instanceof Error) { - secret.message = `Error while computing DH secret (${this.type}): ${secret.message}`; - secret.level = "handshake"; - return doFatalError( - this._protocol, - secret, - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - const hash = createHash(this.hashName); - hashString(hash, isServer ? this._remoteIdentRaw : this._identRaw); - hashString(hash, isServer ? this._identRaw : this._remoteIdentRaw); - hashString(hash, isServer ? this._remoteKexinit : this._kexinit); - hashString(hash, isServer ? this._kexinit : this._remoteKexinit); - const serverPublicHostKey = isServer ? this._hostKey.getPublicSSH() : this._hostKey; - hashString(hash, serverPublicHostKey); - if (this.type === "groupex") { - const params = this.getDHParams(); - const num = Buffer.allocUnsafe(4); - writeUInt32BE(num, this._minBits, 0); - hash.update(num); - writeUInt32BE(num, this._prefBits, 0); - hash.update(num); - writeUInt32BE(num, this._maxBits, 0); - hash.update(num); - hashString(hash, params.prime); - hashString(hash, params.generator); - } - hashString(hash, isServer ? pubKey : this.getPublicKey()); - const serverPublicKey = isServer ? this.getPublicKey() : pubKey; - hashString(hash, serverPublicKey); - hashString(hash, secret); - const exchangeHash = hash.digest(); - if (!isServer) { - bufferParser.init(this._sig, 0); - const sigType = bufferParser.readString(true); - if (!sigType) { - return doFatalError( - this._protocol, - "Malformed packet while reading signature", - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - if (sigType !== negotiated.serverHostKey) { - return doFatalError( - this._protocol, - `Wrong signature type: ${sigType}, expected: ${negotiated.serverHostKey}`, - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - let sigValue = bufferParser.readString(); - bufferParser.clear(); - if (sigValue === void 0) { - return doFatalError( - this._protocol, - "Malformed packet while reading signature", - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - if (!(sigValue = sigSSHToASN1(sigValue, sigType))) { - return doFatalError( - this._protocol, - "Malformed signature", - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - let parsedHostKey; - { - bufferParser.init(this._hostKey, 0); - const name = bufferParser.readString(true); - const hostKey = this._hostKey.slice(bufferParser.pos()); - bufferParser.clear(); - parsedHostKey = parseDERKey(hostKey, name); - if (parsedHostKey instanceof Error) { - parsedHostKey.level = "handshake"; - return doFatalError( - this._protocol, - parsedHostKey, - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - } - let hashAlgo; - switch (this.negotiated.serverHostKey) { - case "rsa-sha2-256": - hashAlgo = "sha256"; - break; - case "rsa-sha2-512": - hashAlgo = "sha512"; - break; - } - this._protocol._debug && this._protocol._debug("Verifying signature ..."); - const verified = parsedHostKey.verify(exchangeHash, sigValue, hashAlgo); - if (verified !== true) { - if (verified instanceof Error) { - this._protocol._debug && this._protocol._debug( - `Signature verification failed: ${verified.stack}` - ); - } else { - this._protocol._debug && this._protocol._debug( - "Signature verification failed" - ); - } - return doFatalError( - this._protocol, - "Handshake failed: signature verification failed", - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug("Verified signature"); - } else { - let hashAlgo; - switch (this.negotiated.serverHostKey) { - case "rsa-sha2-256": - hashAlgo = "sha256"; - break; - case "rsa-sha2-512": - hashAlgo = "sha512"; - break; - } - this._protocol._debug && this._protocol._debug( - "Generating signature ..." - ); - let signature = this._hostKey.sign(exchangeHash, hashAlgo); - if (signature instanceof Error) { - return doFatalError( - this._protocol, - `Handshake failed: signature generation failed for ${this._hostKey.type} host key: ${signature.message}`, - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - signature = convertSignature(signature, this._hostKey.type); - if (signature === false) { - return doFatalError( - this._protocol, - `Handshake failed: signature conversion failed for ${this._hostKey.type} host key`, - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - const sigType = this.negotiated.serverHostKey; - const sigTypeLen = Buffer.byteLength(sigType); - const sigLen = 4 + sigTypeLen + 4 + signature.length; - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = this._protocol._packetRW.write.alloc( - 1 + 4 + serverPublicHostKey.length + 4 + serverPublicKey.length + 4 + sigLen, - true - ); - packet[p] = MESSAGE.KEXDH_REPLY; - writeUInt32BE(packet, serverPublicHostKey.length, ++p); - packet.set(serverPublicHostKey, p += 4); - writeUInt32BE( - packet, - serverPublicKey.length, - p += serverPublicHostKey.length - ); - packet.set(serverPublicKey, p += 4); - writeUInt32BE(packet, sigLen, p += serverPublicKey.length); - writeUInt32BE(packet, sigTypeLen, p += 4); - packet.utf8Write(sigType, p += 4, sigTypeLen); - writeUInt32BE(packet, signature.length, p += sigTypeLen); - packet.set(signature, p += 4); - if (this._protocol._debug) { - let type; - switch (this.type) { - case "group": - type = "KEXDH_REPLY"; - break; - case "groupex": - type = "KEXDH_GEX_REPLY"; - break; - default: - type = "KEXECDH_REPLY"; - } - this._protocol._debug(`Outbound: Sending ${type}`); - } - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); - } - if (isServer || !scOnly) - trySendNEWKEYS(this); - let hsCipherConfig; - let hsWrite; - const completeHandshake = (partial) => { - if (hsCipherConfig) { - trySendNEWKEYS(this); - hsCipherConfig.outbound.seqno = this._protocol._cipher.outSeqno; - this._protocol._cipher.free(); - this._protocol._cipher = createCipher(hsCipherConfig); - this._protocol._packetRW.write = hsWrite; - hsCipherConfig = void 0; - hsWrite = void 0; - this._protocol._onHandshakeComplete(negotiated); - return false; - } - if (!this.sessionID) - this.sessionID = exchangeHash; - { - const newSecret = Buffer.allocUnsafe(4 + secret.length); - writeUInt32BE(newSecret, secret.length, 0); - newSecret.set(secret, 4); - secret = newSecret; - } - const csCipherInfo = CIPHER_INFO[negotiated.cs.cipher]; - const scCipherInfo = CIPHER_INFO[negotiated.sc.cipher]; - const csIV = generateKEXVal( - csCipherInfo.ivLen, - this.hashName, - secret, - exchangeHash, - this.sessionID, - "A" - ); - const scIV = generateKEXVal( - scCipherInfo.ivLen, - this.hashName, - secret, - exchangeHash, - this.sessionID, - "B" - ); - const csKey = generateKEXVal( - csCipherInfo.keyLen, - this.hashName, - secret, - exchangeHash, - this.sessionID, - "C" - ); - const scKey = generateKEXVal( - scCipherInfo.keyLen, - this.hashName, - secret, - exchangeHash, - this.sessionID, - "D" - ); - let csMacInfo; - let csMacKey; - if (!csCipherInfo.authLen) { - csMacInfo = MAC_INFO[negotiated.cs.mac]; - csMacKey = generateKEXVal( - csMacInfo.len, - this.hashName, - secret, - exchangeHash, - this.sessionID, - "E" - ); - } - let scMacInfo; - let scMacKey; - if (!scCipherInfo.authLen) { - scMacInfo = MAC_INFO[negotiated.sc.mac]; - scMacKey = generateKEXVal( - scMacInfo.len, - this.hashName, - secret, - exchangeHash, - this.sessionID, - "F" - ); - } - const config = { - inbound: { - onPayload: this._protocol._onPayload, - seqno: this._protocol._decipher.inSeqno, - decipherInfo: !isServer ? scCipherInfo : csCipherInfo, - decipherIV: !isServer ? scIV : csIV, - decipherKey: !isServer ? scKey : csKey, - macInfo: !isServer ? scMacInfo : csMacInfo, - macKey: !isServer ? scMacKey : csMacKey - }, - outbound: { - onWrite: this._protocol._onWrite, - seqno: this._protocol._cipher.outSeqno, - cipherInfo: isServer ? scCipherInfo : csCipherInfo, - cipherIV: isServer ? scIV : csIV, - cipherKey: isServer ? scKey : csKey, - macInfo: isServer ? scMacInfo : csMacInfo, - macKey: isServer ? scMacKey : csMacKey - } - }; - this._protocol._decipher.free(); - hsCipherConfig = config; - this._protocol._decipher = createDecipher(config); - const rw = { - read: void 0, - write: void 0 - }; - switch (negotiated.cs.compress) { - case "zlib": - if (isServer) - rw.read = new ZlibPacketReader(); - else - rw.write = new ZlibPacketWriter(this._protocol); - break; - case "zlib@openssh.com": - if (this._protocol._authenticated) { - if (isServer) - rw.read = new ZlibPacketReader(); - else - rw.write = new ZlibPacketWriter(this._protocol); - break; - } - // FALLTHROUGH - default: - if (isServer) - rw.read = new PacketReader(); - else - rw.write = new PacketWriter(this._protocol); - } - switch (negotiated.sc.compress) { - case "zlib": - if (isServer) - rw.write = new ZlibPacketWriter(this._protocol); - else - rw.read = new ZlibPacketReader(); - break; - case "zlib@openssh.com": - if (this._protocol._authenticated) { - if (isServer) - rw.write = new ZlibPacketWriter(this._protocol); - else - rw.read = new ZlibPacketReader(); - break; - } - // FALLTHROUGH - default: - if (isServer) - rw.write = new PacketWriter(this._protocol); - else - rw.read = new PacketReader(); - } - this._protocol._packetRW.read.cleanup(); - this._protocol._packetRW.write.cleanup(); - this._protocol._packetRW.read = rw.read; - hsWrite = rw.write; - this._public = null; - this._dh = null; - this._kexinit = this._protocol._kexinit = void 0; - this._remoteKexinit = void 0; - this._identRaw = void 0; - this._remoteIdentRaw = void 0; - this._hostKey = void 0; - this._dhData = void 0; - this._sig = void 0; - if (!partial) - return completeHandshake(); - return false; - }; - if (isServer || scOnly) - this.finish = completeHandshake; - if (!isServer) - return completeHandshake(scOnly); - } - start() { - if (!this._protocol._server) { - if (this._protocol._debug) { - let type; - switch (this.type) { - case "group": - type = "KEXDH_INIT"; - break; - default: - type = "KEXECDH_INIT"; - } - this._protocol._debug(`Outbound: Sending ${type}`); - } - const pubKey = this.getPublicKey(); - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = this._protocol._packetRW.write.alloc( - 1 + 4 + pubKey.length, - true - ); - packet[p] = MESSAGE.KEXDH_INIT; - writeUInt32BE(packet, pubKey.length, ++p); - packet.set(pubKey, p += 4); - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); - } - } - getPublicKey() { - this.generateKeys(); - const key = this._public; - if (key) - return this.convertPublicKey(key); - } - convertPublicKey(key) { - let newKey; - let idx = 0; - let len = key.length; - while (key[idx] === 0) { - ++idx; - --len; - } - if (key[idx] & 128) { - newKey = Buffer.allocUnsafe(1 + len); - newKey[0] = 0; - key.copy(newKey, 1, idx); - return newKey; - } - if (len !== key.length) { - newKey = Buffer.allocUnsafe(len); - key.copy(newKey, 0, idx); - key = newKey; - } - return key; - } - computeSecret(otherPublicKey) { - this.generateKeys(); - try { - return convertToMpint(this._dh.computeSecret(otherPublicKey)); - } catch (ex) { - return ex; - } - } - parse(payload) { - const type = payload[0]; - switch (this._step) { - case 1: - if (this._protocol._server) { - if (type !== MESSAGE.KEXDH_INIT) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_INIT}`, - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - "Received DH Init" - ); - bufferParser.init(payload, 1); - const dhData = bufferParser.readString(); - bufferParser.clear(); - if (dhData === void 0) { - return doFatalError( - this._protocol, - "Received malformed KEX*_INIT", - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._dhData = dhData; - let hostKey = this._protocol._hostKeys[this.negotiated.serverHostKey]; - if (Array.isArray(hostKey)) - hostKey = hostKey[0]; - this._hostKey = hostKey; - this.finish(); - } else { - if (type !== MESSAGE.KEXDH_REPLY) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_REPLY}`, - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - "Received DH Reply" - ); - bufferParser.init(payload, 1); - let hostPubKey; - let dhData; - let sig; - if ((hostPubKey = bufferParser.readString()) === void 0 || (dhData = bufferParser.readString()) === void 0 || (sig = bufferParser.readString()) === void 0) { - bufferParser.clear(); - return doFatalError( - this._protocol, - "Received malformed KEX*_REPLY", - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - bufferParser.clear(); - bufferParser.init(hostPubKey, 0); - const hostPubKeyType = bufferParser.readString(true); - bufferParser.clear(); - if (hostPubKeyType === void 0) { - return doFatalError( - this._protocol, - "Received malformed host public key", - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - if (hostPubKeyType !== this.negotiated.serverHostKey) { - switch (this.negotiated.serverHostKey) { - case "rsa-sha2-256": - case "rsa-sha2-512": - if (hostPubKeyType === "ssh-rsa") - break; - // FALLTHROUGH - default: - return doFatalError( - this._protocol, - "Host key does not match negotiated type", - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - } - this._hostKey = hostPubKey; - this._dhData = dhData; - this._sig = sig; - let checked = false; - let ret; - if (this._protocol._hostVerifier === void 0) { - ret = true; - this._protocol._debug && this._protocol._debug( - "Host accepted by default (no verification)" - ); - } else { - ret = this._protocol._hostVerifier(hostPubKey, (permitted) => { - if (checked) - return; - checked = true; - if (permitted === false) { - this._protocol._debug && this._protocol._debug( - "Host denied (verification failed)" - ); - return doFatalError( - this._protocol, - "Host denied (verification failed)", - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - "Host accepted (verified)" - ); - this._hostVerified = true; - if (this._receivedNEWKEYS) - this.finish(); - else - trySendNEWKEYS(this); - }); - } - if (ret === void 0) { - ++this._step; - return; - } - checked = true; - if (ret === false) { - this._protocol._debug && this._protocol._debug( - "Host denied (verification failed)" - ); - return doFatalError( - this._protocol, - "Host denied (verification failed)", - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - "Host accepted (verified)" - ); - this._hostVerified = true; - trySendNEWKEYS(this); - } - ++this._step; - break; - case 2: - if (type !== MESSAGE.NEWKEYS) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.NEWKEYS}`, - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - "Inbound: NEWKEYS" - ); - this._receivedNEWKEYS = true; - if (this._protocol._strictMode) - this._protocol._decipher.inSeqno = 0; - ++this._step; - return this.finish(!this._protocol._server && !this._hostVerified); - default: - return doFatalError( - this._protocol, - `Received unexpected packet ${type} after NEWKEYS`, - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - } - } - class Curve25519Exchange extends KeyExchange { - constructor(hashName, ...args) { - super(...args); - this.type = "25519"; - this.hashName = hashName; - this._keys = null; - } - generateKeys() { - if (!this._keys) - this._keys = generateKeyPairSync("x25519"); - } - getPublicKey() { - this.generateKeys(); - const key = this._keys.publicKey.export({ type: "spki", format: "der" }); - return key.slice(-32); - } - convertPublicKey(key) { - let newKey; - let idx = 0; - let len = key.length; - while (key[idx] === 0) { - ++idx; - --len; - } - if (key.length === 32) - return key; - if (len !== key.length) { - newKey = Buffer.allocUnsafe(len); - key.copy(newKey, 0, idx); - key = newKey; - } - return key; - } - computeSecret(otherPublicKey) { - this.generateKeys(); - try { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - asnWriter.startSequence(); - asnWriter.writeOID("1.3.101.110"); - asnWriter.endSequence(); - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0); - asnWriter._ensure(otherPublicKey.length); - otherPublicKey.copy( - asnWriter._buf, - asnWriter._offset, - 0, - otherPublicKey.length - ); - asnWriter._offset += otherPublicKey.length; - asnWriter.endSequence(); - asnWriter.endSequence(); - return convertToMpint(diffieHellman({ - privateKey: this._keys.privateKey, - publicKey: createPublicKey({ - key: asnWriter.buffer, - type: "spki", - format: "der" - }) - })); - } catch (ex) { - return ex; - } - } - } - class ECDHExchange extends KeyExchange { - constructor(curveName, hashName, ...args) { - super(...args); - this.type = "ecdh"; - this.curveName = curveName; - this.hashName = hashName; - } - generateKeys() { - if (!this._dh) { - this._dh = createECDH(this.curveName); - this._public = this._dh.generateKeys(); - } - } - } - class DHGroupExchange extends KeyExchange { - constructor(hashName, ...args) { - super(...args); - this.type = "groupex"; - this.hashName = hashName; - this._prime = null; - this._generator = null; - this._minBits = GEX_MIN_BITS; - this._prefBits = dhEstimate(this.negotiated); - if (this._protocol._compatFlags & COMPAT.BUG_DHGEX_LARGE) - this._prefBits = Math.min(this._prefBits, 4096); - this._maxBits = GEX_MAX_BITS; - } - start() { - if (this._protocol._server) - return; - this._protocol._debug && this._protocol._debug( - "Outbound: Sending KEXDH_GEX_REQUEST" - ); - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = this._protocol._packetRW.write.alloc( - 1 + 4 + 4 + 4, - true - ); - packet[p] = MESSAGE.KEXDH_GEX_REQUEST; - writeUInt32BE(packet, this._minBits, ++p); - writeUInt32BE(packet, this._prefBits, p += 4); - writeUInt32BE(packet, this._maxBits, p += 4); - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); - } - generateKeys() { - if (!this._dh && this._prime && this._generator) { - this._dh = createDiffieHellman(this._prime, this._generator); - this._public = this._dh.generateKeys(); - } - } - setDHParams(prime, generator) { - if (!Buffer.isBuffer(prime)) - throw new Error("Invalid prime value"); - if (!Buffer.isBuffer(generator)) - throw new Error("Invalid generator value"); - this._prime = prime; - this._generator = generator; - } - getDHParams() { - if (this._dh) { - return { - prime: convertToMpint(this._dh.getPrime()), - generator: convertToMpint(this._dh.getGenerator()) - }; - } - } - parse(payload) { - const type = payload[0]; - switch (this._step) { - case 1: { - if (this._protocol._server) { - if (type !== MESSAGE.KEXDH_GEX_REQUEST) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ` + MESSAGE.KEXDH_GEX_REQUEST, - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - return doFatalError( - this._protocol, - "Group exchange not implemented for server", - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - if (type !== MESSAGE.KEXDH_GEX_GROUP) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_GROUP}`, - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - "Received DH GEX Group" - ); - bufferParser.init(payload, 1); - let prime; - let gen; - if ((prime = bufferParser.readString()) === void 0 || (gen = bufferParser.readString()) === void 0) { - bufferParser.clear(); - return doFatalError( - this._protocol, - "Received malformed KEXDH_GEX_GROUP", - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - bufferParser.clear(); - this.setDHParams(prime, gen); - this.generateKeys(); - const pubkey = this.getPublicKey(); - this._protocol._debug && this._protocol._debug( - "Outbound: Sending KEXDH_GEX_INIT" - ); - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = this._protocol._packetRW.write.alloc(1 + 4 + pubkey.length, true); - packet[p] = MESSAGE.KEXDH_GEX_INIT; - writeUInt32BE(packet, pubkey.length, ++p); - packet.set(pubkey, p += 4); - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); - ++this._step; - break; - } - case 2: - if (this._protocol._server) { - if (type !== MESSAGE.KEXDH_GEX_INIT) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_INIT}`, - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - "Received DH GEX Init" - ); - return doFatalError( - this._protocol, - "Group exchange not implemented for server", - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } else if (type !== MESSAGE.KEXDH_GEX_REPLY) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_REPLY}`, - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - "Received DH GEX Reply" - ); - this._step = 1; - payload[0] = MESSAGE.KEXDH_REPLY; - this.parse = KeyExchange.prototype.parse; - this.parse(payload); - } - } - } - class DHExchange extends KeyExchange { - constructor(groupName, hashName, ...args) { - super(...args); - this.type = "group"; - this.groupName = groupName; - this.hashName = hashName; - } - start() { - if (!this._protocol._server) { - this._protocol._debug && this._protocol._debug( - "Outbound: Sending KEXDH_INIT" - ); - const pubKey = this.getPublicKey(); - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = this._protocol._packetRW.write.alloc(1 + 4 + pubKey.length, true); - packet[p] = MESSAGE.KEXDH_INIT; - writeUInt32BE(packet, pubKey.length, ++p); - packet.set(pubKey, p += 4); - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); - } - } - generateKeys() { - if (!this._dh) { - this._dh = createDiffieHellmanGroup(this.groupName); - this._public = this._dh.generateKeys(); - } - } - getDHParams() { - if (this._dh) { - return { - prime: convertToMpint(this._dh.getPrime()), - generator: convertToMpint(this._dh.getGenerator()) - }; - } - } - } - return (negotiated, ...args) => { - if (typeof negotiated !== "object" || negotiated === null) - throw new Error("Invalid negotiated argument"); - const kexType = negotiated.kex; - if (typeof kexType === "string") { - args = [negotiated, ...args]; - switch (kexType) { - case "curve25519-sha256": - case "curve25519-sha256@libssh.org": - if (!curve25519Supported) - break; - return new Curve25519Exchange("sha256", ...args); - case "ecdh-sha2-nistp256": - return new ECDHExchange("prime256v1", "sha256", ...args); - case "ecdh-sha2-nistp384": - return new ECDHExchange("secp384r1", "sha384", ...args); - case "ecdh-sha2-nistp521": - return new ECDHExchange("secp521r1", "sha512", ...args); - case "diffie-hellman-group1-sha1": - return new DHExchange("modp2", "sha1", ...args); - case "diffie-hellman-group14-sha1": - return new DHExchange("modp14", "sha1", ...args); - case "diffie-hellman-group14-sha256": - return new DHExchange("modp14", "sha256", ...args); - case "diffie-hellman-group15-sha512": - return new DHExchange("modp15", "sha512", ...args); - case "diffie-hellman-group16-sha512": - return new DHExchange("modp16", "sha512", ...args); - case "diffie-hellman-group17-sha512": - return new DHExchange("modp17", "sha512", ...args); - case "diffie-hellman-group18-sha512": - return new DHExchange("modp18", "sha512", ...args); - case "diffie-hellman-group-exchange-sha1": - return new DHGroupExchange("sha1", ...args); - case "diffie-hellman-group-exchange-sha256": - return new DHGroupExchange("sha256", ...args); - } - throw new Error(`Unsupported key exchange algorithm: ${kexType}`); - } - throw new Error(`Invalid key exchange type: ${kexType}`); - }; - })(); - var KexInit = /* @__PURE__ */ (() => { - const KEX_PROPERTY_NAMES = [ - "kex", - "serverHostKey", - ["cs", "cipher"], - ["sc", "cipher"], - ["cs", "mac"], - ["sc", "mac"], - ["cs", "compress"], - ["sc", "compress"], - ["cs", "lang"], - ["sc", "lang"] - ]; - return class KexInit { - constructor(obj) { - if (typeof obj !== "object" || obj === null) - throw new TypeError("Argument must be an object"); - const lists = { - kex: void 0, - serverHostKey: void 0, - cs: { - cipher: void 0, - mac: void 0, - compress: void 0, - lang: void 0 - }, - sc: { - cipher: void 0, - mac: void 0, - compress: void 0, - lang: void 0 - }, - all: void 0 - }; - let totalSize = 0; - for (const prop of KEX_PROPERTY_NAMES) { - let base; - let val; - let desc; - let key; - if (typeof prop === "string") { - base = lists; - val = obj[prop]; - desc = key = prop; - } else { - const parent = prop[0]; - base = lists[parent]; - key = prop[1]; - val = obj[parent][key]; - desc = `${parent}.${key}`; - } - const entry = { array: void 0, buffer: void 0 }; - if (Buffer.isBuffer(val)) { - entry.array = ("" + val).split(","); - entry.buffer = val; - totalSize += 4 + val.length; - } else { - if (typeof val === "string") - val = val.split(","); - if (Array.isArray(val)) { - entry.array = val; - entry.buffer = Buffer.from(val.join(",")); - } else { - throw new TypeError(`Invalid \`${desc}\` type: ${typeof val}`); - } - totalSize += 4 + entry.buffer.length; - } - base[key] = entry; - } - const all = Buffer.allocUnsafe(totalSize); - lists.all = all; - let allPos = 0; - for (const prop of KEX_PROPERTY_NAMES) { - let data; - if (typeof prop === "string") - data = lists[prop].buffer; - else - data = lists[prop[0]][prop[1]].buffer; - allPos = writeUInt32BE(all, data.length, allPos); - all.set(data, allPos); - allPos += data.length; - } - this.totalSize = totalSize; - this.lists = lists; - } - copyAllTo(buf, offset) { - const src = this.lists.all; - if (typeof offset !== "number") - throw new TypeError(`Invalid offset value: ${typeof offset}`); - if (buf.length - offset < src.length) - throw new Error("Insufficient space to copy list"); - buf.set(src, offset); - return src.length; - } - }; - })(); - var hashString = (() => { - const LEN = Buffer.allocUnsafe(4); - return (hash, buf) => { - writeUInt32BE(LEN, buf.length, 0); - hash.update(LEN); - hash.update(buf); - }; - })(); - function generateKEXVal(len, hashName, secret, exchangeHash, sessionID, char) { - let ret; - if (len) { - let digest = createHash(hashName).update(secret).update(exchangeHash).update(char).update(sessionID).digest(); - while (digest.length < len) { - const chunk = createHash(hashName).update(secret).update(exchangeHash).update(digest).digest(); - const extended = Buffer.allocUnsafe(digest.length + chunk.length); - extended.set(digest, 0); - extended.set(chunk, digest.length); - digest = extended; - } - if (digest.length === len) - ret = digest; - else - ret = new FastBuffer(digest.buffer, digest.byteOffset, len); - } else { - ret = EMPTY_BUFFER; - } - return ret; - } - function onKEXPayload(state, payload) { - if (payload.length === 0) { - this._debug && this._debug("Inbound: Skipping empty packet payload"); - return; - } - if (this._skipNextInboundPacket) { - this._skipNextInboundPacket = false; - return; - } - payload = this._packetRW.read.read(payload); - const type = payload[0]; - if (!this._strictMode) { - switch (type) { - case MESSAGE.IGNORE: - case MESSAGE.UNIMPLEMENTED: - case MESSAGE.DEBUG: - if (!MESSAGE_HANDLERS) - MESSAGE_HANDLERS = require_handlers(); - return MESSAGE_HANDLERS[type](this, payload); - } - } - switch (type) { - case MESSAGE.DISCONNECT: - if (!MESSAGE_HANDLERS) - MESSAGE_HANDLERS = require_handlers(); - return MESSAGE_HANDLERS[type](this, payload); - case MESSAGE.KEXINIT: - if (!state.firstPacket) { - return doFatalError( - this, - "Received extra KEXINIT during handshake", - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - state.firstPacket = false; - return handleKexInit(this, payload); - default: - if (type < 20 || type > 49) { - return doFatalError( - this, - `Received unexpected packet type ${type}`, - "handshake", - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - } - return this._kex.parse(payload); - } - function dhEstimate(neg) { - const csCipher = CIPHER_INFO[neg.cs.cipher]; - const scCipher = CIPHER_INFO[neg.sc.cipher]; - const bits = Math.max( - 0, - csCipher.sslName === "des-ede3-cbc" ? 14 : csCipher.keyLen, - csCipher.blockLen, - csCipher.ivLen, - scCipher.sslName === "des-ede3-cbc" ? 14 : scCipher.keyLen, - scCipher.blockLen, - scCipher.ivLen - ) * 8; - if (bits <= 112) - return 2048; - if (bits <= 128) - return 3072; - if (bits <= 192) - return 7680; - return 8192; - } - function trySendNEWKEYS(kex) { - if (!kex._sentNEWKEYS) { - kex._protocol._debug && kex._protocol._debug( - "Outbound: Sending NEWKEYS" - ); - const p = kex._protocol._packetRW.write.allocStartKEX; - const packet = kex._protocol._packetRW.write.alloc(1, true); - packet[p] = MESSAGE.NEWKEYS; - kex._protocol._cipher.encrypt( - kex._protocol._packetRW.write.finalize(packet, true) - ); - kex._sentNEWKEYS = true; - if (kex._protocol._strictMode) - kex._protocol._cipher.outSeqno = 0; - } - } - module2.exports = { - KexInit, - kexinit, - onKEXPayload, - DEFAULT_KEXINIT_CLIENT: new KexInit({ - kex: DEFAULT_KEX.concat(["ext-info-c", "kex-strict-c-v00@openssh.com"]), - serverHostKey: DEFAULT_SERVER_HOST_KEY, - cs: { - cipher: DEFAULT_CIPHER, - mac: DEFAULT_MAC, - compress: DEFAULT_COMPRESSION, - lang: [] - }, - sc: { - cipher: DEFAULT_CIPHER, - mac: DEFAULT_MAC, - compress: DEFAULT_COMPRESSION, - lang: [] - } - }), - DEFAULT_KEXINIT_SERVER: new KexInit({ - kex: DEFAULT_KEX.concat(["kex-strict-s-v00@openssh.com"]), - serverHostKey: DEFAULT_SERVER_HOST_KEY, - cs: { - cipher: DEFAULT_CIPHER, - mac: DEFAULT_MAC, - compress: DEFAULT_COMPRESSION, - lang: [] - }, - sc: { - cipher: DEFAULT_CIPHER, - mac: DEFAULT_MAC, - compress: DEFAULT_COMPRESSION, - lang: [] - } - }), - HANDLERS: { - [MESSAGE.KEXINIT]: handleKexInit - } - }; - } -}); - -// node_modules/ssh2/package.json -var require_package = __commonJS({ - "node_modules/ssh2/package.json"(exports2, module2) { - module2.exports = { - name: "ssh2", - version: "1.17.0", - author: "Brian White ", - description: "SSH2 client and server modules written in pure JavaScript for node.js", - main: "./lib/index.js", - engines: { - node: ">=10.16.0" - }, - dependencies: { - asn1: "^0.2.6", - "bcrypt-pbkdf": "^1.0.2" - }, - devDependencies: { - "@mscdex/eslint-config": "^1.1.0", - eslint: "^7.32.0" - }, - optionalDependencies: { - "cpu-features": "~0.0.10", - nan: "^2.23.0" - }, - scripts: { - install: "node install.js", - rebuild: "node install.js", - test: "node test/test.js", - lint: "eslint --cache --report-unused-disable-directives --ext=.js .eslintrc.js examples lib test", - "lint:fix": "npm run lint -- --fix" - }, - keywords: [ - "ssh", - "ssh2", - "sftp", - "secure", - "shell", - "exec", - "remote", - "client" - ], - licenses: [ - { - type: "MIT", - url: "http://github.com/mscdex/ssh2/raw/master/LICENSE" - } - ], - repository: { - type: "git", - url: "http://github.com/mscdex/ssh2.git" - } - }; - } -}); - -// node_modules/ssh2/lib/protocol/Protocol.js -var require_Protocol = __commonJS({ - "node_modules/ssh2/lib/protocol/Protocol.js"(exports2, module2) { - "use strict"; - var { inspect } = require("util"); - var { bindingAvailable, NullCipher, NullDecipher } = require_crypto(); - var { - COMPAT_CHECKS, - DISCONNECT_REASON, - eddsaSupported, - MESSAGE, - SIGNALS, - TERMINAL_MODE - } = require_constants6(); - var { - DEFAULT_KEXINIT_CLIENT, - DEFAULT_KEXINIT_SERVER, - KexInit, - kexinit, - onKEXPayload - } = require_kex(); - var { - parseKey - } = require_keyParser(); - var MESSAGE_HANDLERS = require_handlers(); - var { - bufferCopy, - bufferFill, - bufferSlice, - convertSignature, - sendPacket, - writeUInt32BE - } = require_utils4(); - var { - PacketReader, - PacketWriter, - ZlibPacketReader, - ZlibPacketWriter - } = require_zlib(); - var MODULE_VER = require_package().version; - var VALID_DISCONNECT_REASONS = new Map( - Object.values(DISCONNECT_REASON).map((n) => [n, 1]) - ); - var IDENT_RAW = Buffer.from(`SSH-2.0-ssh2js${MODULE_VER}`); - var IDENT = Buffer.from(`${IDENT_RAW}\r -`); - var MAX_LINE_LEN = 8192; - var MAX_LINES = 1024; - var PING_PAYLOAD = Buffer.from([ - MESSAGE.GLOBAL_REQUEST, - // "keepalive@openssh.com" - 0, - 0, - 0, - 21, - 107, - 101, - 101, - 112, - 97, - 108, - 105, - 118, - 101, - 64, - 111, - 112, - 101, - 110, - 115, - 115, - 104, - 46, - 99, - 111, - 109, - // Request a reply - 1 - ]); - var NO_TERMINAL_MODES_BUFFER = Buffer.from([TERMINAL_MODE.TTY_OP_END]); - function noop3() { - } - var Protocol = class { - constructor(config) { - const onWrite = config.onWrite; - if (typeof onWrite !== "function") - throw new Error("Missing onWrite function"); - this._onWrite = (data) => { - onWrite(data); - }; - const onError = config.onError; - if (typeof onError !== "function") - throw new Error("Missing onError function"); - this._onError = (err) => { - onError(err); - }; - const debug2 = config.debug; - this._debug = typeof debug2 === "function" ? (msg) => { - debug2(msg); - } : void 0; - const onHeader = config.onHeader; - this._onHeader = typeof onHeader === "function" ? (...args) => { - onHeader(...args); - } : noop3; - const onPacket = config.onPacket; - this._onPacket = typeof onPacket === "function" ? () => { - onPacket(); - } : noop3; - let onHandshakeComplete = config.onHandshakeComplete; - if (typeof onHandshakeComplete !== "function") - onHandshakeComplete = noop3; - let firstHandshake; - this._onHandshakeComplete = (...args) => { - this._debug && this._debug("Handshake completed"); - if (firstHandshake === void 0) - firstHandshake = true; - else - firstHandshake = false; - const oldQueue = this._queue; - if (oldQueue) { - this._queue = void 0; - this._debug && this._debug( - `Draining outbound queue (${oldQueue.length}) ...` - ); - for (let i = 0; i < oldQueue.length; ++i) { - const data = oldQueue[i]; - let finalized = this._packetRW.write.finalize(data); - if (finalized === data) { - const packet = this._cipher.allocPacket(data.length); - packet.set(data, 5); - finalized = packet; - } - sendPacket(this, finalized); - } - this._debug && this._debug("... finished draining outbound queue"); - } - if (firstHandshake && this._server && this._kex.remoteExtInfoEnabled) - sendExtInfo(this); - onHandshakeComplete(...args); - }; - this._queue = void 0; - const messageHandlers = config.messageHandlers; - if (typeof messageHandlers === "object" && messageHandlers !== null) - this._handlers = messageHandlers; - else - this._handlers = {}; - this._onPayload = onPayload.bind(this); - this._server = !!config.server; - this._banner = void 0; - let greeting; - if (this._server) { - if (typeof config.hostKeys !== "object" || config.hostKeys === null) - throw new Error("Missing server host key(s)"); - this._hostKeys = config.hostKeys; - if (typeof config.greeting === "string" && config.greeting.length) { - greeting = config.greeting.slice(-2) === "\r\n" ? config.greeting : `${config.greeting}\r -`; - } - if (typeof config.banner === "string" && config.banner.length) { - this._banner = config.banner.slice(-2) === "\r\n" ? config.banner : `${config.banner}\r -`; - } - } else { - this._hostKeys = void 0; - } - let offer = config.offer; - if (typeof offer !== "object" || offer === null) { - offer = this._server ? DEFAULT_KEXINIT_SERVER : DEFAULT_KEXINIT_CLIENT; - } else if (offer.constructor !== KexInit) { - if (this._server) { - offer.kex = offer.kex.concat(["kex-strict-s-v00@openssh.com"]); - } else { - offer.kex = offer.kex.concat([ - "ext-info-c", - "kex-strict-c-v00@openssh.com" - ]); - } - offer = new KexInit(offer); - } - this._kex = void 0; - this._strictMode = void 0; - this._kexinit = void 0; - this._offer = offer; - this._cipher = new NullCipher(0, this._onWrite); - this._decipher = void 0; - this._skipNextInboundPacket = false; - this._packetRW = { - read: new PacketReader(), - write: new PacketWriter(this) - }; - this._hostVerifier = !this._server && typeof config.hostVerifier === "function" ? config.hostVerifier : void 0; - this._parse = parseHeader; - this._buffer = void 0; - this._authsQueue = []; - this._authenticated = false; - this._remoteIdentRaw = void 0; - let sentIdent; - if (typeof config.ident === "string") { - this._identRaw = Buffer.from(`SSH-2.0-${config.ident}`); - sentIdent = Buffer.allocUnsafe(this._identRaw.length + 2); - sentIdent.set(this._identRaw, 0); - sentIdent[sentIdent.length - 2] = 13; - sentIdent[sentIdent.length - 1] = 10; - } else if (Buffer.isBuffer(config.ident)) { - const fullIdent = Buffer.allocUnsafe(8 + config.ident.length); - fullIdent.latin1Write("SSH-2.0-", 0, 8); - fullIdent.set(config.ident, 8); - this._identRaw = fullIdent; - sentIdent = Buffer.allocUnsafe(fullIdent.length + 2); - sentIdent.set(fullIdent, 0); - sentIdent[sentIdent.length - 2] = 13; - sentIdent[sentIdent.length - 1] = 10; - } else { - this._identRaw = IDENT_RAW; - sentIdent = IDENT; - } - this._compatFlags = 0; - if (this._debug) { - if (bindingAvailable) - this._debug("Custom crypto binding available"); - else - this._debug("Custom crypto binding not available"); - } - this._debug && this._debug( - `Local ident: ${inspect(this._identRaw.toString())}` - ); - this.start = () => { - this.start = void 0; - if (greeting) - this._onWrite(greeting); - this._onWrite(sentIdent); - }; - } - _destruct(reason) { - this._packetRW.read.cleanup(); - this._packetRW.write.cleanup(); - this._cipher && this._cipher.free(); - this._decipher && this._decipher.free(); - if (typeof reason !== "string" || reason.length === 0) - reason = "fatal error"; - this.parse = () => { - throw new Error(`Instance unusable after ${reason}`); - }; - this._onWrite = () => { - throw new Error(`Instance unusable after ${reason}`); - }; - this._destruct = void 0; - } - cleanup() { - this._destruct && this._destruct(); - } - parse(chunk, i, len) { - while (i < len) - i = this._parse(chunk, i, len); - } - // Protocol message API - // =========================================================================== - // Common/Shared ============================================================= - // =========================================================================== - // Global - // ------ - disconnect(reason) { - const pktLen = 1 + 4 + 4 + 4; - let p = this._packetRW.write.allocStartKEX; - const packet = this._packetRW.write.alloc(pktLen, true); - const end = p + pktLen; - if (!VALID_DISCONNECT_REASONS.has(reason)) - reason = DISCONNECT_REASON.PROTOCOL_ERROR; - packet[p] = MESSAGE.DISCONNECT; - writeUInt32BE(packet, reason, ++p); - packet.fill(0, p += 4, end); - this._debug && this._debug(`Outbound: Sending DISCONNECT (${reason})`); - sendPacket(this, this._packetRW.write.finalize(packet, true), true); - } - ping() { - const p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(PING_PAYLOAD.length); - packet.set(PING_PAYLOAD, p); - this._debug && this._debug( - "Outbound: Sending ping (GLOBAL_REQUEST: keepalive@openssh.com)" - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - rekey() { - if (this._kexinit === void 0) { - this._debug && this._debug("Outbound: Initiated explicit rekey"); - this._queue = []; - kexinit(this); - } else { - this._debug && this._debug("Outbound: Ignoring rekey during handshake"); - } - } - // 'ssh-connection' service-specific - // --------------------------------- - requestSuccess(data) { - let p = this._packetRW.write.allocStart; - let packet; - if (Buffer.isBuffer(data)) { - packet = this._packetRW.write.alloc(1 + data.length); - packet[p] = MESSAGE.REQUEST_SUCCESS; - packet.set(data, ++p); - } else { - packet = this._packetRW.write.alloc(1); - packet[p] = MESSAGE.REQUEST_SUCCESS; - } - this._debug && this._debug("Outbound: Sending REQUEST_SUCCESS"); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - requestFailure() { - const p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1); - packet[p] = MESSAGE.REQUEST_FAILURE; - this._debug && this._debug("Outbound: Sending REQUEST_FAILURE"); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelSuccess(chan) { - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4); - packet[p] = MESSAGE.CHANNEL_SUCCESS; - writeUInt32BE(packet, chan, ++p); - this._debug && this._debug(`Outbound: Sending CHANNEL_SUCCESS (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelFailure(chan) { - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4); - packet[p] = MESSAGE.CHANNEL_FAILURE; - writeUInt32BE(packet, chan, ++p); - this._debug && this._debug(`Outbound: Sending CHANNEL_FAILURE (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelEOF(chan) { - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4); - packet[p] = MESSAGE.CHANNEL_EOF; - writeUInt32BE(packet, chan, ++p); - this._debug && this._debug(`Outbound: Sending CHANNEL_EOF (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelClose(chan) { - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4); - packet[p] = MESSAGE.CHANNEL_CLOSE; - writeUInt32BE(packet, chan, ++p); - this._debug && this._debug(`Outbound: Sending CHANNEL_CLOSE (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelWindowAdjust(chan, amount) { - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4); - packet[p] = MESSAGE.CHANNEL_WINDOW_ADJUST; - writeUInt32BE(packet, chan, ++p); - writeUInt32BE(packet, amount, p += 4); - this._debug && this._debug( - `Outbound: Sending CHANNEL_WINDOW_ADJUST (r:${chan}, ${amount})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelData(chan, data) { - const isBuffer = Buffer.isBuffer(data); - const dataLen = isBuffer ? data.length : Buffer.byteLength(data); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + dataLen); - packet[p] = MESSAGE.CHANNEL_DATA; - writeUInt32BE(packet, chan, ++p); - writeUInt32BE(packet, dataLen, p += 4); - if (isBuffer) - packet.set(data, p += 4); - else - packet.utf8Write(data, p += 4, dataLen); - this._debug && this._debug( - `Outbound: Sending CHANNEL_DATA (r:${chan}, ${dataLen})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelExtData(chan, data, type) { - const isBuffer = Buffer.isBuffer(data); - const dataLen = isBuffer ? data.length : Buffer.byteLength(data); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + dataLen); - packet[p] = MESSAGE.CHANNEL_EXTENDED_DATA; - writeUInt32BE(packet, chan, ++p); - writeUInt32BE(packet, type, p += 4); - writeUInt32BE(packet, dataLen, p += 4); - if (isBuffer) - packet.set(data, p += 4); - else - packet.utf8Write(data, p += 4, dataLen); - this._debug && this._debug(`Outbound: Sending CHANNEL_EXTENDED_DATA (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelOpenConfirm(remote, local, initWindow, maxPacket) { - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 4); - packet[p] = MESSAGE.CHANNEL_OPEN_CONFIRMATION; - writeUInt32BE(packet, remote, ++p); - writeUInt32BE(packet, local, p += 4); - writeUInt32BE(packet, initWindow, p += 4); - writeUInt32BE(packet, maxPacket, p += 4); - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN_CONFIRMATION (r:${remote}, l:${local})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelOpenFail(remote, reason, desc) { - if (typeof desc !== "string") - desc = ""; - const descLen = Buffer.byteLength(desc); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + descLen + 4); - packet[p] = MESSAGE.CHANNEL_OPEN_FAILURE; - writeUInt32BE(packet, remote, ++p); - writeUInt32BE(packet, reason, p += 4); - writeUInt32BE(packet, descLen, p += 4); - p += 4; - if (descLen) { - packet.utf8Write(desc, p, descLen); - p += descLen; - } - writeUInt32BE(packet, 0, p); - this._debug && this._debug(`Outbound: Sending CHANNEL_OPEN_FAILURE (r:${remote})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - // =========================================================================== - // Client-specific =========================================================== - // =========================================================================== - // Global - // ------ - service(name) { - if (this._server) - throw new Error("Client-only method called in server mode"); - const nameLen = Buffer.byteLength(name); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + nameLen); - packet[p] = MESSAGE.SERVICE_REQUEST; - writeUInt32BE(packet, nameLen, ++p); - packet.utf8Write(name, p += 4, nameLen); - this._debug && this._debug(`Outbound: Sending SERVICE_REQUEST (${name})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - // 'ssh-userauth' service-specific - // ------------------------------- - authPassword(username, password, newPassword) { - if (this._server) - throw new Error("Client-only method called in server mode"); - const userLen = Buffer.byteLength(username); - const passLen = Buffer.byteLength(password); - const newPassLen = newPassword ? Buffer.byteLength(newPassword) : 0; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + userLen + 4 + 14 + 4 + 8 + 1 + 4 + passLen + (newPassword ? 4 + newPassLen : 0) - ); - packet[p] = MESSAGE.USERAUTH_REQUEST; - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write("ssh-connection", p += 4, 14); - writeUInt32BE(packet, 8, p += 14); - packet.utf8Write("password", p += 4, 8); - packet[p += 8] = newPassword ? 1 : 0; - writeUInt32BE(packet, passLen, ++p); - if (Buffer.isBuffer(password)) - bufferCopy(password, packet, 0, passLen, p += 4); - else - packet.utf8Write(password, p += 4, passLen); - if (newPassword) { - writeUInt32BE(packet, newPassLen, p += passLen); - if (Buffer.isBuffer(newPassword)) - bufferCopy(newPassword, packet, 0, newPassLen, p += 4); - else - packet.utf8Write(newPassword, p += 4, newPassLen); - this._debug && this._debug( - "Outbound: Sending USERAUTH_REQUEST (changed password)" - ); - } else { - this._debug && this._debug( - "Outbound: Sending USERAUTH_REQUEST (password)" - ); - } - this._authsQueue.push("password"); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authPK(username, pubKey, keyAlgo, cbSign) { - if (this._server) - throw new Error("Client-only method called in server mode"); - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) - throw new Error("Invalid key"); - const keyType = pubKey.type; - pubKey = pubKey.getPublicSSH(); - if (typeof keyAlgo === "function") { - cbSign = keyAlgo; - keyAlgo = void 0; - } - if (!keyAlgo) - keyAlgo = keyType; - const userLen = Buffer.byteLength(username); - const algoLen = Buffer.byteLength(keyAlgo); - const pubKeyLen = pubKey.length; - const sessionID = this._kex.sessionID; - const sesLen = sessionID.length; - const payloadLen = (cbSign ? 4 + sesLen : 0) + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen; - let packet; - let p; - if (cbSign) { - packet = Buffer.allocUnsafe(payloadLen); - p = 0; - writeUInt32BE(packet, sesLen, p); - packet.set(sessionID, p += 4); - p += sesLen; - } else { - packet = this._packetRW.write.alloc(payloadLen); - p = this._packetRW.write.allocStart; - } - packet[p] = MESSAGE.USERAUTH_REQUEST; - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write("ssh-connection", p += 4, 14); - writeUInt32BE(packet, 9, p += 14); - packet.utf8Write("publickey", p += 4, 9); - packet[p += 9] = cbSign ? 1 : 0; - writeUInt32BE(packet, algoLen, ++p); - packet.utf8Write(keyAlgo, p += 4, algoLen); - writeUInt32BE(packet, pubKeyLen, p += algoLen); - packet.set(pubKey, p += 4); - if (!cbSign) { - this._authsQueue.push("publickey"); - this._debug && this._debug( - "Outbound: Sending USERAUTH_REQUEST (publickey -- check)" - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - return; - } - cbSign(packet, (signature) => { - signature = convertSignature(signature, keyType); - if (signature === false) - throw new Error("Error while converting handshake signature"); - const sigLen = signature.length; - p = this._packetRW.write.allocStart; - packet = this._packetRW.write.alloc( - 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen + 4 + 4 + algoLen + 4 + sigLen - ); - packet[p] = MESSAGE.USERAUTH_REQUEST; - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write("ssh-connection", p += 4, 14); - writeUInt32BE(packet, 9, p += 14); - packet.utf8Write("publickey", p += 4, 9); - packet[p += 9] = 1; - writeUInt32BE(packet, algoLen, ++p); - packet.utf8Write(keyAlgo, p += 4, algoLen); - writeUInt32BE(packet, pubKeyLen, p += algoLen); - packet.set(pubKey, p += 4); - writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += pubKeyLen); - writeUInt32BE(packet, algoLen, p += 4); - packet.utf8Write(keyAlgo, p += 4, algoLen); - writeUInt32BE(packet, sigLen, p += algoLen); - packet.set(signature, p += 4); - this._authsQueue.push("publickey"); - this._debug && this._debug( - "Outbound: Sending USERAUTH_REQUEST (publickey)" - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - }); - } - authHostbased(username, pubKey, hostname, userlocal, keyAlgo, cbSign) { - if (this._server) - throw new Error("Client-only method called in server mode"); - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) - throw new Error("Invalid key"); - const keyType = pubKey.type; - pubKey = pubKey.getPublicSSH(); - if (typeof keyAlgo === "function") { - cbSign = keyAlgo; - keyAlgo = void 0; - } - if (!keyAlgo) - keyAlgo = keyType; - const userLen = Buffer.byteLength(username); - const algoLen = Buffer.byteLength(keyAlgo); - const pubKeyLen = pubKey.length; - const sessionID = this._kex.sessionID; - const sesLen = sessionID.length; - const hostnameLen = Buffer.byteLength(hostname); - const userlocalLen = Buffer.byteLength(userlocal); - const data = Buffer.allocUnsafe( - 4 + sesLen + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 4 + algoLen + 4 + pubKeyLen + 4 + hostnameLen + 4 + userlocalLen - ); - let p = 0; - writeUInt32BE(data, sesLen, p); - data.set(sessionID, p += 4); - data[p += sesLen] = MESSAGE.USERAUTH_REQUEST; - writeUInt32BE(data, userLen, ++p); - data.utf8Write(username, p += 4, userLen); - writeUInt32BE(data, 14, p += userLen); - data.utf8Write("ssh-connection", p += 4, 14); - writeUInt32BE(data, 9, p += 14); - data.utf8Write("hostbased", p += 4, 9); - writeUInt32BE(data, algoLen, p += 9); - data.utf8Write(keyAlgo, p += 4, algoLen); - writeUInt32BE(data, pubKeyLen, p += algoLen); - data.set(pubKey, p += 4); - writeUInt32BE(data, hostnameLen, p += pubKeyLen); - data.utf8Write(hostname, p += 4, hostnameLen); - writeUInt32BE(data, userlocalLen, p += hostnameLen); - data.utf8Write(userlocal, p += 4, userlocalLen); - cbSign(data, (signature) => { - signature = convertSignature(signature, keyType); - if (!signature) - throw new Error("Error while converting handshake signature"); - const sigLen = signature.length; - const reqDataLen = data.length - sesLen - 4; - p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - reqDataLen + 4 + 4 + algoLen + 4 + sigLen - ); - bufferCopy(data, packet, 4 + sesLen, data.length, p); - writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += reqDataLen); - writeUInt32BE(packet, algoLen, p += 4); - packet.utf8Write(keyAlgo, p += 4, algoLen); - writeUInt32BE(packet, sigLen, p += algoLen); - packet.set(signature, p += 4); - this._authsQueue.push("hostbased"); - this._debug && this._debug( - "Outbound: Sending USERAUTH_REQUEST (hostbased)" - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - }); - } - authKeyboard(username) { - if (this._server) - throw new Error("Client-only method called in server mode"); - const userLen = Buffer.byteLength(username); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + userLen + 4 + 14 + 4 + 20 + 4 + 4 - ); - packet[p] = MESSAGE.USERAUTH_REQUEST; - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write("ssh-connection", p += 4, 14); - writeUInt32BE(packet, 20, p += 14); - packet.utf8Write("keyboard-interactive", p += 4, 20); - writeUInt32BE(packet, 0, p += 20); - writeUInt32BE(packet, 0, p += 4); - this._authsQueue.push("keyboard-interactive"); - this._debug && this._debug( - "Outbound: Sending USERAUTH_REQUEST (keyboard-interactive)" - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authNone(username) { - if (this._server) - throw new Error("Client-only method called in server mode"); - const userLen = Buffer.byteLength(username); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + userLen + 4 + 14 + 4 + 4); - packet[p] = MESSAGE.USERAUTH_REQUEST; - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write("ssh-connection", p += 4, 14); - writeUInt32BE(packet, 4, p += 14); - packet.utf8Write("none", p += 4, 4); - this._authsQueue.push("none"); - this._debug && this._debug("Outbound: Sending USERAUTH_REQUEST (none)"); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authInfoRes(responses) { - if (this._server) - throw new Error("Client-only method called in server mode"); - let responsesTotalLen = 0; - let responseLens; - if (responses) { - responseLens = new Array(responses.length); - for (let i = 0; i < responses.length; ++i) { - const len = Buffer.byteLength(responses[i]); - responseLens[i] = len; - responsesTotalLen += 4 + len; - } - } - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + responsesTotalLen); - packet[p] = MESSAGE.USERAUTH_INFO_RESPONSE; - if (responses) { - writeUInt32BE(packet, responses.length, ++p); - p += 4; - for (let i = 0; i < responses.length; ++i) { - const len = responseLens[i]; - writeUInt32BE(packet, len, p); - p += 4; - if (len) { - packet.utf8Write(responses[i], p, len); - p += len; - } - } - } else { - writeUInt32BE(packet, 0, ++p); - } - this._debug && this._debug("Outbound: Sending USERAUTH_INFO_RESPONSE"); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - // 'ssh-connection' service-specific - // --------------------------------- - tcpipForward(bindAddr, bindPort, wantReply) { - if (this._server) - throw new Error("Client-only method called in server mode"); - const addrLen = Buffer.byteLength(bindAddr); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 13 + 1 + 4 + addrLen + 4); - packet[p] = MESSAGE.GLOBAL_REQUEST; - writeUInt32BE(packet, 13, ++p); - packet.utf8Write("tcpip-forward", p += 4, 13); - packet[p += 13] = wantReply === void 0 || wantReply === true ? 1 : 0; - writeUInt32BE(packet, addrLen, ++p); - packet.utf8Write(bindAddr, p += 4, addrLen); - writeUInt32BE(packet, bindPort, p += addrLen); - this._debug && this._debug("Outbound: Sending GLOBAL_REQUEST (tcpip-forward)"); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - cancelTcpipForward(bindAddr, bindPort, wantReply) { - if (this._server) - throw new Error("Client-only method called in server mode"); - const addrLen = Buffer.byteLength(bindAddr); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 20 + 1 + 4 + addrLen + 4); - packet[p] = MESSAGE.GLOBAL_REQUEST; - writeUInt32BE(packet, 20, ++p); - packet.utf8Write("cancel-tcpip-forward", p += 4, 20); - packet[p += 20] = wantReply === void 0 || wantReply === true ? 1 : 0; - writeUInt32BE(packet, addrLen, ++p); - packet.utf8Write(bindAddr, p += 4, addrLen); - writeUInt32BE(packet, bindPort, p += addrLen); - this._debug && this._debug("Outbound: Sending GLOBAL_REQUEST (cancel-tcpip-forward)"); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_streamLocalForward(socketPath, wantReply) { - if (this._server) - throw new Error("Client-only method called in server mode"); - const socketPathLen = Buffer.byteLength(socketPath); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 31 + 1 + 4 + socketPathLen - ); - packet[p] = MESSAGE.GLOBAL_REQUEST; - writeUInt32BE(packet, 31, ++p); - packet.utf8Write("streamlocal-forward@openssh.com", p += 4, 31); - packet[p += 31] = wantReply === void 0 || wantReply === true ? 1 : 0; - writeUInt32BE(packet, socketPathLen, ++p); - packet.utf8Write(socketPath, p += 4, socketPathLen); - this._debug && this._debug( - "Outbound: Sending GLOBAL_REQUEST (streamlocal-forward@openssh.com)" - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_cancelStreamLocalForward(socketPath, wantReply) { - if (this._server) - throw new Error("Client-only method called in server mode"); - const socketPathLen = Buffer.byteLength(socketPath); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 38 + 1 + 4 + socketPathLen - ); - packet[p] = MESSAGE.GLOBAL_REQUEST; - writeUInt32BE(packet, 38, ++p); - packet.utf8Write("cancel-streamlocal-forward@openssh.com", p += 4, 38); - packet[p += 38] = wantReply === void 0 || wantReply === true ? 1 : 0; - writeUInt32BE(packet, socketPathLen, ++p); - packet.utf8Write(socketPath, p += 4, socketPathLen); - if (this._debug) { - this._debug( - "Outbound: Sending GLOBAL_REQUEST (cancel-streamlocal-forward@openssh.com)" - ); - } - sendPacket(this, this._packetRW.write.finalize(packet)); - } - directTcpip(chan, initWindow, maxPacket, cfg) { - if (this._server) - throw new Error("Client-only method called in server mode"); - const srcLen = Buffer.byteLength(cfg.srcIP); - const dstLen = Buffer.byteLength(cfg.dstIP); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 12 + 4 + 4 + 4 + 4 + srcLen + 4 + 4 + dstLen + 4 - ); - packet[p] = MESSAGE.CHANNEL_OPEN; - writeUInt32BE(packet, 12, ++p); - packet.utf8Write("direct-tcpip", p += 4, 12); - writeUInt32BE(packet, chan, p += 12); - writeUInt32BE(packet, initWindow, p += 4); - writeUInt32BE(packet, maxPacket, p += 4); - writeUInt32BE(packet, dstLen, p += 4); - packet.utf8Write(cfg.dstIP, p += 4, dstLen); - writeUInt32BE(packet, cfg.dstPort, p += dstLen); - writeUInt32BE(packet, srcLen, p += 4); - packet.utf8Write(cfg.srcIP, p += 4, srcLen); - writeUInt32BE(packet, cfg.srcPort, p += srcLen); - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN (r:${chan}, direct-tcpip)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_directStreamLocal(chan, initWindow, maxPacket, cfg) { - if (this._server) - throw new Error("Client-only method called in server mode"); - const pathLen = Buffer.byteLength(cfg.socketPath); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 30 + 4 + 4 + 4 + 4 + pathLen + 4 + 4 - ); - packet[p] = MESSAGE.CHANNEL_OPEN; - writeUInt32BE(packet, 30, ++p); - packet.utf8Write("direct-streamlocal@openssh.com", p += 4, 30); - writeUInt32BE(packet, chan, p += 30); - writeUInt32BE(packet, initWindow, p += 4); - writeUInt32BE(packet, maxPacket, p += 4); - writeUInt32BE(packet, pathLen, p += 4); - packet.utf8Write(cfg.socketPath, p += 4, pathLen); - bufferFill(packet, 0, p += pathLen, p + 8); - if (this._debug) { - this._debug( - `Outbound: Sending CHANNEL_OPEN (r:${chan}, direct-streamlocal@openssh.com)` - ); - } - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_noMoreSessions(wantReply) { - if (this._server) - throw new Error("Client-only method called in server mode"); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 28 + 1); - packet[p] = MESSAGE.GLOBAL_REQUEST; - writeUInt32BE(packet, 28, ++p); - packet.utf8Write("no-more-sessions@openssh.com", p += 4, 28); - packet[p += 28] = wantReply === void 0 || wantReply === true ? 1 : 0; - this._debug && this._debug( - "Outbound: Sending GLOBAL_REQUEST (no-more-sessions@openssh.com)" - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - session(chan, initWindow, maxPacket) { - if (this._server) - throw new Error("Client-only method called in server mode"); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 7 + 4 + 4 + 4); - packet[p] = MESSAGE.CHANNEL_OPEN; - writeUInt32BE(packet, 7, ++p); - packet.utf8Write("session", p += 4, 7); - writeUInt32BE(packet, chan, p += 7); - writeUInt32BE(packet, initWindow, p += 4); - writeUInt32BE(packet, maxPacket, p += 4); - this._debug && this._debug(`Outbound: Sending CHANNEL_OPEN (r:${chan}, session)`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - windowChange(chan, rows, cols, height, width) { - if (this._server) - throw new Error("Client-only method called in server mode"); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 13 + 1 + 4 + 4 + 4 + 4 - ); - packet[p] = MESSAGE.CHANNEL_REQUEST; - writeUInt32BE(packet, chan, ++p); - writeUInt32BE(packet, 13, p += 4); - packet.utf8Write("window-change", p += 4, 13); - packet[p += 13] = 0; - writeUInt32BE(packet, cols, ++p); - writeUInt32BE(packet, rows, p += 4); - writeUInt32BE(packet, width, p += 4); - writeUInt32BE(packet, height, p += 4); - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, window-change)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - pty(chan, rows, cols, height, width, term, modes, wantReply) { - if (this._server) - throw new Error("Client-only method called in server mode"); - if (!term || !term.length) - term = "vt100"; - if (modes && !Buffer.isBuffer(modes) && !Array.isArray(modes) && typeof modes === "object" && modes !== null) { - modes = modesToBytes(modes); - } - if (!modes || !modes.length) - modes = NO_TERMINAL_MODES_BUFFER; - const termLen = term.length; - const modesLen = modes.length; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 7 + 1 + 4 + termLen + 4 + 4 + 4 + 4 + 4 + modesLen - ); - packet[p] = MESSAGE.CHANNEL_REQUEST; - writeUInt32BE(packet, chan, ++p); - writeUInt32BE(packet, 7, p += 4); - packet.utf8Write("pty-req", p += 4, 7); - packet[p += 7] = wantReply === void 0 || wantReply === true ? 1 : 0; - writeUInt32BE(packet, termLen, ++p); - packet.utf8Write(term, p += 4, termLen); - writeUInt32BE(packet, cols, p += termLen); - writeUInt32BE(packet, rows, p += 4); - writeUInt32BE(packet, width, p += 4); - writeUInt32BE(packet, height, p += 4); - writeUInt32BE(packet, modesLen, p += 4); - p += 4; - if (Array.isArray(modes)) { - for (let i = 0; i < modesLen; ++i) - packet[p++] = modes[i]; - } else if (Buffer.isBuffer(modes)) { - packet.set(modes, p); - } - this._debug && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, pty-req)`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - shell(chan, wantReply) { - if (this._server) - throw new Error("Client-only method called in server mode"); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 5 + 1); - packet[p] = MESSAGE.CHANNEL_REQUEST; - writeUInt32BE(packet, chan, ++p); - writeUInt32BE(packet, 5, p += 4); - packet.utf8Write("shell", p += 4, 5); - packet[p += 5] = wantReply === void 0 || wantReply === true ? 1 : 0; - this._debug && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, shell)`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - exec(chan, cmd, wantReply) { - if (this._server) - throw new Error("Client-only method called in server mode"); - const isBuf = Buffer.isBuffer(cmd); - const cmdLen = isBuf ? cmd.length : Buffer.byteLength(cmd); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 1 + 4 + cmdLen); - packet[p] = MESSAGE.CHANNEL_REQUEST; - writeUInt32BE(packet, chan, ++p); - writeUInt32BE(packet, 4, p += 4); - packet.utf8Write("exec", p += 4, 4); - packet[p += 4] = wantReply === void 0 || wantReply === true ? 1 : 0; - writeUInt32BE(packet, cmdLen, ++p); - if (isBuf) - packet.set(cmd, p += 4); - else - packet.utf8Write(cmd, p += 4, cmdLen); - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exec: ${cmd})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - signal(chan, signal) { - if (this._server) - throw new Error("Client-only method called in server mode"); - const origSignal = signal; - signal = signal.toUpperCase(); - if (signal.slice(0, 3) === "SIG") - signal = signal.slice(3); - if (SIGNALS[signal] !== 1) - throw new Error(`Invalid signal: ${origSignal}`); - const signalLen = signal.length; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 6 + 1 + 4 + signalLen - ); - packet[p] = MESSAGE.CHANNEL_REQUEST; - writeUInt32BE(packet, chan, ++p); - writeUInt32BE(packet, 6, p += 4); - packet.utf8Write("signal", p += 4, 6); - packet[p += 6] = 0; - writeUInt32BE(packet, signalLen, ++p); - packet.utf8Write(signal, p += 4, signalLen); - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, signal: ${signal})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - env(chan, key, val, wantReply) { - if (this._server) - throw new Error("Client-only method called in server mode"); - const keyLen = Buffer.byteLength(key); - const isBuf = Buffer.isBuffer(val); - const valLen = isBuf ? val.length : Buffer.byteLength(val); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 3 + 1 + 4 + keyLen + 4 + valLen - ); - packet[p] = MESSAGE.CHANNEL_REQUEST; - writeUInt32BE(packet, chan, ++p); - writeUInt32BE(packet, 3, p += 4); - packet.utf8Write("env", p += 4, 3); - packet[p += 3] = wantReply === void 0 || wantReply === true ? 1 : 0; - writeUInt32BE(packet, keyLen, ++p); - packet.utf8Write(key, p += 4, keyLen); - writeUInt32BE(packet, valLen, p += keyLen); - if (isBuf) - packet.set(val, p += 4); - else - packet.utf8Write(val, p += 4, valLen); - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, env: ${key}=${val})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - x11Forward(chan, cfg, wantReply) { - if (this._server) - throw new Error("Client-only method called in server mode"); - const protocol = cfg.protocol; - const cookie = cfg.cookie; - const isBufProto = Buffer.isBuffer(protocol); - const protoLen = isBufProto ? protocol.length : Buffer.byteLength(protocol); - const isBufCookie = Buffer.isBuffer(cookie); - const cookieLen = isBufCookie ? cookie.length : Buffer.byteLength(cookie); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 7 + 1 + 1 + 4 + protoLen + 4 + cookieLen + 4 - ); - packet[p] = MESSAGE.CHANNEL_REQUEST; - writeUInt32BE(packet, chan, ++p); - writeUInt32BE(packet, 7, p += 4); - packet.utf8Write("x11-req", p += 4, 7); - packet[p += 7] = wantReply === void 0 || wantReply === true ? 1 : 0; - packet[++p] = cfg.single ? 1 : 0; - writeUInt32BE(packet, protoLen, ++p); - if (isBufProto) - packet.set(protocol, p += 4); - else - packet.utf8Write(protocol, p += 4, protoLen); - writeUInt32BE(packet, cookieLen, p += protoLen); - if (isBufCookie) - packet.set(cookie, p += 4); - else - packet.latin1Write(cookie, p += 4, cookieLen); - writeUInt32BE(packet, cfg.screen || 0, p += cookieLen); - this._debug && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, x11-req)`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - subsystem(chan, name, wantReply) { - if (this._server) - throw new Error("Client-only method called in server mode"); - const nameLen = Buffer.byteLength(name); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 9 + 1 + 4 + nameLen); - packet[p] = MESSAGE.CHANNEL_REQUEST; - writeUInt32BE(packet, chan, ++p); - writeUInt32BE(packet, 9, p += 4); - packet.utf8Write("subsystem", p += 4, 9); - packet[p += 9] = wantReply === void 0 || wantReply === true ? 1 : 0; - writeUInt32BE(packet, nameLen, ++p); - packet.utf8Write(name, p += 4, nameLen); - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, subsystem: ${name})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_agentForward(chan, wantReply) { - if (this._server) - throw new Error("Client-only method called in server mode"); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 26 + 1); - packet[p] = MESSAGE.CHANNEL_REQUEST; - writeUInt32BE(packet, chan, ++p); - writeUInt32BE(packet, 26, p += 4); - packet.utf8Write("auth-agent-req@openssh.com", p += 4, 26); - packet[p += 26] = wantReply === void 0 || wantReply === true ? 1 : 0; - if (this._debug) { - this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, auth-agent-req@openssh.com)` - ); - } - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_hostKeysProve(keys) { - if (this._server) - throw new Error("Client-only method called in server mode"); - let keysTotal = 0; - const publicKeys = []; - for (const key of keys) { - const publicKey = key.getPublicSSH(); - keysTotal += 4 + publicKey.length; - publicKeys.push(publicKey); - } - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 29 + 1 + keysTotal); - packet[p] = MESSAGE.GLOBAL_REQUEST; - writeUInt32BE(packet, 29, ++p); - packet.utf8Write("hostkeys-prove-00@openssh.com", p += 4, 29); - packet[p += 29] = 1; - ++p; - for (const buf of publicKeys) { - writeUInt32BE(packet, buf.length, p); - bufferCopy(buf, packet, 0, buf.length, p += 4); - p += buf.length; - } - if (this._debug) { - this._debug( - "Outbound: Sending GLOBAL_REQUEST (hostkeys-prove-00@openssh.com)" - ); - } - sendPacket(this, this._packetRW.write.finalize(packet)); - } - // =========================================================================== - // Server-specific =========================================================== - // =========================================================================== - // Global - // ------ - serviceAccept(svcName) { - if (!this._server) - throw new Error("Server-only method called in client mode"); - const svcNameLen = Buffer.byteLength(svcName); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + svcNameLen); - packet[p] = MESSAGE.SERVICE_ACCEPT; - writeUInt32BE(packet, svcNameLen, ++p); - packet.utf8Write(svcName, p += 4, svcNameLen); - this._debug && this._debug(`Outbound: Sending SERVICE_ACCEPT (${svcName})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - if (this._server && this._banner && svcName === "ssh-userauth") { - const banner = this._banner; - this._banner = void 0; - const bannerLen = Buffer.byteLength(banner); - p = this._packetRW.write.allocStart; - const packet2 = this._packetRW.write.alloc(1 + 4 + bannerLen + 4); - packet2[p] = MESSAGE.USERAUTH_BANNER; - writeUInt32BE(packet2, bannerLen, ++p); - packet2.utf8Write(banner, p += 4, bannerLen); - writeUInt32BE(packet2, 0, p += bannerLen); - this._debug && this._debug("Outbound: Sending USERAUTH_BANNER"); - sendPacket(this, this._packetRW.write.finalize(packet2)); - } - } - // 'ssh-connection' service-specific - forwardedTcpip(chan, initWindow, maxPacket, cfg) { - if (!this._server) - throw new Error("Server-only method called in client mode"); - const boundAddrLen = Buffer.byteLength(cfg.boundAddr); - const remoteAddrLen = Buffer.byteLength(cfg.remoteAddr); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 15 + 4 + 4 + 4 + 4 + boundAddrLen + 4 + 4 + remoteAddrLen + 4 - ); - packet[p] = MESSAGE.CHANNEL_OPEN; - writeUInt32BE(packet, 15, ++p); - packet.utf8Write("forwarded-tcpip", p += 4, 15); - writeUInt32BE(packet, chan, p += 15); - writeUInt32BE(packet, initWindow, p += 4); - writeUInt32BE(packet, maxPacket, p += 4); - writeUInt32BE(packet, boundAddrLen, p += 4); - packet.utf8Write(cfg.boundAddr, p += 4, boundAddrLen); - writeUInt32BE(packet, cfg.boundPort, p += boundAddrLen); - writeUInt32BE(packet, remoteAddrLen, p += 4); - packet.utf8Write(cfg.remoteAddr, p += 4, remoteAddrLen); - writeUInt32BE(packet, cfg.remotePort, p += remoteAddrLen); - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN (r:${chan}, forwarded-tcpip)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - x11(chan, initWindow, maxPacket, cfg) { - if (!this._server) - throw new Error("Server-only method called in client mode"); - const addrLen = Buffer.byteLength(cfg.originAddr); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 3 + 4 + 4 + 4 + 4 + addrLen + 4 - ); - packet[p] = MESSAGE.CHANNEL_OPEN; - writeUInt32BE(packet, 3, ++p); - packet.utf8Write("x11", p += 4, 3); - writeUInt32BE(packet, chan, p += 3); - writeUInt32BE(packet, initWindow, p += 4); - writeUInt32BE(packet, maxPacket, p += 4); - writeUInt32BE(packet, addrLen, p += 4); - packet.utf8Write(cfg.originAddr, p += 4, addrLen); - writeUInt32BE(packet, cfg.originPort, p += addrLen); - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN (r:${chan}, x11)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_authAgent(chan, initWindow, maxPacket) { - if (!this._server) - throw new Error("Server-only method called in client mode"); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 22 + 4 + 4 + 4); - packet[p] = MESSAGE.CHANNEL_OPEN; - writeUInt32BE(packet, 22, ++p); - packet.utf8Write("auth-agent@openssh.com", p += 4, 22); - writeUInt32BE(packet, chan, p += 22); - writeUInt32BE(packet, initWindow, p += 4); - writeUInt32BE(packet, maxPacket, p += 4); - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN (r:${chan}, auth-agent@openssh.com)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_forwardedStreamLocal(chan, initWindow, maxPacket, cfg) { - if (!this._server) - throw new Error("Server-only method called in client mode"); - const pathLen = Buffer.byteLength(cfg.socketPath); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 33 + 4 + 4 + 4 + 4 + pathLen + 4 - ); - packet[p] = MESSAGE.CHANNEL_OPEN; - writeUInt32BE(packet, 33, ++p); - packet.utf8Write("forwarded-streamlocal@openssh.com", p += 4, 33); - writeUInt32BE(packet, chan, p += 33); - writeUInt32BE(packet, initWindow, p += 4); - writeUInt32BE(packet, maxPacket, p += 4); - writeUInt32BE(packet, pathLen, p += 4); - packet.utf8Write(cfg.socketPath, p += 4, pathLen); - writeUInt32BE(packet, 0, p += pathLen); - if (this._debug) { - this._debug( - `Outbound: Sending CHANNEL_OPEN (r:${chan}, forwarded-streamlocal@openssh.com)` - ); - } - sendPacket(this, this._packetRW.write.finalize(packet)); - } - exitStatus(chan, status) { - if (!this._server) - throw new Error("Server-only method called in client mode"); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 11 + 1 + 4); - packet[p] = MESSAGE.CHANNEL_REQUEST; - writeUInt32BE(packet, chan, ++p); - writeUInt32BE(packet, 11, p += 4); - packet.utf8Write("exit-status", p += 4, 11); - packet[p += 11] = 0; - writeUInt32BE(packet, status, ++p); - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-status: ${status})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - exitSignal(chan, name, coreDumped, msg) { - if (!this._server) - throw new Error("Server-only method called in client mode"); - const origSignal = name; - if (typeof origSignal !== "string" || !origSignal) - throw new Error(`Invalid signal: ${origSignal}`); - let signal = name.toUpperCase(); - if (signal.slice(0, 3) === "SIG") - signal = signal.slice(3); - if (SIGNALS[signal] !== 1) - throw new Error(`Invalid signal: ${origSignal}`); - const nameLen = Buffer.byteLength(signal); - const msgLen = msg ? Buffer.byteLength(msg) : 0; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 11 + 1 + 4 + nameLen + 1 + 4 + msgLen + 4 - ); - packet[p] = MESSAGE.CHANNEL_REQUEST; - writeUInt32BE(packet, chan, ++p); - writeUInt32BE(packet, 11, p += 4); - packet.utf8Write("exit-signal", p += 4, 11); - packet[p += 11] = 0; - writeUInt32BE(packet, nameLen, ++p); - packet.utf8Write(signal, p += 4, nameLen); - packet[p += nameLen] = coreDumped ? 1 : 0; - writeUInt32BE(packet, msgLen, ++p); - p += 4; - if (msgLen) { - packet.utf8Write(msg, p, msgLen); - p += msgLen; - } - writeUInt32BE(packet, 0, p); - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-signal: ${name})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - // 'ssh-userauth' service-specific - authFailure(authMethods, isPartial) { - if (!this._server) - throw new Error("Server-only method called in client mode"); - if (this._authsQueue.length === 0) - throw new Error("No auth in progress"); - let methods; - if (typeof authMethods === "boolean") { - isPartial = authMethods; - authMethods = void 0; - } - if (authMethods) { - methods = []; - for (let i = 0; i < authMethods.length; ++i) { - if (authMethods[i].toLowerCase() === "none") - continue; - methods.push(authMethods[i]); - } - methods = methods.join(","); - } else { - methods = ""; - } - const methodsLen = methods.length; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + methodsLen + 1); - packet[p] = MESSAGE.USERAUTH_FAILURE; - writeUInt32BE(packet, methodsLen, ++p); - packet.utf8Write(methods, p += 4, methodsLen); - packet[p += methodsLen] = isPartial === true ? 1 : 0; - this._authsQueue.shift(); - this._debug && this._debug("Outbound: Sending USERAUTH_FAILURE"); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authSuccess() { - if (!this._server) - throw new Error("Server-only method called in client mode"); - if (this._authsQueue.length === 0) - throw new Error("No auth in progress"); - const p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1); - packet[p] = MESSAGE.USERAUTH_SUCCESS; - this._authsQueue.shift(); - this._authenticated = true; - this._debug && this._debug("Outbound: Sending USERAUTH_SUCCESS"); - sendPacket(this, this._packetRW.write.finalize(packet)); - if (this._kex.negotiated.cs.compress === "zlib@openssh.com") - this._packetRW.read = new ZlibPacketReader(); - if (this._kex.negotiated.sc.compress === "zlib@openssh.com") - this._packetRW.write = new ZlibPacketWriter(this); - } - authPKOK(keyAlgo, key) { - if (!this._server) - throw new Error("Server-only method called in client mode"); - if (this._authsQueue.length === 0 || this._authsQueue[0] !== "publickey") - throw new Error('"publickey" auth not in progress'); - const keyAlgoLen = Buffer.byteLength(keyAlgo); - const keyLen = key.length; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + keyAlgoLen + 4 + keyLen); - packet[p] = MESSAGE.USERAUTH_PK_OK; - writeUInt32BE(packet, keyAlgoLen, ++p); - packet.utf8Write(keyAlgo, p += 4, keyAlgoLen); - writeUInt32BE(packet, keyLen, p += keyAlgoLen); - packet.set(key, p += 4); - this._authsQueue.shift(); - this._debug && this._debug("Outbound: Sending USERAUTH_PK_OK"); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authPasswdChg(prompt) { - if (!this._server) - throw new Error("Server-only method called in client mode"); - const promptLen = Buffer.byteLength(prompt); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + promptLen + 4); - packet[p] = MESSAGE.USERAUTH_PASSWD_CHANGEREQ; - writeUInt32BE(packet, promptLen, ++p); - packet.utf8Write(prompt, p += 4, promptLen); - writeUInt32BE(packet, 0, p += promptLen); - this._debug && this._debug("Outbound: Sending USERAUTH_PASSWD_CHANGEREQ"); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authInfoReq(name, instructions, prompts) { - if (!this._server) - throw new Error("Server-only method called in client mode"); - let promptsLen = 0; - const nameLen = name ? Buffer.byteLength(name) : 0; - const instrLen = instructions ? Buffer.byteLength(instructions) : 0; - for (let i = 0; i < prompts.length; ++i) - promptsLen += 4 + Buffer.byteLength(prompts[i].prompt) + 1; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + nameLen + 4 + instrLen + 4 + 4 + promptsLen - ); - packet[p] = MESSAGE.USERAUTH_INFO_REQUEST; - writeUInt32BE(packet, nameLen, ++p); - p += 4; - if (name) { - packet.utf8Write(name, p, nameLen); - p += nameLen; - } - writeUInt32BE(packet, instrLen, p); - p += 4; - if (instructions) { - packet.utf8Write(instructions, p, instrLen); - p += instrLen; - } - writeUInt32BE(packet, 0, p); - writeUInt32BE(packet, prompts.length, p += 4); - p += 4; - for (let i = 0; i < prompts.length; ++i) { - const prompt = prompts[i]; - const promptLen = Buffer.byteLength(prompt.prompt); - writeUInt32BE(packet, promptLen, p); - p += 4; - if (promptLen) { - packet.utf8Write(prompt.prompt, p, promptLen); - p += promptLen; - } - packet[p++] = prompt.echo ? 1 : 0; - } - this._debug && this._debug("Outbound: Sending USERAUTH_INFO_REQUEST"); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - }; - var RE_IDENT = /^SSH-(2\.0|1\.99)-([^ ]+)(?: (.*))?$/; - function parseHeader(chunk, p, len) { - let data; - let chunkOffset; - if (this._buffer) { - data = Buffer.allocUnsafe(this._buffer.length + (len - p)); - data.set(this._buffer, 0); - if (p === 0) { - data.set(chunk, this._buffer.length); - } else { - data.set( - new Uint8Array( - chunk.buffer, - chunk.byteOffset + p, - len - p - ), - this._buffer.length - ); - } - chunkOffset = this._buffer.length; - p = 0; - } else { - data = chunk; - chunkOffset = 0; - } - const op = p; - let start = p; - let end = p; - let needNL = false; - let lineLen = 0; - let lines = 0; - for (; p < data.length; ++p) { - const ch = data[p]; - if (ch === 13) { - needNL = true; - continue; - } - if (ch === 10) { - if (end > start && end - start > 4 && data[start] === 83 && data[start + 1] === 83 && data[start + 2] === 72 && data[start + 3] === 45) { - const full = data.latin1Slice(op, end + 1); - const identRaw = start === op ? full : full.slice(start - op); - const m = RE_IDENT.exec(identRaw); - if (!m) - throw new Error("Invalid identification string"); - const header = { - greeting: start === op ? "" : full.slice(0, start - op), - identRaw, - versions: { - protocol: m[1], - software: m[2] - }, - comments: m[3] - }; - this._remoteIdentRaw = Buffer.from(identRaw); - this._debug && this._debug(`Remote ident: ${inspect(identRaw)}`); - this._compatFlags = getCompatFlags(header); - this._buffer = void 0; - this._decipher = new NullDecipher(0, onKEXPayload.bind(this, { firstPacket: true })); - this._parse = parsePacket; - this._onHeader(header); - if (!this._destruct) { - return len; - } - kexinit(this); - return p + 1 - chunkOffset; - } - if (this._server) - throw new Error("Greetings from clients not permitted"); - if (++lines > MAX_LINES) - throw new Error("Max greeting lines exceeded"); - needNL = false; - start = p + 1; - lineLen = 0; - } else if (needNL) { - throw new Error("Invalid header: expected newline"); - } else if (++lineLen >= MAX_LINE_LEN) { - throw new Error("Header line too long"); - } - end = p; - } - if (!this._buffer) - this._buffer = bufferSlice(data, op); - return p - chunkOffset; - } - function parsePacket(chunk, p, len) { - return this._decipher.decrypt(chunk, p, len); - } - function onPayload(payload) { - this._onPacket(); - if (payload.length === 0) { - this._debug && this._debug("Inbound: Skipping empty packet payload"); - return; - } - payload = this._packetRW.read.read(payload); - const type = payload[0]; - if (type === MESSAGE.USERAUTH_SUCCESS && !this._server && !this._authenticated) { - this._authenticated = true; - if (this._kex.negotiated.cs.compress === "zlib@openssh.com") - this._packetRW.write = new ZlibPacketWriter(this); - if (this._kex.negotiated.sc.compress === "zlib@openssh.com") - this._packetRW.read = new ZlibPacketReader(); - } - const handler2 = MESSAGE_HANDLERS[type]; - if (handler2 === void 0) { - this._debug && this._debug(`Inbound: Unsupported message type: ${type}`); - return; - } - return handler2(this, payload); - } - function getCompatFlags(header) { - const software = header.versions.software; - let flags = 0; - for (const rule of COMPAT_CHECKS) { - if (typeof rule[0] === "string") { - if (software === rule[0]) - flags |= rule[1]; - } else if (rule[0].test(software)) { - flags |= rule[1]; - } - } - return flags; - } - function modesToBytes(modes) { - const keys = Object.keys(modes); - const bytes = Buffer.allocUnsafe(5 * keys.length + 1); - let b = 0; - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - if (key === "TTY_OP_END") - continue; - const opcode = TERMINAL_MODE[key]; - if (opcode === void 0) - continue; - const val = modes[key]; - if (typeof val === "number" && isFinite(val)) { - bytes[b++] = opcode; - bytes[b++] = val >>> 24; - bytes[b++] = val >>> 16; - bytes[b++] = val >>> 8; - bytes[b++] = val; - } - } - bytes[b++] = TERMINAL_MODE.TTY_OP_END; - if (b < bytes.length) - return bufferSlice(bytes, 0, b); - return bytes; - } - function sendExtInfo(proto) { - let serverSigAlgs = "ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521rsa-sha2-512,rsa-sha2-256,ssh-rsa,ssh-dss"; - if (eddsaSupported) - serverSigAlgs = `ssh-ed25519,${serverSigAlgs}`; - const algsLen = Buffer.byteLength(serverSigAlgs); - let p = proto._packetRW.write.allocStart; - const packet = proto._packetRW.write.alloc(1 + 4 + 4 + 15 + 4 + algsLen); - packet[p] = MESSAGE.EXT_INFO; - writeUInt32BE(packet, 1, ++p); - writeUInt32BE(packet, 15, p += 4); - packet.utf8Write("server-sig-algs", p += 4, 15); - writeUInt32BE(packet, algsLen, p += 15); - packet.utf8Write(serverSigAlgs, p += 4, algsLen); - proto._debug && proto._debug("Outbound: Sending EXT_INFO"); - sendPacket(proto, proto._packetRW.write.finalize(packet)); - } - module2.exports = Protocol; - } -}); - -// node_modules/ssh2/lib/protocol/node-fs-compat.js -var require_node_fs_compat = __commonJS({ - "node_modules/ssh2/lib/protocol/node-fs-compat.js"(exports2) { - "use strict"; - var assert = require("assert"); - var { inspect } = require("util"); - function addNumericalSeparator(val) { - let res = ""; - let i = val.length; - const start = val[0] === "-" ? 1 : 0; - for (; i >= start + 4; i -= 3) - res = `_${val.slice(i - 3, i)}${res}`; - return `${val.slice(0, i)}${res}`; - } - function oneOf(expected, thing) { - assert(typeof thing === "string", "`thing` has to be of type string"); - if (Array.isArray(expected)) { - const len = expected.length; - assert(len > 0, "At least one expected value needs to be specified"); - 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]}`; - } - return `of ${thing} ${expected[0]}`; - } - return `of ${thing} ${String(expected)}`; - } - exports2.ERR_INTERNAL_ASSERTION = class ERR_INTERNAL_ASSERTION extends Error { - constructor(message) { - super(); - Error.captureStackTrace(this, ERR_INTERNAL_ASSERTION); - const suffix = "This is caused by either a bug in ssh2 or incorrect usage of ssh2 internals.\nPlease open an issue with this stack trace at https://github.com/mscdex/ssh2/issues\n"; - this.message = message === void 0 ? suffix : `${message} -${suffix}`; - } - }; - var MAX_32BIT_INT = 2 ** 32; - var MAX_32BIT_BIGINT = (() => { - try { - return new Function("return 2n ** 32n")(); - } catch { - } - })(); - exports2.ERR_OUT_OF_RANGE = class ERR_OUT_OF_RANGE extends RangeError { - constructor(str, range, input, replaceDefaultBoolean) { - super(); - Error.captureStackTrace(this, ERR_OUT_OF_RANGE); - assert(range, 'Missing "range" argument'); - let msg = replaceDefaultBoolean ? str : `The value of "${str}" is out of range.`; - let received; - if (Number.isInteger(input) && Math.abs(input) > MAX_32BIT_INT) { - received = addNumericalSeparator(String(input)); - } else if (typeof input === "bigint") { - received = String(input); - if (input > MAX_32BIT_BIGINT || input < -MAX_32BIT_BIGINT) - received = addNumericalSeparator(received); - received += "n"; - } else { - received = inspect(input); - } - msg += ` It must be ${range}. Received ${received}`; - this.message = msg; - } - }; - var ERR_INVALID_ARG_TYPE = class _ERR_INVALID_ARG_TYPE extends TypeError { - constructor(name, expected, actual) { - super(); - Error.captureStackTrace(this, _ERR_INVALID_ARG_TYPE); - assert(typeof name === "string", `'name' must be a string`); - let determiner; - if (typeof expected === "string" && expected.startsWith("not ")) { - determiner = "must not be"; - expected = expected.replace(/^not /, ""); - } else { - determiner = "must be"; - } - let msg; - if (name.endsWith(" argument")) { - msg = `The ${name} ${determiner} ${oneOf(expected, "type")}`; - } else { - const type = name.includes(".") ? "property" : "argument"; - msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, "type")}`; - } - msg += `. Received type ${typeof actual}`; - this.message = msg; - } - }; - exports2.ERR_INVALID_ARG_TYPE = ERR_INVALID_ARG_TYPE; - exports2.validateNumber = function validateNumber(value, name) { - if (typeof value !== "number") - throw new ERR_INVALID_ARG_TYPE(name, "number", value); - }; - } -}); - -// node_modules/ssh2/lib/protocol/SFTP.js -var require_SFTP = __commonJS({ - "node_modules/ssh2/lib/protocol/SFTP.js"(exports2, module2) { - "use strict"; - var EventEmitter = require("events"); - var fs3 = require("fs"); - var { constants } = fs3; - var { - Readable: ReadableStream2, - Writable: WritableStream - } = require("stream"); - var { inherits, types: { isDate } } = require("util"); - var FastBuffer = Buffer[Symbol.species]; - var { - bufferCopy, - bufferSlice, - makeBufferParser, - writeUInt32BE - } = require_utils4(); - var ATTR = { - SIZE: 1, - UIDGID: 2, - PERMISSIONS: 4, - ACMODTIME: 8, - EXTENDED: 2147483648 - }; - var ATTRS_BUF = Buffer.alloc(28); - var STATUS_CODE = { - OK: 0, - EOF: 1, - NO_SUCH_FILE: 2, - PERMISSION_DENIED: 3, - FAILURE: 4, - BAD_MESSAGE: 5, - NO_CONNECTION: 6, - CONNECTION_LOST: 7, - OP_UNSUPPORTED: 8 - }; - var VALID_STATUS_CODES = new Map( - Object.values(STATUS_CODE).map((n) => [n, 1]) - ); - var STATUS_CODE_STR = { - [STATUS_CODE.OK]: "No error", - [STATUS_CODE.EOF]: "End of file", - [STATUS_CODE.NO_SUCH_FILE]: "No such file or directory", - [STATUS_CODE.PERMISSION_DENIED]: "Permission denied", - [STATUS_CODE.FAILURE]: "Failure", - [STATUS_CODE.BAD_MESSAGE]: "Bad message", - [STATUS_CODE.NO_CONNECTION]: "No connection", - [STATUS_CODE.CONNECTION_LOST]: "Connection lost", - [STATUS_CODE.OP_UNSUPPORTED]: "Operation unsupported" - }; - var REQUEST = { - INIT: 1, - OPEN: 3, - CLOSE: 4, - READ: 5, - WRITE: 6, - LSTAT: 7, - FSTAT: 8, - SETSTAT: 9, - FSETSTAT: 10, - OPENDIR: 11, - READDIR: 12, - REMOVE: 13, - MKDIR: 14, - RMDIR: 15, - REALPATH: 16, - STAT: 17, - RENAME: 18, - READLINK: 19, - SYMLINK: 20, - EXTENDED: 200 - }; - var RESPONSE = { - VERSION: 2, - STATUS: 101, - HANDLE: 102, - DATA: 103, - NAME: 104, - ATTRS: 105, - EXTENDED: 201 - }; - var OPEN_MODE = { - READ: 1, - WRITE: 2, - APPEND: 4, - CREAT: 8, - TRUNC: 16, - EXCL: 32 - }; - var PKT_RW_OVERHEAD = 2 * 1024; - var MAX_REQID = 2 ** 32 - 1; - var CLIENT_VERSION_BUFFER = Buffer.from([ - 0, - 0, - 0, - 5, - REQUEST.INIT, - 0, - 0, - 0, - 3 - /* version */ - ]); - var SERVER_VERSION_BUFFER = Buffer.from([ - 0, - 0, - 0, - 5, - RESPONSE.VERSION, - 0, - 0, - 0, - 3 - /* version */ - ]); - var RE_OPENSSH = /^SSH-2.0-(?:OpenSSH|dropbear)/; - var OPENSSH_MAX_PKT_LEN = 256 * 1024; - var bufferParser = makeBufferParser(); - var fakeStderr = { - readable: false, - writable: false, - push: (data) => { - }, - once: () => { - }, - on: () => { - }, - emit: () => { - }, - end: () => { - } - }; - function noop3() { - } - var SFTP = class extends EventEmitter { - constructor(client, chanInfo, cfg) { - super(); - if (typeof cfg !== "object" || !cfg) - cfg = {}; - const remoteIdentRaw = client._protocol._remoteIdentRaw; - this.server = !!cfg.server; - this._debug = typeof cfg.debug === "function" ? cfg.debug : void 0; - this._isOpenSSH = remoteIdentRaw && RE_OPENSSH.test(remoteIdentRaw); - this._version = -1; - this._extensions = {}; - this._biOpt = cfg.biOpt; - this._pktLenBytes = 0; - this._pktLen = 0; - this._pktPos = 0; - this._pktType = 0; - this._pktData = void 0; - this._writeReqid = -1; - this._requests = {}; - this._maxInPktLen = OPENSSH_MAX_PKT_LEN; - this._maxOutPktLen = 34e3; - this._maxReadLen = (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34e3) - PKT_RW_OVERHEAD; - this._maxWriteLen = (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34e3) - PKT_RW_OVERHEAD; - this.maxOpenHandles = void 0; - this._client = client; - this._protocol = client._protocol; - this._callbacks = []; - this._hasX11 = false; - this._exit = { - code: void 0, - signal: void 0, - dump: void 0, - desc: void 0 - }; - this._waitWindow = false; - this._chunkcb = void 0; - this._buffer = []; - this.type = chanInfo.type; - this.subtype = void 0; - this.incoming = chanInfo.incoming; - this.outgoing = chanInfo.outgoing; - this.stderr = fakeStderr; - this.readable = true; - } - // This handles incoming data to parse - push(data) { - if (data === null) { - cleanupRequests(this); - if (!this.readable) - return; - this.readable = false; - this.emit("end"); - return; - } - let p = 0; - while (p < data.length) { - if (this._pktLenBytes < 4) { - let nb = Math.min(4 - this._pktLenBytes, data.length - p); - this._pktLenBytes += nb; - while (nb--) - this._pktLen = (this._pktLen << 8) + data[p++]; - if (this._pktLenBytes < 4) - return; - if (this._pktLen === 0) - return doFatalSFTPError(this, "Invalid packet length"); - if (this._pktLen > this._maxInPktLen) { - const max = this._maxInPktLen; - return doFatalSFTPError( - this, - `Packet length ${this._pktLen} exceeds max length of ${max}` - ); - } - if (p >= data.length) - return; - } - if (this._pktPos < this._pktLen) { - const nb = Math.min(this._pktLen - this._pktPos, data.length - p); - if (p !== 0 || nb !== data.length) { - if (nb === this._pktLen) { - this._pkt = new FastBuffer(data.buffer, data.byteOffset + p, nb); - } else { - if (!this._pkt) - this._pkt = Buffer.allocUnsafe(this._pktLen); - this._pkt.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._pktPos - ); - } - } else if (nb === this._pktLen) { - this._pkt = data; - } else { - if (!this._pkt) - this._pkt = Buffer.allocUnsafe(this._pktLen); - this._pkt.set(data, this._pktPos); - } - p += nb; - this._pktPos += nb; - if (this._pktPos < this._pktLen) - return; - } - const type = this._pkt[0]; - const payload = this._pkt; - this._pktLen = 0; - this._pktLenBytes = 0; - this._pkt = void 0; - this._pktPos = 0; - const handler2 = this.server ? SERVER_HANDLERS[type] : CLIENT_HANDLERS[type]; - if (!handler2) - return doFatalSFTPError(this, `Unknown packet type ${type}`); - if (this._version === -1) { - if (this.server) { - if (type !== REQUEST.INIT) - return doFatalSFTPError(this, `Expected INIT packet, got ${type}`); - } else if (type !== RESPONSE.VERSION) { - return doFatalSFTPError(this, `Expected VERSION packet, got ${type}`); - } - } - if (handler2(this, payload) === false) - return; - } - } - end() { - this.destroy(); - } - destroy() { - if (this.outgoing.state === "open" || this.outgoing.state === "eof") { - this.outgoing.state = "closing"; - this._protocol.channelClose(this.outgoing.id); - } - } - _init() { - this._init = noop3; - if (!this.server) - sendOrBuffer(this, CLIENT_VERSION_BUFFER); - } - // =========================================================================== - // Client-specific =========================================================== - // =========================================================================== - createReadStream(path, options) { - if (this.server) - throw new Error("Client-only method called in server mode"); - return new ReadStream(this, path, options); - } - createWriteStream(path, options) { - if (this.server) - throw new Error("Client-only method called in server mode"); - return new WriteStream(this, path, options); - } - open(path, flags_, attrs, cb) { - if (this.server) - throw new Error("Client-only method called in server mode"); - if (typeof attrs === "function") { - cb = attrs; - attrs = void 0; - } - const flags = typeof flags_ === "number" ? flags_ : stringToFlags(flags_); - if (flags === null) - throw new Error(`Unknown flags string: ${flags_}`); - let attrsFlags = 0; - let attrsLen = 0; - if (typeof attrs === "string" || typeof attrs === "number") - attrs = { mode: attrs }; - if (typeof attrs === "object" && attrs !== null) { - attrs = attrsToBytes(attrs); - attrsFlags = attrs.flags; - attrsLen = attrs.nb; - } - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + 4 + attrsLen); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.OPEN; - const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - writeUInt32BE(buf, flags, p += pathLen); - writeUInt32BE(buf, attrsFlags, p += 4); - if (attrsLen) { - p += 4; - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - p += attrsLen; - } - this._requests[reqid] = { cb }; - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} OPEN` - ); - } - close(handle, cb) { - if (this.server) - throw new Error("Client-only method called in server mode"); - if (!Buffer.isBuffer(handle)) - throw new Error("handle is not a Buffer"); - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.CLOSE; - const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - writeUInt32BE(buf, handleLen, p); - buf.set(handle, p += 4); - this._requests[reqid] = { cb }; - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} CLOSE` - ); - } - read(handle, buf, off, len, position, cb) { - if (this.server) - throw new Error("Client-only method called in server mode"); - if (!Buffer.isBuffer(handle)) - throw new Error("handle is not a Buffer"); - if (!Buffer.isBuffer(buf)) - throw new Error("buffer is not a Buffer"); - if (off >= buf.length) - throw new Error("offset is out of bounds"); - if (off + len > buf.length) - throw new Error("length extends beyond buffer"); - if (position === null) - throw new Error("null position currently unsupported"); - read_(this, handle, buf, off, len, position, cb); - } - readData(handle, buf, off, len, position, cb) { - this.read(handle, buf, off, len, position, cb); - } - write(handle, buf, off, len, position, cb) { - if (this.server) - throw new Error("Client-only method called in server mode"); - if (!Buffer.isBuffer(handle)) - throw new Error("handle is not a Buffer"); - if (!Buffer.isBuffer(buf)) - throw new Error("buffer is not a Buffer"); - if (off > buf.length) - throw new Error("offset is out of bounds"); - if (off + len > buf.length) - throw new Error("length extends beyond buffer"); - if (position === null) - throw new Error("null position currently unsupported"); - if (!len) { - cb && process.nextTick(cb, void 0, 0); - return; - } - const maxDataLen = this._maxWriteLen; - const overflow = Math.max(len - maxDataLen, 0); - const origPosition = position; - if (overflow) - len = maxDataLen; - const handleLen = handle.length; - let p = 9; - const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4 + len); - writeUInt32BE(out, out.length - 4, 0); - out[4] = REQUEST.WRITE; - const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; - writeUInt32BE(out, reqid, 5); - writeUInt32BE(out, handleLen, p); - out.set(handle, p += 4); - p += handleLen; - for (let i = 7; i >= 0; --i) { - out[p + i] = position & 255; - position /= 256; - } - writeUInt32BE(out, len, p += 8); - bufferCopy(buf, out, off, off + len, p += 4); - this._requests[reqid] = { - cb: (err) => { - if (err) { - if (typeof cb === "function") - cb(err); - } else if (overflow) { - this.write( - handle, - buf, - off + len, - overflow, - origPosition + len, - cb - ); - } else if (typeof cb === "function") { - cb(void 0, off + len); - } - } - }; - const isSent = sendOrBuffer(this, out); - if (this._debug) { - const how = isSent ? "Sent" : "Buffered"; - this._debug(`SFTP: Outbound: ${how} WRITE (id:${reqid})`); - } - } - writeData(handle, buf, off, len, position, cb) { - this.write(handle, buf, off, len, position, cb); - } - fastGet(remotePath, localPath, opts, cb) { - if (this.server) - throw new Error("Client-only method called in server mode"); - fastXfer(this, fs3, remotePath, localPath, opts, cb); - } - fastPut(localPath, remotePath, opts, cb) { - if (this.server) - throw new Error("Client-only method called in server mode"); - fastXfer(fs3, this, localPath, remotePath, opts, cb); - } - readFile(path, options, callback_) { - if (this.server) - throw new Error("Client-only method called in server mode"); - let callback; - if (typeof callback_ === "function") { - callback = callback_; - } else if (typeof options === "function") { - callback = options; - options = void 0; - } - if (typeof options === "string") - options = { encoding: options, flag: "r" }; - else if (!options) - options = { encoding: null, flag: "r" }; - else if (typeof options !== "object") - throw new TypeError("Bad arguments"); - const encoding = options.encoding; - if (encoding && !Buffer.isEncoding(encoding)) - throw new Error(`Unknown encoding: ${encoding}`); - let size; - let buffer; - let buffers; - let pos = 0; - let handle; - let bytesRead = 0; - const flag = options.flag || "r"; - const read = () => { - if (size === 0) { - buffer = Buffer.allocUnsafe(8192); - this.read(handle, buffer, 0, 8192, bytesRead, afterRead); - } else { - this.read(handle, buffer, pos, size - pos, bytesRead, afterRead); - } - }; - const afterRead = (er, nbytes) => { - let eof; - if (er) { - eof = er.code === STATUS_CODE.EOF; - if (!eof) { - return this.close(handle, () => { - return callback && callback(er); - }); - } - } else { - eof = false; - } - if (eof || size === 0 && nbytes === 0) - return close(); - bytesRead += nbytes; - pos += nbytes; - if (size !== 0) { - if (pos === size) - close(); - else - read(); - } else { - buffers.push(bufferSlice(buffer, 0, nbytes)); - read(); - } - }; - afterRead._wantEOFError = true; - const close = () => { - this.close(handle, (er) => { - if (size === 0) { - buffer = Buffer.concat(buffers, pos); - } else if (pos < size) { - buffer = bufferSlice(buffer, 0, pos); - } - if (encoding) - buffer = buffer.toString(encoding); - return callback && callback(er, buffer); - }); - }; - this.open(path, flag, 438, (er, handle_) => { - if (er) - return callback && callback(er); - handle = handle_; - const tryStat = (er2, st) => { - if (er2) { - this.stat(path, (er_, st_) => { - if (er_) { - return this.close(handle, () => { - callback && callback(er2); - }); - } - tryStat(null, st_); - }); - return; - } - size = st.size || 0; - if (size === 0) { - buffers = []; - return read(); - } - buffer = Buffer.allocUnsafe(size); - read(); - }; - this.fstat(handle, tryStat); - }); - } - writeFile(path, data, options, callback_) { - if (this.server) - throw new Error("Client-only method called in server mode"); - let callback; - if (typeof callback_ === "function") { - callback = callback_; - } else if (typeof options === "function") { - callback = options; - options = void 0; - } - if (typeof options === "string") - options = { encoding: options, mode: 438, flag: "w" }; - else if (!options) - options = { encoding: "utf8", mode: 438, flag: "w" }; - else if (typeof options !== "object") - throw new TypeError("Bad arguments"); - if (options.encoding && !Buffer.isEncoding(options.encoding)) - throw new Error(`Unknown encoding: ${options.encoding}`); - const flag = options.flag || "w"; - this.open(path, flag, options.mode, (openErr, handle) => { - if (openErr) { - callback && callback(openErr); - } else { - const buffer = Buffer.isBuffer(data) ? data : Buffer.from("" + data, options.encoding || "utf8"); - const position = /a/.test(flag) ? null : 0; - if (position === null) { - const tryStat = (er, st) => { - if (er) { - this.stat(path, (er_, st_) => { - if (er_) { - return this.close(handle, () => { - callback && callback(er); - }); - } - tryStat(null, st_); - }); - return; - } - writeAll(this, handle, buffer, 0, buffer.length, st.size, callback); - }; - this.fstat(handle, tryStat); - return; - } - writeAll(this, handle, buffer, 0, buffer.length, position, callback); - } - }); - } - appendFile(path, data, options, callback_) { - if (this.server) - throw new Error("Client-only method called in server mode"); - let callback; - if (typeof callback_ === "function") { - callback = callback_; - } else if (typeof options === "function") { - callback = options; - options = void 0; - } - if (typeof options === "string") - options = { encoding: options, mode: 438, flag: "a" }; - else if (!options) - options = { encoding: "utf8", mode: 438, flag: "a" }; - else if (typeof options !== "object") - throw new TypeError("Bad arguments"); - if (!options.flag) - options = Object.assign({ flag: "a" }, options); - this.writeFile(path, data, options, callback); - } - exists(path, cb) { - if (this.server) - throw new Error("Client-only method called in server mode"); - this.stat(path, (err) => { - cb && cb(err ? false : true); - }); - } - unlink(filename, cb) { - if (this.server) - throw new Error("Client-only method called in server mode"); - const fnameLen = Buffer.byteLength(filename); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + fnameLen); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.REMOVE; - const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - writeUInt32BE(buf, fnameLen, p); - buf.utf8Write(filename, p += 4, fnameLen); - this._requests[reqid] = { cb }; - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} REMOVE` - ); - } - rename(oldPath, newPath, cb) { - if (this.server) - throw new Error("Client-only method called in server mode"); - const oldLen = Buffer.byteLength(oldPath); - const newLen = Buffer.byteLength(newPath); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + oldLen + 4 + newLen); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.RENAME; - const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - writeUInt32BE(buf, oldLen, p); - buf.utf8Write(oldPath, p += 4, oldLen); - writeUInt32BE(buf, newLen, p += oldLen); - buf.utf8Write(newPath, p += 4, newLen); - this._requests[reqid] = { cb }; - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} RENAME` - ); - } - mkdir(path, attrs, cb) { - if (this.server) - throw new Error("Client-only method called in server mode"); - let flags = 0; - let attrsLen = 0; - if (typeof attrs === "function") { - cb = attrs; - attrs = void 0; - } - if (typeof attrs === "object" && attrs !== null) { - attrs = attrsToBytes(attrs); - flags = attrs.flags; - attrsLen = attrs.nb; - } - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.MKDIR; - const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - writeUInt32BE(buf, flags, p += pathLen); - if (attrsLen) { - p += 4; - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - p += attrsLen; - } - this._requests[reqid] = { cb }; - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} MKDIR` - ); - } - rmdir(path, cb) { - if (this.server) - throw new Error("Client-only method called in server mode"); - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.RMDIR; - const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - this._requests[reqid] = { cb }; - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} RMDIR` - ); - } - readdir(where, opts, cb) { - if (this.server) - throw new Error("Client-only method called in server mode"); - if (typeof opts === "function") { - cb = opts; - opts = {}; - } - if (typeof opts !== "object" || opts === null) - opts = {}; - const doFilter = opts && opts.full ? false : true; - if (!Buffer.isBuffer(where) && typeof where !== "string") - throw new Error("missing directory handle or path"); - if (typeof where === "string") { - const entries = []; - let e = 0; - const reread = (err, handle) => { - if (err) - return cb(err); - this.readdir(handle, opts, (err2, list) => { - const eof = err2 && err2.code === STATUS_CODE.EOF; - if (err2 && !eof) - return this.close(handle, () => cb(err2)); - if (eof) { - return this.close(handle, (err3) => { - if (err3) - return cb(err3); - cb(void 0, entries); - }); - } - for (let i = 0; i < list.length; ++i, ++e) - entries[e] = list[i]; - reread(void 0, handle); - }); - }; - return this.opendir(where, reread); - } - const handleLen = where.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.READDIR; - const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - writeUInt32BE(buf, handleLen, p); - buf.set(where, p += 4); - this._requests[reqid] = { - cb: doFilter ? (err, list) => { - if (typeof cb !== "function") - return; - if (err) - return cb(err); - for (let i = list.length - 1; i >= 0; --i) { - if (list[i].filename === "." || list[i].filename === "..") - list.splice(i, 1); - } - cb(void 0, list); - } : cb - }; - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} READDIR` - ); - } - fstat(handle, cb) { - if (this.server) - throw new Error("Client-only method called in server mode"); - if (!Buffer.isBuffer(handle)) - throw new Error("handle is not a Buffer"); - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.FSTAT; - const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - writeUInt32BE(buf, handleLen, p); - buf.set(handle, p += 4); - this._requests[reqid] = { cb }; - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} FSTAT` - ); - } - stat(path, cb) { - if (this.server) - throw new Error("Client-only method called in server mode"); - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.STAT; - const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - this._requests[reqid] = { cb }; - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} STAT` - ); - } - lstat(path, cb) { - if (this.server) - throw new Error("Client-only method called in server mode"); - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.LSTAT; - const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - this._requests[reqid] = { cb }; - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} LSTAT` - ); - } - opendir(path, cb) { - if (this.server) - throw new Error("Client-only method called in server mode"); - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.OPENDIR; - const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - this._requests[reqid] = { cb }; - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} OPENDIR` - ); - } - setstat(path, attrs, cb) { - if (this.server) - throw new Error("Client-only method called in server mode"); - let flags = 0; - let attrsLen = 0; - if (typeof attrs === "object" && attrs !== null) { - attrs = attrsToBytes(attrs); - flags = attrs.flags; - attrsLen = attrs.nb; - } else if (typeof attrs === "function") { - cb = attrs; - } - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.SETSTAT; - const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - writeUInt32BE(buf, flags, p += pathLen); - if (attrsLen) { - p += 4; - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - p += attrsLen; - } - this._requests[reqid] = { cb }; - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} SETSTAT` - ); - } - fsetstat(handle, attrs, cb) { - if (this.server) - throw new Error("Client-only method called in server mode"); - if (!Buffer.isBuffer(handle)) - throw new Error("handle is not a Buffer"); - let flags = 0; - let attrsLen = 0; - if (typeof attrs === "object" && attrs !== null) { - attrs = attrsToBytes(attrs); - flags = attrs.flags; - attrsLen = attrs.nb; - } else if (typeof attrs === "function") { - cb = attrs; - } - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 4 + attrsLen); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.FSETSTAT; - const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - writeUInt32BE(buf, handleLen, p); - buf.set(handle, p += 4); - writeUInt32BE(buf, flags, p += handleLen); - if (attrsLen) { - p += 4; - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - p += attrsLen; - } - this._requests[reqid] = { cb }; - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} FSETSTAT` - ); - } - futimes(handle, atime, mtime, cb) { - return this.fsetstat(handle, { - atime: toUnixTimestamp(atime), - mtime: toUnixTimestamp(mtime) - }, cb); - } - utimes(path, atime, mtime, cb) { - return this.setstat(path, { - atime: toUnixTimestamp(atime), - mtime: toUnixTimestamp(mtime) - }, cb); - } - fchown(handle, uid, gid, cb) { - return this.fsetstat(handle, { - uid, - gid - }, cb); - } - chown(path, uid, gid, cb) { - return this.setstat(path, { - uid, - gid - }, cb); - } - fchmod(handle, mode, cb) { - return this.fsetstat(handle, { - mode - }, cb); - } - chmod(path, mode, cb) { - return this.setstat(path, { - mode - }, cb); - } - readlink(path, cb) { - if (this.server) - throw new Error("Client-only method called in server mode"); - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.READLINK; - const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - this._requests[reqid] = { - cb: (err, names) => { - if (typeof cb !== "function") - return; - if (err) - return cb(err); - if (!names || !names.length) - return cb(new Error("Response missing link info")); - cb(void 0, names[0].filename); - } - }; - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} READLINK` - ); - } - symlink(targetPath, linkPath, cb) { - if (this.server) - throw new Error("Client-only method called in server mode"); - const linkLen = Buffer.byteLength(linkPath); - const targetLen = Buffer.byteLength(targetPath); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + linkLen + 4 + targetLen); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.SYMLINK; - const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - if (this._isOpenSSH) { - writeUInt32BE(buf, targetLen, p); - buf.utf8Write(targetPath, p += 4, targetLen); - writeUInt32BE(buf, linkLen, p += targetLen); - buf.utf8Write(linkPath, p += 4, linkLen); - } else { - writeUInt32BE(buf, linkLen, p); - buf.utf8Write(linkPath, p += 4, linkLen); - writeUInt32BE(buf, targetLen, p += linkLen); - buf.utf8Write(targetPath, p += 4, targetLen); - } - this._requests[reqid] = { cb }; - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} SYMLINK` - ); - } - realpath(path, cb) { - if (this.server) - throw new Error("Client-only method called in server mode"); - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.REALPATH; - const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - this._requests[reqid] = { - cb: (err, names) => { - if (typeof cb !== "function") - return; - if (err) - return cb(err); - if (!names || !names.length) - return cb(new Error("Response missing path info")); - cb(void 0, names[0].filename); - } - }; - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} REALPATH` - ); - } - // extended requests - ext_openssh_rename(oldPath, newPath, cb) { - if (this.server) - throw new Error("Client-only method called in server mode"); - const ext = this._extensions["posix-rename@openssh.com"]; - if (!ext || ext !== "1") - throw new Error("Server does not support this extended request"); - const oldLen = Buffer.byteLength(oldPath); - const newLen = Buffer.byteLength(newPath); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 24 + 4 + oldLen + 4 + newLen); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - writeUInt32BE(buf, 24, p); - buf.utf8Write("posix-rename@openssh.com", p += 4, 24); - writeUInt32BE(buf, oldLen, p += 24); - buf.utf8Write(oldPath, p += 4, oldLen); - writeUInt32BE(buf, newLen, p += oldLen); - buf.utf8Write(newPath, p += 4, newLen); - this._requests[reqid] = { cb }; - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const which = isBuffered ? "Buffered" : "Sending"; - this._debug(`SFTP: Outbound: ${which} posix-rename@openssh.com`); - } - } - ext_openssh_statvfs(path, cb) { - if (this.server) - throw new Error("Client-only method called in server mode"); - const ext = this._extensions["statvfs@openssh.com"]; - if (!ext || ext !== "2") - throw new Error("Server does not support this extended request"); - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 19 + 4 + pathLen); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - writeUInt32BE(buf, 19, p); - buf.utf8Write("statvfs@openssh.com", p += 4, 19); - writeUInt32BE(buf, pathLen, p += 19); - buf.utf8Write(path, p += 4, pathLen); - this._requests[reqid] = { extended: "statvfs@openssh.com", cb }; - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const which = isBuffered ? "Buffered" : "Sending"; - this._debug(`SFTP: Outbound: ${which} statvfs@openssh.com`); - } - } - ext_openssh_fstatvfs(handle, cb) { - if (this.server) - throw new Error("Client-only method called in server mode"); - const ext = this._extensions["fstatvfs@openssh.com"]; - if (!ext || ext !== "2") - throw new Error("Server does not support this extended request"); - if (!Buffer.isBuffer(handle)) - throw new Error("handle is not a Buffer"); - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + handleLen); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - writeUInt32BE(buf, 20, p); - buf.utf8Write("fstatvfs@openssh.com", p += 4, 20); - writeUInt32BE(buf, handleLen, p += 20); - buf.set(handle, p += 4); - this._requests[reqid] = { extended: "fstatvfs@openssh.com", cb }; - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const which = isBuffered ? "Buffered" : "Sending"; - this._debug(`SFTP: Outbound: ${which} fstatvfs@openssh.com`); - } - } - ext_openssh_hardlink(oldPath, newPath, cb) { - if (this.server) - throw new Error("Client-only method called in server mode"); - const ext = this._extensions["hardlink@openssh.com"]; - if (ext !== "1") - throw new Error("Server does not support this extended request"); - const oldLen = Buffer.byteLength(oldPath); - const newLen = Buffer.byteLength(newPath); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + oldLen + 4 + newLen); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - writeUInt32BE(buf, 20, p); - buf.utf8Write("hardlink@openssh.com", p += 4, 20); - writeUInt32BE(buf, oldLen, p += 20); - buf.utf8Write(oldPath, p += 4, oldLen); - writeUInt32BE(buf, newLen, p += oldLen); - buf.utf8Write(newPath, p += 4, newLen); - this._requests[reqid] = { cb }; - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const which = isBuffered ? "Buffered" : "Sending"; - this._debug(`SFTP: Outbound: ${which} hardlink@openssh.com`); - } - } - ext_openssh_fsync(handle, cb) { - if (this.server) - throw new Error("Client-only method called in server mode"); - const ext = this._extensions["fsync@openssh.com"]; - if (ext !== "1") - throw new Error("Server does not support this extended request"); - if (!Buffer.isBuffer(handle)) - throw new Error("handle is not a Buffer"); - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 17 + 4 + handleLen); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - writeUInt32BE(buf, 17, p); - buf.utf8Write("fsync@openssh.com", p += 4, 17); - writeUInt32BE(buf, handleLen, p += 17); - buf.set(handle, p += 4); - this._requests[reqid] = { cb }; - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} fsync@openssh.com` - ); - } - ext_openssh_lsetstat(path, attrs, cb) { - if (this.server) - throw new Error("Client-only method called in server mode"); - const ext = this._extensions["lsetstat@openssh.com"]; - if (ext !== "1") - throw new Error("Server does not support this extended request"); - let flags = 0; - let attrsLen = 0; - if (typeof attrs === "object" && attrs !== null) { - attrs = attrsToBytes(attrs); - flags = attrs.flags; - attrsLen = attrs.nb; - } else if (typeof attrs === "function") { - cb = attrs; - } - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + pathLen + 4 + attrsLen); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - writeUInt32BE(buf, 20, p); - buf.utf8Write("lsetstat@openssh.com", p += 4, 20); - writeUInt32BE(buf, pathLen, p += 20); - buf.utf8Write(path, p += 4, pathLen); - writeUInt32BE(buf, flags, p += pathLen); - if (attrsLen) { - p += 4; - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - p += attrsLen; - } - this._requests[reqid] = { cb }; - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const status = isBuffered ? "Buffered" : "Sending"; - this._debug(`SFTP: Outbound: ${status} lsetstat@openssh.com`); - } - } - ext_openssh_expandPath(path, cb) { - if (this.server) - throw new Error("Client-only method called in server mode"); - const ext = this._extensions["expand-path@openssh.com"]; - if (ext !== "1") - throw new Error("Server does not support this extended request"); - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 23 + 4 + pathLen); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - writeUInt32BE(buf, 23, p); - buf.utf8Write("expand-path@openssh.com", p += 4, 23); - writeUInt32BE(buf, pathLen, p += 20); - buf.utf8Write(path, p += 4, pathLen); - this._requests[reqid] = { - cb: (err, names) => { - if (typeof cb !== "function") - return; - if (err) - return cb(err); - if (!names || !names.length) - return cb(new Error("Response missing expanded path")); - cb(void 0, names[0].filename); - } - }; - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const status = isBuffered ? "Buffered" : "Sending"; - this._debug(`SFTP: Outbound: ${status} expand-path@openssh.com`); - } - } - ext_copy_data(srcHandle, srcOffset, len, dstHandle, dstOffset, cb) { - if (this.server) - throw new Error("Client-only method called in server mode"); - const ext = this._extensions["copy-data"]; - if (ext !== "1") - throw new Error("Server does not support this extended request"); - if (!Buffer.isBuffer(srcHandle)) - throw new Error("Source handle is not a Buffer"); - if (!Buffer.isBuffer(dstHandle)) - throw new Error("Destination handle is not a Buffer"); - let p = 0; - const buf = Buffer.allocUnsafe( - 4 + 1 + 4 + 4 + 9 + 4 + srcHandle.length + 8 + 8 + 4 + dstHandle.length + 8 - ); - writeUInt32BE(buf, buf.length - 4, p); - p += 4; - buf[p] = REQUEST.EXTENDED; - ++p; - const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; - writeUInt32BE(buf, reqid, p); - p += 4; - writeUInt32BE(buf, 9, p); - p += 4; - buf.utf8Write("copy-data", p, 9); - p += 9; - writeUInt32BE(buf, srcHandle.length, p); - p += 4; - buf.set(srcHandle, p); - p += srcHandle.length; - for (let i = 7; i >= 0; --i) { - buf[p + i] = srcOffset & 255; - srcOffset /= 256; - } - p += 8; - for (let i = 7; i >= 0; --i) { - buf[p + i] = len & 255; - len /= 256; - } - p += 8; - writeUInt32BE(buf, dstHandle.length, p); - p += 4; - buf.set(dstHandle, p); - p += dstHandle.length; - for (let i = 7; i >= 0; --i) { - buf[p + i] = dstOffset & 255; - dstOffset /= 256; - } - this._requests[reqid] = { cb }; - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const status = isBuffered ? "Buffered" : "Sending"; - this._debug(`SFTP: Outbound: ${status} copy-data`); - } - } - ext_home_dir(username, cb) { - if (this.server) - throw new Error("Client-only method called in server mode"); - const ext = this._extensions["home-directory"]; - if (ext !== "1") - throw new Error("Server does not support this extended request"); - if (typeof username !== "string") - throw new TypeError("username is not a string"); - let p = 0; - const usernameLen = Buffer.byteLength(username); - const buf = Buffer.allocUnsafe( - 4 + 1 + 4 + 4 + 14 + 4 + usernameLen - ); - writeUInt32BE(buf, buf.length - 4, p); - p += 4; - buf[p] = REQUEST.EXTENDED; - ++p; - const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; - writeUInt32BE(buf, reqid, p); - p += 4; - writeUInt32BE(buf, 14, p); - p += 4; - buf.utf8Write("home-directory", p, 14); - p += 14; - writeUInt32BE(buf, usernameLen, p); - p += 4; - buf.utf8Write(username, p, usernameLen); - p += usernameLen; - this._requests[reqid] = { - cb: (err, names) => { - if (typeof cb !== "function") - return; - if (err) - return cb(err); - if (!names || !names.length) - return cb(new Error("Response missing home directory")); - cb(void 0, names[0].filename); - } - }; - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const status = isBuffered ? "Buffered" : "Sending"; - this._debug(`SFTP: Outbound: ${status} home-directory`); - } - } - ext_users_groups(uids, gids, cb) { - if (this.server) - throw new Error("Client-only method called in server mode"); - const ext = this._extensions["users-groups-by-id@openssh.com"]; - if (ext !== "1") - throw new Error("Server does not support this extended request"); - if (!Array.isArray(uids)) - throw new TypeError("uids is not an array"); - for (const val of uids) { - if (!Number.isInteger(val) || val < 0 || val > 2 ** 32 - 1) - throw new Error("uid values must all be 32-bit unsigned integers"); - } - if (!Array.isArray(gids)) - throw new TypeError("gids is not an array"); - for (const val of gids) { - if (!Number.isInteger(val) || val < 0 || val > 2 ** 32 - 1) - throw new Error("gid values must all be 32-bit unsigned integers"); - } - let p = 0; - const buf = Buffer.allocUnsafe( - 4 + 1 + 4 + 4 + 30 + 4 + 4 * uids.length + 4 + 4 * gids.length - ); - writeUInt32BE(buf, buf.length - 4, p); - p += 4; - buf[p] = REQUEST.EXTENDED; - ++p; - const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; - writeUInt32BE(buf, reqid, p); - p += 4; - writeUInt32BE(buf, 30, p); - p += 4; - buf.utf8Write("users-groups-by-id@openssh.com", p, 30); - p += 30; - writeUInt32BE(buf, 4 * uids.length, p); - p += 4; - for (const val of uids) { - writeUInt32BE(buf, val, p); - p += 4; - } - writeUInt32BE(buf, 4 * gids.length, p); - p += 4; - for (const val of gids) { - writeUInt32BE(buf, val, p); - p += 4; - } - this._requests[reqid] = { extended: "users-groups-by-id@openssh.com", cb }; - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const status = isBuffered ? "Buffered" : "Sending"; - this._debug(`SFTP: Outbound: ${status} users-groups-by-id@openssh.com`); - } - } - // =========================================================================== - // Server-specific =========================================================== - // =========================================================================== - handle(reqid, handle) { - if (!this.server) - throw new Error("Server-only method called in client mode"); - if (!Buffer.isBuffer(handle)) - throw new Error("handle is not a Buffer"); - const handleLen = handle.length; - if (handleLen > 256) - throw new Error("handle too large (> 256 bytes)"); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.HANDLE; - writeUInt32BE(buf, reqid, 5); - writeUInt32BE(buf, handleLen, p); - if (handleLen) - buf.set(handle, p += 4); - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} HANDLE` - ); - } - status(reqid, code, message) { - if (!this.server) - throw new Error("Server-only method called in client mode"); - if (!VALID_STATUS_CODES.has(code)) - throw new Error(`Bad status code: ${code}`); - message || (message = ""); - const msgLen = Buffer.byteLength(message); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 4 + msgLen + 4); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.STATUS; - writeUInt32BE(buf, reqid, 5); - writeUInt32BE(buf, code, p); - writeUInt32BE(buf, msgLen, p += 4); - p += 4; - if (msgLen) { - buf.utf8Write(message, p, msgLen); - p += msgLen; - } - writeUInt32BE(buf, 0, p); - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} STATUS` - ); - } - data(reqid, data, encoding) { - if (!this.server) - throw new Error("Server-only method called in client mode"); - const isBuffer = Buffer.isBuffer(data); - if (!isBuffer && typeof data !== "string") - throw new Error("data is not a Buffer or string"); - let isUTF8; - if (!isBuffer && !encoding) { - encoding = void 0; - isUTF8 = true; - } - const dataLen = isBuffer ? data.length : Buffer.byteLength(data, encoding); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + dataLen); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.DATA; - writeUInt32BE(buf, reqid, 5); - writeUInt32BE(buf, dataLen, p); - if (dataLen) { - if (isBuffer) - buf.set(data, p += 4); - else if (isUTF8) - buf.utf8Write(data, p += 4, dataLen); - else - buf.write(data, p += 4, dataLen, encoding); - } - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} DATA` - ); - } - name(reqid, names) { - if (!this.server) - throw new Error("Server-only method called in client mode"); - if (!Array.isArray(names)) { - if (typeof names !== "object" || names === null) - throw new Error("names is not an object or array"); - names = [names]; - } - const count = names.length; - let namesLen = 0; - let nameAttrs; - const attrs = []; - for (let i = 0; i < count; ++i) { - const name = names[i]; - const filename = !name || !name.filename || typeof name.filename !== "string" ? "" : name.filename; - namesLen += 4 + Buffer.byteLength(filename); - const longname = !name || !name.longname || typeof name.longname !== "string" ? "" : name.longname; - namesLen += 4 + Buffer.byteLength(longname); - if (typeof name.attrs === "object" && name.attrs !== null) { - nameAttrs = attrsToBytes(name.attrs); - namesLen += 4 + nameAttrs.nb; - if (nameAttrs.nb) { - let bytes; - if (nameAttrs.nb === ATTRS_BUF.length) { - bytes = new Uint8Array(ATTRS_BUF); - } else { - bytes = new Uint8Array(nameAttrs.nb); - bufferCopy(ATTRS_BUF, bytes, 0, nameAttrs.nb, 0); - } - nameAttrs.bytes = bytes; - } - attrs.push(nameAttrs); - } else { - namesLen += 4; - attrs.push(null); - } - } - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + namesLen); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.NAME; - writeUInt32BE(buf, reqid, 5); - writeUInt32BE(buf, count, p); - p += 4; - for (let i = 0; i < count; ++i) { - const name = names[i]; - { - const filename = !name || !name.filename || typeof name.filename !== "string" ? "" : name.filename; - const len = Buffer.byteLength(filename); - writeUInt32BE(buf, len, p); - p += 4; - if (len) { - buf.utf8Write(filename, p, len); - p += len; - } - } - { - const longname = !name || !name.longname || typeof name.longname !== "string" ? "" : name.longname; - const len = Buffer.byteLength(longname); - writeUInt32BE(buf, len, p); - p += 4; - if (len) { - buf.utf8Write(longname, p, len); - p += len; - } - } - const attr = attrs[i]; - if (attr) { - writeUInt32BE(buf, attr.flags, p); - p += 4; - if (attr.flags && attr.bytes) { - buf.set(attr.bytes, p); - p += attr.nb; - } - } else { - writeUInt32BE(buf, 0, p); - p += 4; - } - } - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} NAME` - ); - } - attrs(reqid, attrs) { - if (!this.server) - throw new Error("Server-only method called in client mode"); - if (typeof attrs !== "object" || attrs === null) - throw new Error("attrs is not an object"); - attrs = attrsToBytes(attrs); - const flags = attrs.flags; - const attrsLen = attrs.nb; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + attrsLen); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.ATTRS; - writeUInt32BE(buf, reqid, 5); - writeUInt32BE(buf, flags, p); - if (attrsLen) { - p += 4; - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - p += attrsLen; - } - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} ATTRS` - ); - } - }; - function tryCreateBuffer(size) { - try { - return Buffer.allocUnsafe(size); - } catch (ex) { - return ex; - } - } - function read_(self2, handle, buf, off, len, position, cb, req_) { - const maxDataLen = self2._maxReadLen; - const overflow = Math.max(len - maxDataLen, 0); - if (overflow) - len = maxDataLen; - const handleLen = handle.length; - let p = 9; - let pos = position; - const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4); - writeUInt32BE(out, out.length - 4, 0); - out[4] = REQUEST.READ; - const reqid = self2._writeReqid = self2._writeReqid + 1 & MAX_REQID; - writeUInt32BE(out, reqid, 5); - writeUInt32BE(out, handleLen, p); - out.set(handle, p += 4); - p += handleLen; - for (let i = 7; i >= 0; --i) { - out[p + i] = pos & 255; - pos /= 256; - } - writeUInt32BE(out, len, p += 8); - if (typeof cb !== "function") - cb = noop3; - const req = req_ || { - nb: 0, - position, - off, - origOff: off, - len: void 0, - overflow: void 0, - cb: (err, data, nb) => { - const len2 = req.len; - const overflow2 = req.overflow; - if (err) { - if (cb._wantEOFError || err.code !== STATUS_CODE.EOF) - return cb(err); - } else if (nb > len2) { - return cb(new Error("Received more data than requested")); - } else if (nb === len2 && overflow2) { - req.nb += nb; - req.position += nb; - req.off += nb; - read_(self2, handle, buf, req.off, overflow2, req.position, cb, req); - return; - } - nb = nb || 0; - if (req.origOff === 0 && buf.length === req.nb) - data = buf; - else - data = bufferSlice(buf, req.origOff, req.origOff + req.nb + nb); - cb(void 0, req.nb + nb, data, req.position); - }, - buffer: void 0 - }; - req.len = len; - req.overflow = overflow; - req.buffer = bufferSlice(buf, off, off + len); - self2._requests[reqid] = req; - const isBuffered = sendOrBuffer(self2, out); - self2._debug && self2._debug( - `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} READ` - ); - } - function fastXfer(src, dst, srcPath, dstPath, opts, cb) { - let concurrency = 64; - let chunkSize = 32768; - let onstep; - let mode; - let fileSize; - if (typeof opts === "function") { - cb = opts; - } else if (typeof opts === "object" && opts !== null) { - if (typeof opts.concurrency === "number" && opts.concurrency > 0 && !isNaN(opts.concurrency)) { - concurrency = opts.concurrency; - } - if (typeof opts.chunkSize === "number" && opts.chunkSize > 0 && !isNaN(opts.chunkSize)) { - chunkSize = opts.chunkSize; - } - if (typeof opts.fileSize === "number" && opts.fileSize > 0 && !isNaN(opts.fileSize)) { - fileSize = opts.fileSize; - } - if (typeof opts.step === "function") - onstep = opts.step; - if (typeof opts.mode === "string" || typeof opts.mode === "number") - mode = modeNum(opts.mode); - } - let fsize; - let pdst = 0; - let total = 0; - let hadError = false; - let srcHandle; - let dstHandle; - let readbuf; - let bufsize = chunkSize * concurrency; - function onerror(err) { - if (hadError) - return; - hadError = true; - let left = 0; - let cbfinal; - if (srcHandle || dstHandle) { - cbfinal = () => { - if (--left === 0) - cb(err); - }; - if (srcHandle && (src === fs3 || src.outgoing.state === "open")) - ++left; - if (dstHandle && (dst === fs3 || dst.outgoing.state === "open")) - ++left; - if (srcHandle && (src === fs3 || src.outgoing.state === "open")) - src.close(srcHandle, cbfinal); - if (dstHandle && (dst === fs3 || dst.outgoing.state === "open")) - dst.close(dstHandle, cbfinal); - } else { - cb(err); - } - } - src.open(srcPath, "r", (err, sourceHandle) => { - if (err) - return onerror(err); - srcHandle = sourceHandle; - if (fileSize === void 0) - src.fstat(srcHandle, tryStat); - else - tryStat(null, { size: fileSize }); - function tryStat(err2, attrs) { - if (err2) { - if (src !== fs3) { - src.stat(srcPath, (err_, attrs_) => { - if (err_) - return onerror(err2); - tryStat(null, attrs_); - }); - return; - } - return onerror(err2); - } - fsize = attrs.size; - dst.open(dstPath, "w", (err3, destHandle) => { - if (err3) - return onerror(err3); - dstHandle = destHandle; - if (fsize <= 0) - return onerror(); - while (bufsize > fsize) { - if (concurrency === 1) { - bufsize = fsize; - break; - } - bufsize -= chunkSize; - --concurrency; - } - readbuf = tryCreateBuffer(bufsize); - if (readbuf instanceof Error) - return onerror(readbuf); - if (mode !== void 0) { - dst.fchmod(dstHandle, mode, function tryAgain(err4) { - if (err4) { - dst.chmod(dstPath, mode, (err_) => tryAgain()); - return; - } - startReads(); - }); - } else { - startReads(); - } - function onread(err4, nb, data, dstpos, datapos, origChunkLen) { - if (err4) - return onerror(err4); - datapos = datapos || 0; - dst.write(dstHandle, readbuf, datapos, nb, dstpos, writeCb); - function writeCb(err5) { - if (err5) - return onerror(err5); - total += nb; - onstep && onstep(total, nb, fsize); - if (nb < origChunkLen) - return singleRead(datapos, dstpos + nb, origChunkLen - nb); - if (total === fsize) { - dst.close(dstHandle, (err6) => { - dstHandle = void 0; - if (err6) - return onerror(err6); - src.close(srcHandle, (err7) => { - srcHandle = void 0; - if (err7) - return onerror(err7); - cb(); - }); - }); - return; - } - if (pdst >= fsize) - return; - const chunk = pdst + chunkSize > fsize ? fsize - pdst : chunkSize; - singleRead(datapos, pdst, chunk); - pdst += chunk; - } - } - function makeCb(psrc, pdst2, chunk) { - return (err4, nb, data) => { - onread(err4, nb, data, pdst2, psrc, chunk); - }; - } - function singleRead(psrc, pdst2, chunk) { - src.read( - srcHandle, - readbuf, - psrc, - chunk, - pdst2, - makeCb(psrc, pdst2, chunk) - ); - } - function startReads() { - let reads = 0; - let psrc = 0; - while (pdst < fsize && reads < concurrency) { - const chunk = pdst + chunkSize > fsize ? fsize - pdst : chunkSize; - singleRead(psrc, pdst, chunk); - psrc += chunk; - pdst += chunk; - ++reads; - } - } - }); - } - }); - } - function writeAll(sftp, handle, buffer, offset, length, position, callback_) { - const callback = typeof callback_ === "function" ? callback_ : void 0; - sftp.write( - handle, - buffer, - offset, - length, - position, - (writeErr, written) => { - if (writeErr) { - return sftp.close(handle, () => { - callback && callback(writeErr); - }); - } - if (written === length) { - sftp.close(handle, callback); - } else { - offset += written; - length -= written; - position += written; - writeAll(sftp, handle, buffer, offset, length, position, callback); - } - } - ); - } - var Stats = class { - constructor(initial) { - this.mode = initial && initial.mode; - this.uid = initial && initial.uid; - this.gid = initial && initial.gid; - this.size = initial && initial.size; - this.atime = initial && initial.atime; - this.mtime = initial && initial.mtime; - this.extended = initial && initial.extended; - } - isDirectory() { - return (this.mode & constants.S_IFMT) === constants.S_IFDIR; - } - isFile() { - return (this.mode & constants.S_IFMT) === constants.S_IFREG; - } - isBlockDevice() { - return (this.mode & constants.S_IFMT) === constants.S_IFBLK; - } - isCharacterDevice() { - return (this.mode & constants.S_IFMT) === constants.S_IFCHR; - } - isSymbolicLink() { - return (this.mode & constants.S_IFMT) === constants.S_IFLNK; - } - isFIFO() { - return (this.mode & constants.S_IFMT) === constants.S_IFIFO; - } - isSocket() { - return (this.mode & constants.S_IFMT) === constants.S_IFSOCK; - } - }; - function attrsToBytes(attrs) { - let flags = 0; - let nb = 0; - if (typeof attrs === "object" && attrs !== null) { - if (typeof attrs.size === "number") { - flags |= ATTR.SIZE; - const val = attrs.size; - ATTRS_BUF[nb++] = val / 72057594037927940; - ATTRS_BUF[nb++] = val / 281474976710656; - ATTRS_BUF[nb++] = val / 1099511627776; - ATTRS_BUF[nb++] = val / 4294967296; - ATTRS_BUF[nb++] = val / 16777216; - ATTRS_BUF[nb++] = val / 65536; - ATTRS_BUF[nb++] = val / 256; - ATTRS_BUF[nb++] = val; - } - if (typeof attrs.uid === "number" && typeof attrs.gid === "number") { - flags |= ATTR.UIDGID; - const uid = attrs.uid; - const gid = attrs.gid; - ATTRS_BUF[nb++] = uid >>> 24; - ATTRS_BUF[nb++] = uid >>> 16; - ATTRS_BUF[nb++] = uid >>> 8; - ATTRS_BUF[nb++] = uid; - ATTRS_BUF[nb++] = gid >>> 24; - ATTRS_BUF[nb++] = gid >>> 16; - ATTRS_BUF[nb++] = gid >>> 8; - ATTRS_BUF[nb++] = gid; - } - if (typeof attrs.mode === "number" || typeof attrs.mode === "string") { - const mode = modeNum(attrs.mode); - flags |= ATTR.PERMISSIONS; - ATTRS_BUF[nb++] = mode >>> 24; - ATTRS_BUF[nb++] = mode >>> 16; - ATTRS_BUF[nb++] = mode >>> 8; - ATTRS_BUF[nb++] = mode; - } - if ((typeof attrs.atime === "number" || isDate(attrs.atime)) && (typeof attrs.mtime === "number" || isDate(attrs.mtime))) { - const atime = toUnixTimestamp(attrs.atime); - const mtime = toUnixTimestamp(attrs.mtime); - flags |= ATTR.ACMODTIME; - ATTRS_BUF[nb++] = atime >>> 24; - ATTRS_BUF[nb++] = atime >>> 16; - ATTRS_BUF[nb++] = atime >>> 8; - ATTRS_BUF[nb++] = atime; - ATTRS_BUF[nb++] = mtime >>> 24; - ATTRS_BUF[nb++] = mtime >>> 16; - ATTRS_BUF[nb++] = mtime >>> 8; - ATTRS_BUF[nb++] = mtime; - } - } - return { flags, nb }; - } - function toUnixTimestamp(time) { - if (typeof time === "number" && time === time) - return time; - if (isDate(time)) - return parseInt(time.getTime() / 1e3, 10); - throw new Error(`Cannot parse time: ${time}`); - } - function modeNum(mode) { - if (typeof mode === "number" && mode === mode) - return mode; - if (typeof mode === "string") - return modeNum(parseInt(mode, 8)); - throw new Error(`Cannot parse mode: ${mode}`); - } - var stringFlagMap = { - "r": OPEN_MODE.READ, - "r+": OPEN_MODE.READ | OPEN_MODE.WRITE, - "w": OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE, - "wx": OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, - "xw": OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, - "w+": OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE, - "wx+": OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE | OPEN_MODE.EXCL, - "xw+": OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE | OPEN_MODE.EXCL, - "a": OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE, - "ax": OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, - "xa": OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, - "a+": OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE, - "ax+": OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE | OPEN_MODE.EXCL, - "xa+": OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE | OPEN_MODE.EXCL - }; - function stringToFlags(str) { - const flags = stringFlagMap[str]; - return flags !== void 0 ? flags : null; - } - var flagsToString = (() => { - const stringFlagMapKeys = Object.keys(stringFlagMap); - return (flags) => { - for (let i = 0; i < stringFlagMapKeys.length; ++i) { - const key = stringFlagMapKeys[i]; - if (stringFlagMap[key] === flags) - return key; - } - return null; - }; - })(); - function readAttrs(biOpt) { - const flags = bufferParser.readUInt32BE(); - if (flags === void 0) - return; - const attrs = new Stats(); - if (flags & ATTR.SIZE) { - const size = bufferParser.readUInt64BE(biOpt); - if (size === void 0) - return; - attrs.size = size; - } - if (flags & ATTR.UIDGID) { - const uid = bufferParser.readUInt32BE(); - const gid = bufferParser.readUInt32BE(); - if (gid === void 0) - return; - attrs.uid = uid; - attrs.gid = gid; - } - if (flags & ATTR.PERMISSIONS) { - const mode = bufferParser.readUInt32BE(); - if (mode === void 0) - return; - attrs.mode = mode; - } - if (flags & ATTR.ACMODTIME) { - const atime = bufferParser.readUInt32BE(); - const mtime = bufferParser.readUInt32BE(); - if (mtime === void 0) - return; - attrs.atime = atime; - attrs.mtime = mtime; - } - if (flags & ATTR.EXTENDED) { - const count = bufferParser.readUInt32BE(); - if (count === void 0) - return; - const extended = {}; - for (let i = 0; i < count; ++i) { - const type = bufferParser.readString(true); - const data = bufferParser.readString(); - if (data === void 0) - return; - extended[type] = data; - } - attrs.extended = extended; - } - return attrs; - } - function sendOrBuffer(sftp, payload) { - const ret = tryWritePayload(sftp, payload); - if (ret !== void 0) { - sftp._buffer.push(ret); - return false; - } - return true; - } - function tryWritePayload(sftp, payload) { - const outgoing = sftp.outgoing; - if (outgoing.state !== "open") - return; - if (outgoing.window === 0) { - sftp._waitWindow = true; - sftp._chunkcb = drainBuffer; - return payload; - } - let ret; - const len = payload.length; - let p = 0; - while (len - p > 0 && outgoing.window > 0) { - const actualLen = Math.min(len - p, outgoing.window, outgoing.packetSize); - outgoing.window -= actualLen; - if (outgoing.window === 0) { - sftp._waitWindow = true; - sftp._chunkcb = drainBuffer; - } - if (p === 0 && actualLen === len) { - sftp._protocol.channelData(sftp.outgoing.id, payload); - } else { - sftp._protocol.channelData( - sftp.outgoing.id, - bufferSlice(payload, p, p + actualLen) - ); - } - p += actualLen; - } - if (len - p > 0) { - if (p > 0) - ret = bufferSlice(payload, p, len); - else - ret = payload; - } - return ret; - } - function drainBuffer() { - this._chunkcb = void 0; - const buffer = this._buffer; - let i = 0; - while (i < buffer.length) { - const payload = buffer[i]; - const ret = tryWritePayload(this, payload); - if (ret !== void 0) { - if (ret !== payload) - buffer[i] = ret; - if (i > 0) - this._buffer = buffer.slice(i); - return; - } - ++i; - } - if (i > 0) - this._buffer = []; - } - function doFatalSFTPError(sftp, msg, noDebug) { - const err = new Error(msg); - err.level = "sftp-protocol"; - if (!noDebug && sftp._debug) - sftp._debug(`SFTP: Inbound: ${msg}`); - sftp.emit("error", err); - sftp.destroy(); - cleanupRequests(sftp); - return false; - } - function cleanupRequests(sftp) { - const keys = Object.keys(sftp._requests); - if (keys.length === 0) - return; - const reqs = sftp._requests; - sftp._requests = {}; - const err = new Error("No response from server"); - for (let i = 0; i < keys.length; ++i) { - const req = reqs[keys[i]]; - if (typeof req.cb === "function") - req.cb(err); - } - } - function requestLimits(sftp, cb) { - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 18); - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = sftp._writeReqid = sftp._writeReqid + 1 & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - writeUInt32BE(buf, 18, p); - buf.utf8Write("limits@openssh.com", p += 4, 18); - sftp._requests[reqid] = { extended: "limits@openssh.com", cb }; - const isBuffered = sendOrBuffer(sftp, buf); - if (sftp._debug) { - const which = isBuffered ? "Buffered" : "Sending"; - sftp._debug(`SFTP: Outbound: ${which} limits@openssh.com`); - } - } - var CLIENT_HANDLERS = { - [RESPONSE.VERSION]: (sftp, payload) => { - if (sftp._version !== -1) - return doFatalSFTPError(sftp, "Duplicate VERSION packet"); - const extensions = {}; - bufferParser.init(payload, 1); - let version = bufferParser.readUInt32BE(); - while (bufferParser.avail()) { - const extName = bufferParser.readString(true); - const extData = bufferParser.readString(true); - if (extData === void 0) { - version = void 0; - break; - } - extensions[extName] = extData; - } - bufferParser.clear(); - if (version === void 0) - return doFatalSFTPError(sftp, "Malformed VERSION packet"); - if (sftp._debug) { - const names = Object.keys(extensions); - if (names.length) { - sftp._debug( - `SFTP: Inbound: Received VERSION (v${version}, exts:${names})` - ); - } else { - sftp._debug(`SFTP: Inbound: Received VERSION (v${version})`); - } - } - sftp._version = version; - sftp._extensions = extensions; - if (extensions["limits@openssh.com"] === "1") { - return requestLimits(sftp, (err, limits) => { - if (!err) { - if (limits.maxPktLen > 0) - sftp._maxOutPktLen = limits.maxPktLen; - if (limits.maxReadLen > 0) - sftp._maxReadLen = limits.maxReadLen; - if (limits.maxWriteLen > 0) - sftp._maxWriteLen = limits.maxWriteLen; - sftp.maxOpenHandles = limits.maxOpenHandles > 0 ? limits.maxOpenHandles : Infinity; - } - sftp.emit("ready"); - }); - } - sftp.emit("ready"); - }, - [RESPONSE.STATUS]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - const errorCode = bufferParser.readUInt32BE(); - const errorMsg = bufferParser.readString(true); - bufferParser.clear(); - if (sftp._debug) { - const jsonMsg = JSON.stringify(errorMsg); - sftp._debug( - `SFTP: Inbound: Received STATUS (id:${reqID}, ${errorCode}, ${jsonMsg})` - ); - } - const req = sftp._requests[reqID]; - delete sftp._requests[reqID]; - if (req && typeof req.cb === "function") { - if (errorCode === STATUS_CODE.OK) { - req.cb(); - return; - } - const err = new Error(errorMsg || STATUS_CODE_STR[errorCode] || "Unknown status"); - err.code = errorCode; - req.cb(err); - } - }, - [RESPONSE.HANDLE]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - const handle = bufferParser.readString(); - bufferParser.clear(); - if (handle === void 0) { - if (reqID !== void 0) - delete sftp._requests[reqID]; - return doFatalSFTPError(sftp, "Malformed HANDLE packet"); - } - sftp._debug && sftp._debug(`SFTP: Inbound: Received HANDLE (id:${reqID})`); - const req = sftp._requests[reqID]; - delete sftp._requests[reqID]; - if (req && typeof req.cb === "function") - req.cb(void 0, handle); - }, - [RESPONSE.DATA]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - let req; - if (reqID !== void 0) { - req = sftp._requests[reqID]; - delete sftp._requests[reqID]; - } - if (req && typeof req.cb === "function") { - if (req.buffer) { - const nb = bufferParser.readString(req.buffer); - bufferParser.clear(); - if (nb !== void 0) { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})` - ); - req.cb(void 0, req.buffer, nb); - return; - } - } else { - const data = bufferParser.readString(); - bufferParser.clear(); - if (data !== void 0) { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received DATA (id:${reqID}, ${data.length})` - ); - req.cb(void 0, data); - return; - } - } - } else { - const nb = bufferParser.skipString(); - bufferParser.clear(); - if (nb !== void 0) { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})` - ); - return; - } - } - return doFatalSFTPError(sftp, "Malformed DATA packet"); - }, - [RESPONSE.NAME]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - let req; - if (reqID !== void 0) { - req = sftp._requests[reqID]; - delete sftp._requests[reqID]; - } - const count = bufferParser.readUInt32BE(); - if (count !== void 0) { - let names = []; - for (let i = 0; i < count; ++i) { - const filename = bufferParser.readString(true); - const longname = bufferParser.readString(true); - const attrs = readAttrs(sftp._biOpt); - if (attrs === void 0) { - names = void 0; - break; - } - names.push({ filename, longname, attrs }); - } - if (names !== void 0) { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received NAME (id:${reqID}, ${names.length})` - ); - bufferParser.clear(); - if (req && typeof req.cb === "function") - req.cb(void 0, names); - return; - } - } - bufferParser.clear(); - return doFatalSFTPError(sftp, "Malformed NAME packet"); - }, - [RESPONSE.ATTRS]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - let req; - if (reqID !== void 0) { - req = sftp._requests[reqID]; - delete sftp._requests[reqID]; - } - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); - if (attrs !== void 0) { - sftp._debug && sftp._debug(`SFTP: Inbound: Received ATTRS (id:${reqID})`); - if (req && typeof req.cb === "function") - req.cb(void 0, attrs); - return; - } - return doFatalSFTPError(sftp, "Malformed ATTRS packet"); - }, - [RESPONSE.EXTENDED]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - if (reqID !== void 0) { - const req = sftp._requests[reqID]; - if (req) { - delete sftp._requests[reqID]; - switch (req.extended) { - case "statvfs@openssh.com": - case "fstatvfs@openssh.com": { - const biOpt = sftp._biOpt; - const stats = { - f_bsize: bufferParser.readUInt64BE(biOpt), - f_frsize: bufferParser.readUInt64BE(biOpt), - f_blocks: bufferParser.readUInt64BE(biOpt), - f_bfree: bufferParser.readUInt64BE(biOpt), - f_bavail: bufferParser.readUInt64BE(biOpt), - f_files: bufferParser.readUInt64BE(biOpt), - f_ffree: bufferParser.readUInt64BE(biOpt), - f_favail: bufferParser.readUInt64BE(biOpt), - f_sid: bufferParser.readUInt64BE(biOpt), - f_flag: bufferParser.readUInt64BE(biOpt), - f_namemax: bufferParser.readUInt64BE(biOpt) - }; - if (stats.f_namemax === void 0) - break; - if (sftp._debug) { - sftp._debug( - `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ${req.extended})` - ); - } - bufferParser.clear(); - if (typeof req.cb === "function") - req.cb(void 0, stats); - return; - } - case "limits@openssh.com": { - const limits = { - maxPktLen: bufferParser.readUInt64BE(), - maxReadLen: bufferParser.readUInt64BE(), - maxWriteLen: bufferParser.readUInt64BE(), - maxOpenHandles: bufferParser.readUInt64BE() - }; - if (limits.maxOpenHandles === void 0) - break; - if (sftp._debug) { - sftp._debug( - `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ${req.extended})` - ); - } - bufferParser.clear(); - if (typeof req.cb === "function") - req.cb(void 0, limits); - return; - } - case "users-groups-by-id@openssh.com": { - const usernameCount = bufferParser.readUInt32BE(); - if (usernameCount === void 0) - break; - const usernames = new Array(usernameCount); - for (let i = 0; i < usernames.length; ++i) - usernames[i] = bufferParser.readString(true); - const groupnameCount = bufferParser.readUInt32BE(); - if (groupnameCount === void 0) - break; - const groupnames = new Array(groupnameCount); - for (let i = 0; i < groupnames.length; ++i) - groupnames[i] = bufferParser.readString(true); - if (groupnames.length > 0 && groupnames[groupnames.length - 1] === void 0) { - break; - } - if (sftp._debug) { - sftp._debug( - `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ${req.extended})` - ); - } - bufferParser.clear(); - if (typeof req.cb === "function") - req.cb(void 0, usernames, groupnames); - return; - } - default: - sftp._debug && sftp._debug( - `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)` - ); - bufferParser.clear(); - if (typeof req.cb === "function") - req.cb(); - return; - } - } else { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)` - ); - bufferParser.clear(); - return; - } - } - bufferParser.clear(); - return doFatalSFTPError(sftp, "Malformed EXTENDED_REPLY packet"); - } - }; - var SERVER_HANDLERS = { - [REQUEST.INIT]: (sftp, payload) => { - if (sftp._version !== -1) - return doFatalSFTPError(sftp, "Duplicate INIT packet"); - const extensions = {}; - bufferParser.init(payload, 1); - let version = bufferParser.readUInt32BE(); - while (bufferParser.avail()) { - const extName = bufferParser.readString(true); - const extData = bufferParser.readString(true); - if (extData === void 0) { - version = void 0; - break; - } - extensions[extName] = extData; - } - bufferParser.clear(); - if (version === void 0) - return doFatalSFTPError(sftp, "Malformed INIT packet"); - if (sftp._debug) { - const names = Object.keys(extensions); - if (names.length) { - sftp._debug( - `SFTP: Inbound: Received INIT (v${version}, exts:${names})` - ); - } else { - sftp._debug(`SFTP: Inbound: Received INIT (v${version})`); - } - } - sendOrBuffer(sftp, SERVER_VERSION_BUFFER); - sftp._version = version; - sftp._extensions = extensions; - sftp.emit("ready"); - }, - [REQUEST.OPEN]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - const filename = bufferParser.readString(true); - const pflags = bufferParser.readUInt32BE(); - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); - if (attrs === void 0) - return doFatalSFTPError(sftp, "Malformed OPEN packet"); - sftp._debug && sftp._debug(`SFTP: Inbound: Received OPEN (id:${reqID})`); - if (!sftp.emit("OPEN", reqID, filename, pflags, attrs)) { - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.CLOSE]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - const handle = bufferParser.readString(); - bufferParser.clear(); - if (handle === void 0 || handle.length > 256) - return doFatalSFTPError(sftp, "Malformed CLOSE packet"); - sftp._debug && sftp._debug(`SFTP: Inbound: Received CLOSE (id:${reqID})`); - if (!sftp.emit("CLOSE", reqID, handle)) { - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.READ]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - const handle = bufferParser.readString(); - const offset = bufferParser.readUInt64BE(sftp._biOpt); - const len = bufferParser.readUInt32BE(); - bufferParser.clear(); - if (len === void 0 || handle.length > 256) - return doFatalSFTPError(sftp, "Malformed READ packet"); - sftp._debug && sftp._debug(`SFTP: Inbound: Received READ (id:${reqID})`); - if (!sftp.emit("READ", reqID, handle, offset, len)) { - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.WRITE]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - const handle = bufferParser.readString(); - const offset = bufferParser.readUInt64BE(sftp._biOpt); - const data = bufferParser.readString(); - bufferParser.clear(); - if (data === void 0 || handle.length > 256) - return doFatalSFTPError(sftp, "Malformed WRITE packet"); - sftp._debug && sftp._debug(`SFTP: Inbound: Received WRITE (id:${reqID})`); - if (!sftp.emit("WRITE", reqID, handle, offset, data)) { - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.LSTAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - const path = bufferParser.readString(true); - bufferParser.clear(); - if (path === void 0) - return doFatalSFTPError(sftp, "Malformed LSTAT packet"); - sftp._debug && sftp._debug(`SFTP: Inbound: Received LSTAT (id:${reqID})`); - if (!sftp.emit("LSTAT", reqID, path)) { - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.FSTAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - const handle = bufferParser.readString(); - bufferParser.clear(); - if (handle === void 0 || handle.length > 256) - return doFatalSFTPError(sftp, "Malformed FSTAT packet"); - sftp._debug && sftp._debug(`SFTP: Inbound: Received FSTAT (id:${reqID})`); - if (!sftp.emit("FSTAT", reqID, handle)) { - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.SETSTAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - const path = bufferParser.readString(true); - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); - if (attrs === void 0) - return doFatalSFTPError(sftp, "Malformed SETSTAT packet"); - sftp._debug && sftp._debug(`SFTP: Inbound: Received SETSTAT (id:${reqID})`); - if (!sftp.emit("SETSTAT", reqID, path, attrs)) { - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.FSETSTAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - const handle = bufferParser.readString(); - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); - if (attrs === void 0 || handle.length > 256) - return doFatalSFTPError(sftp, "Malformed FSETSTAT packet"); - sftp._debug && sftp._debug( - `SFTP: Inbound: Received FSETSTAT (id:${reqID})` - ); - if (!sftp.emit("FSETSTAT", reqID, handle, attrs)) { - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.OPENDIR]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - const path = bufferParser.readString(true); - bufferParser.clear(); - if (path === void 0) - return doFatalSFTPError(sftp, "Malformed OPENDIR packet"); - sftp._debug && sftp._debug(`SFTP: Inbound: Received OPENDIR (id:${reqID})`); - if (!sftp.emit("OPENDIR", reqID, path)) { - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.READDIR]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - const handle = bufferParser.readString(); - bufferParser.clear(); - if (handle === void 0 || handle.length > 256) - return doFatalSFTPError(sftp, "Malformed READDIR packet"); - sftp._debug && sftp._debug(`SFTP: Inbound: Received READDIR (id:${reqID})`); - if (!sftp.emit("READDIR", reqID, handle)) { - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.REMOVE]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - const path = bufferParser.readString(true); - bufferParser.clear(); - if (path === void 0) - return doFatalSFTPError(sftp, "Malformed REMOVE packet"); - sftp._debug && sftp._debug(`SFTP: Inbound: Received REMOVE (id:${reqID})`); - if (!sftp.emit("REMOVE", reqID, path)) { - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.MKDIR]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - const path = bufferParser.readString(true); - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); - if (attrs === void 0) - return doFatalSFTPError(sftp, "Malformed MKDIR packet"); - sftp._debug && sftp._debug(`SFTP: Inbound: Received MKDIR (id:${reqID})`); - if (!sftp.emit("MKDIR", reqID, path, attrs)) { - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.RMDIR]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - const path = bufferParser.readString(true); - bufferParser.clear(); - if (path === void 0) - return doFatalSFTPError(sftp, "Malformed RMDIR packet"); - sftp._debug && sftp._debug(`SFTP: Inbound: Received RMDIR (id:${reqID})`); - if (!sftp.emit("RMDIR", reqID, path)) { - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.REALPATH]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - const path = bufferParser.readString(true); - bufferParser.clear(); - if (path === void 0) - return doFatalSFTPError(sftp, "Malformed REALPATH packet"); - sftp._debug && sftp._debug( - `SFTP: Inbound: Received REALPATH (id:${reqID})` - ); - if (!sftp.emit("REALPATH", reqID, path)) { - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.STAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - const path = bufferParser.readString(true); - bufferParser.clear(); - if (path === void 0) - return doFatalSFTPError(sftp, "Malformed STAT packet"); - sftp._debug && sftp._debug(`SFTP: Inbound: Received STAT (id:${reqID})`); - if (!sftp.emit("STAT", reqID, path)) { - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.RENAME]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - const oldPath = bufferParser.readString(true); - const newPath = bufferParser.readString(true); - bufferParser.clear(); - if (newPath === void 0) - return doFatalSFTPError(sftp, "Malformed RENAME packet"); - sftp._debug && sftp._debug(`SFTP: Inbound: Received RENAME (id:${reqID})`); - if (!sftp.emit("RENAME", reqID, oldPath, newPath)) { - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.READLINK]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - const path = bufferParser.readString(true); - bufferParser.clear(); - if (path === void 0) - return doFatalSFTPError(sftp, "Malformed READLINK packet"); - sftp._debug && sftp._debug( - `SFTP: Inbound: Received READLINK (id:${reqID})` - ); - if (!sftp.emit("READLINK", reqID, path)) { - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.SYMLINK]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - const linkPath = bufferParser.readString(true); - const targetPath = bufferParser.readString(true); - bufferParser.clear(); - if (targetPath === void 0) - return doFatalSFTPError(sftp, "Malformed SYMLINK packet"); - sftp._debug && sftp._debug(`SFTP: Inbound: Received SYMLINK (id:${reqID})`); - let handled; - if (sftp._isOpenSSH) { - handled = sftp.emit("SYMLINK", reqID, targetPath, linkPath); - } else { - handled = sftp.emit("SYMLINK", reqID, linkPath, targetPath); - } - if (!handled) { - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.EXTENDED]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - const extName = bufferParser.readString(true); - if (extName === void 0) { - bufferParser.clear(); - return doFatalSFTPError(sftp, "Malformed EXTENDED packet"); - } - let extData; - if (bufferParser.avail()) - extData = bufferParser.readRaw(); - bufferParser.clear(); - sftp._debug && sftp._debug( - `SFTP: Inbound: Received EXTENDED (id:${reqID})` - ); - if (!sftp.emit("EXTENDED", reqID, extName, extData)) { - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - } - }; - var { - ERR_INVALID_ARG_TYPE, - ERR_OUT_OF_RANGE, - validateNumber - } = require_node_fs_compat(); - var kMinPoolSpace = 128; - var pool; - var poolFragments = []; - function allocNewPool(poolSize) { - if (poolFragments.length > 0) - pool = poolFragments.pop(); - else - pool = Buffer.allocUnsafe(poolSize); - pool.used = 0; - } - function checkPosition(pos, name) { - if (!Number.isSafeInteger(pos)) { - validateNumber(pos, name); - if (!Number.isInteger(pos)) - throw new ERR_OUT_OF_RANGE(name, "an integer", pos); - throw new ERR_OUT_OF_RANGE(name, ">= 0 and <= 2 ** 53 - 1", pos); - } - if (pos < 0) - throw new ERR_OUT_OF_RANGE(name, ">= 0 and <= 2 ** 53 - 1", pos); - } - function roundUpToMultipleOf8(n) { - return n + 7 & ~7; - } - function ReadStream(sftp, path, options) { - if (options === void 0) - options = {}; - else if (typeof options === "string") - options = { encoding: options }; - else if (options === null || typeof options !== "object") - throw new TypeError('"options" argument must be a string or an object'); - else - options = Object.create(options); - if (options.highWaterMark === void 0) - options.highWaterMark = 64 * 1024; - options.emitClose = false; - options.autoDestroy = false; - ReadableStream2.call(this, options); - this.path = path; - this.flags = options.flags === void 0 ? "r" : options.flags; - this.mode = options.mode === void 0 ? 438 : options.mode; - this.start = options.start; - this.end = options.end; - this.autoClose = options.autoClose === void 0 ? true : options.autoClose; - this.pos = 0; - this.bytesRead = 0; - this.isClosed = false; - this.handle = options.handle === void 0 ? null : options.handle; - this.sftp = sftp; - this._opening = false; - if (this.start !== void 0) { - checkPosition(this.start, "start"); - this.pos = this.start; - } - if (this.end === void 0) { - this.end = Infinity; - } else if (this.end !== Infinity) { - checkPosition(this.end, "end"); - if (this.start !== void 0 && this.start > this.end) { - throw new ERR_OUT_OF_RANGE( - "start", - `<= "end" (here: ${this.end})`, - this.start - ); - } - } - this.on("end", function() { - if (this.autoClose) - this.destroy(); - }); - if (!Buffer.isBuffer(this.handle)) - this.open(); - } - inherits(ReadStream, ReadableStream2); - ReadStream.prototype.open = function() { - if (this._opening) - return; - this._opening = true; - this.sftp.open(this.path, this.flags, this.mode, (er, handle) => { - this._opening = false; - if (er) { - this.emit("error", er); - if (this.autoClose) - this.destroy(); - return; - } - this.handle = handle; - this.emit("open", handle); - this.emit("ready"); - this.read(); - }); - }; - ReadStream.prototype._read = function(n) { - if (!Buffer.isBuffer(this.handle)) - return this.once("open", () => this._read(n)); - if (this.destroyed) - return; - if (!pool || pool.length - pool.used < kMinPoolSpace) { - allocNewPool(this.readableHighWaterMark || this._readableState.highWaterMark); - } - const thisPool = pool; - let toRead = Math.min(pool.length - pool.used, n); - const start = pool.used; - if (this.end !== void 0) - toRead = Math.min(this.end - this.pos + 1, toRead); - if (toRead <= 0) - return this.push(null); - this.sftp.read( - this.handle, - pool, - pool.used, - toRead, - this.pos, - (er, bytesRead) => { - if (er) { - this.emit("error", er); - if (this.autoClose) - this.destroy(); - return; - } - let b = null; - if (start + toRead === thisPool.used && thisPool === pool) { - thisPool.used = roundUpToMultipleOf8(thisPool.used + bytesRead - toRead); - } else { - const alignedEnd = start + toRead & ~7; - const alignedStart = roundUpToMultipleOf8(start + bytesRead); - if (alignedEnd - alignedStart >= kMinPoolSpace) - poolFragments.push(thisPool.slice(alignedStart, alignedEnd)); - } - if (bytesRead > 0) { - this.bytesRead += bytesRead; - b = thisPool.slice(start, start + bytesRead); - } - this.pos += bytesRead; - this.push(b); - } - ); - pool.used = roundUpToMultipleOf8(pool.used + toRead); - }; - ReadStream.prototype._destroy = function(err, cb) { - if (this._opening && !Buffer.isBuffer(this.handle)) { - this.once("open", closeStream.bind(null, this, cb, err)); - return; - } - closeStream(this, cb, err); - this.handle = null; - this._opening = false; - }; - function closeStream(stream2, cb, err) { - if (!stream2.handle) - return onclose(); - stream2.sftp.close(stream2.handle, onclose); - function onclose(er) { - er = er || err; - cb(er); - stream2.isClosed = true; - if (!er) - stream2.emit("close"); - } - } - ReadStream.prototype.close = function(cb) { - this.destroy(null, cb); - }; - Object.defineProperty(ReadStream.prototype, "pending", { - get() { - return this.handle === null; - }, - configurable: true - }); - function WriteStream(sftp, path, options) { - if (options === void 0) - options = {}; - else if (typeof options === "string") - options = { encoding: options }; - else if (options === null || typeof options !== "object") - throw new TypeError('"options" argument must be a string or an object'); - else - options = Object.create(options); - options.emitClose = false; - options.autoDestroy = false; - WritableStream.call(this, options); - this.path = path; - this.flags = options.flags === void 0 ? "w" : options.flags; - this.mode = options.mode === void 0 ? 438 : options.mode; - this.start = options.start; - this.autoClose = options.autoClose === void 0 ? true : options.autoClose; - this.pos = 0; - this.bytesWritten = 0; - this.isClosed = false; - this.handle = options.handle === void 0 ? null : options.handle; - this.sftp = sftp; - this._opening = false; - if (this.start !== void 0) { - checkPosition(this.start, "start"); - this.pos = this.start; - } - if (options.encoding) - this.setDefaultEncoding(options.encoding); - this.on("finish", function() { - if (this._writableState.finalCalled) - return; - if (this.autoClose) - this.destroy(); - }); - if (!Buffer.isBuffer(this.handle)) - this.open(); - } - inherits(WriteStream, WritableStream); - WriteStream.prototype._final = function(cb) { - if (this.autoClose) - this.destroy(); - cb(); - }; - WriteStream.prototype.open = function() { - if (this._opening) - return; - this._opening = true; - this.sftp.open(this.path, this.flags, this.mode, (er, handle) => { - this._opening = false; - if (er) { - this.emit("error", er); - if (this.autoClose) - this.destroy(); - return; - } - this.handle = handle; - const tryAgain = (err) => { - if (err) { - this.sftp.chmod(this.path, this.mode, (err_) => tryAgain()); - return; - } - if (this.flags[0] === "a") { - const tryStat = (err2, st) => { - if (err2) { - this.sftp.stat(this.path, (err_, st_) => { - if (err_) { - this.destroy(); - this.emit("error", err2); - return; - } - tryStat(null, st_); - }); - return; - } - this.pos = st.size; - this.emit("open", handle); - this.emit("ready"); - }; - this.sftp.fstat(handle, tryStat); - return; - } - this.emit("open", handle); - this.emit("ready"); - }; - this.sftp.fchmod(handle, this.mode, tryAgain); - }); - }; - WriteStream.prototype._write = function(data, encoding, cb) { - if (!Buffer.isBuffer(data)) { - const err = new ERR_INVALID_ARG_TYPE("data", "Buffer", data); - return this.emit("error", err); - } - if (!Buffer.isBuffer(this.handle)) { - return this.once("open", function() { - this._write(data, encoding, cb); - }); - } - this.sftp.write( - this.handle, - data, - 0, - data.length, - this.pos, - (er, bytes) => { - if (er) { - if (this.autoClose) - this.destroy(); - return cb(er); - } - this.bytesWritten += bytes; - cb(); - } - ); - this.pos += data.length; - }; - WriteStream.prototype._writev = function(data, cb) { - if (!Buffer.isBuffer(this.handle)) { - return this.once("open", function() { - this._writev(data, cb); - }); - } - const sftp = this.sftp; - const handle = this.handle; - let writesLeft = data.length; - const onwrite = (er, bytes) => { - if (er) { - this.destroy(); - return cb(er); - } - this.bytesWritten += bytes; - if (--writesLeft === 0) - cb(); - }; - for (let i = 0; i < data.length; ++i) { - const chunk = data[i].chunk; - sftp.write(handle, chunk, 0, chunk.length, this.pos, onwrite); - this.pos += chunk.length; - } - }; - if (typeof WritableStream.prototype.destroy !== "function") - WriteStream.prototype.destroy = ReadStream.prototype.destroy; - WriteStream.prototype._destroy = ReadStream.prototype._destroy; - WriteStream.prototype.close = function(cb) { - if (cb) { - if (this.isClosed) { - process.nextTick(cb); - return; - } - this.on("close", cb); - } - if (!this.autoClose) - this.on("finish", this.destroy.bind(this)); - this.end(); - }; - WriteStream.prototype.destroySoon = WriteStream.prototype.end; - Object.defineProperty(WriteStream.prototype, "pending", { - get() { - return this.handle === null; - }, - configurable: true - }); - module2.exports = { - flagsToString, - OPEN_MODE, - SFTP, - Stats, - STATUS_CODE, - stringToFlags - }; - } -}); - -// node_modules/ssh2/lib/Channel.js -var require_Channel = __commonJS({ - "node_modules/ssh2/lib/Channel.js"(exports2, module2) { - "use strict"; - var { - Duplex: DuplexStream, - Readable: ReadableStream2, - Writable: WritableStream - } = require("stream"); - var { - CHANNEL_EXTENDED_DATATYPE: { STDERR } - } = require_constants6(); - var { bufferSlice } = require_utils4(); - var PACKET_SIZE = 32 * 1024; - var MAX_WINDOW = 2 * 1024 * 1024; - var WINDOW_THRESHOLD = MAX_WINDOW / 2; - var ClientStderr = class extends ReadableStream2 { - constructor(channel, streamOpts) { - super(streamOpts); - this._channel = channel; - } - _read(n) { - if (this._channel._waitChanDrain) { - this._channel._waitChanDrain = false; - if (this._channel.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(this._channel); - } - } - }; - var ServerStderr = class extends WritableStream { - constructor(channel) { - super({ highWaterMark: MAX_WINDOW }); - this._channel = channel; - } - _write(data, encoding, cb) { - const channel = this._channel; - const protocol = channel._client._protocol; - const outgoing = channel.outgoing; - const packetSize = outgoing.packetSize; - const id = outgoing.id; - let window2 = outgoing.window; - const len = data.length; - let p = 0; - if (outgoing.state !== "open") - return; - while (len - p > 0 && window2 > 0) { - let sliceLen = len - p; - if (sliceLen > window2) - sliceLen = window2; - if (sliceLen > packetSize) - sliceLen = packetSize; - if (p === 0 && sliceLen === len) - protocol.channelExtData(id, data, STDERR); - else - protocol.channelExtData(id, bufferSlice(data, p, p + sliceLen), STDERR); - p += sliceLen; - window2 -= sliceLen; - } - outgoing.window = window2; - if (len - p > 0) { - if (window2 === 0) - channel._waitWindow = true; - if (p > 0) - channel._chunkErr = bufferSlice(data, p, len); - else - channel._chunkErr = data; - channel._chunkcbErr = cb; - return; - } - cb(); - } - }; - var Channel = class extends DuplexStream { - constructor(client, info8, opts) { - const streamOpts = { - highWaterMark: MAX_WINDOW, - allowHalfOpen: !opts || opts && opts.allowHalfOpen !== false, - emitClose: false - }; - super(streamOpts); - this.allowHalfOpen = streamOpts.allowHalfOpen; - const server = !!(opts && opts.server); - this.server = server; - this.type = info8.type; - this.subtype = void 0; - this.incoming = info8.incoming; - this.outgoing = info8.outgoing; - this._callbacks = []; - this._client = client; - this._hasX11 = false; - this._exit = { - code: void 0, - signal: void 0, - dump: void 0, - desc: void 0 - }; - this.stdin = this.stdout = this; - if (server) - this.stderr = new ServerStderr(this); - else - this.stderr = new ClientStderr(this, streamOpts); - this._waitWindow = false; - this._waitChanDrain = false; - this._chunk = void 0; - this._chunkcb = void 0; - this._chunkErr = void 0; - this._chunkcbErr = void 0; - this.on("finish", onFinish).on("prefinish", onFinish); - this.on("end", onEnd).on("close", onEnd); - } - _read(n) { - if (this._waitChanDrain) { - this._waitChanDrain = false; - if (this.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(this); - } - } - _write(data, encoding, cb) { - const protocol = this._client._protocol; - const outgoing = this.outgoing; - const packetSize = outgoing.packetSize; - const id = outgoing.id; - let window2 = outgoing.window; - const len = data.length; - let p = 0; - if (outgoing.state !== "open") - return; - while (len - p > 0 && window2 > 0) { - let sliceLen = len - p; - if (sliceLen > window2) - sliceLen = window2; - if (sliceLen > packetSize) - sliceLen = packetSize; - if (p === 0 && sliceLen === len) - protocol.channelData(id, data); - else - protocol.channelData(id, bufferSlice(data, p, p + sliceLen)); - p += sliceLen; - window2 -= sliceLen; - } - outgoing.window = window2; - if (len - p > 0) { - if (window2 === 0) - this._waitWindow = true; - if (p > 0) - this._chunk = bufferSlice(data, p, len); - else - this._chunk = data; - this._chunkcb = cb; - return; - } - cb(); - } - eof() { - if (this.outgoing.state === "open") { - this.outgoing.state = "eof"; - this._client._protocol.channelEOF(this.outgoing.id); - } - } - close() { - if (this.outgoing.state === "open" || this.outgoing.state === "eof") { - this.outgoing.state = "closing"; - this._client._protocol.channelClose(this.outgoing.id); - } - } - destroy() { - this.end(); - this.close(); - return this; - } - // Session type-specific methods ============================================= - setWindow(rows, cols, height, width) { - if (this.server) - throw new Error("Client-only method called in server mode"); - if (this.type === "session" && (this.subtype === "shell" || this.subtype === "exec") && this.writable && this.outgoing.state === "open") { - this._client._protocol.windowChange( - this.outgoing.id, - rows, - cols, - height, - width - ); - } - } - signal(signalName) { - if (this.server) - throw new Error("Client-only method called in server mode"); - if (this.type === "session" && this.writable && this.outgoing.state === "open") { - this._client._protocol.signal(this.outgoing.id, signalName); - } - } - exit(statusOrSignal, coreDumped, msg) { - if (!this.server) - throw new Error("Server-only method called in client mode"); - if (this.type === "session" && this.writable && this.outgoing.state === "open") { - if (typeof statusOrSignal === "number") { - this._client._protocol.exitStatus(this.outgoing.id, statusOrSignal); - } else { - this._client._protocol.exitSignal( - this.outgoing.id, - statusOrSignal, - coreDumped, - msg - ); - } - } - } - }; - function onFinish() { - this.eof(); - if (this.server || !this.allowHalfOpen) - this.close(); - this.writable = false; - } - function onEnd() { - this.readable = false; - } - function windowAdjust(self2) { - if (self2.outgoing.state === "closed") - return; - const amt = MAX_WINDOW - self2.incoming.window; - if (amt <= 0) - return; - self2.incoming.window += amt; - self2._client._protocol.channelWindowAdjust(self2.outgoing.id, amt); - } - module2.exports = { - Channel, - MAX_WINDOW, - PACKET_SIZE, - windowAdjust, - WINDOW_THRESHOLD - }; - } -}); - -// node_modules/ssh2/lib/utils.js -var require_utils5 = __commonJS({ - "node_modules/ssh2/lib/utils.js"(exports2, module2) { - "use strict"; - var { SFTP } = require_SFTP(); - var MAX_CHANNEL = 2 ** 32 - 1; - function onChannelOpenFailure(self2, recipient, info8, cb) { - self2._chanMgr.remove(recipient); - if (typeof cb !== "function") - return; - let err; - if (info8 instanceof Error) { - err = info8; - } else if (typeof info8 === "object" && info8 !== null) { - err = new Error(`(SSH) Channel open failure: ${info8.description}`); - err.reason = info8.reason; - } else { - err = new Error( - "(SSH) Channel open failure: server closed channel unexpectedly" - ); - err.reason = ""; - } - cb(err); - } - function onCHANNEL_CLOSE(self2, recipient, channel, err, dead) { - if (typeof channel === "function") { - onChannelOpenFailure(self2, recipient, err, channel); - return; - } - if (typeof channel !== "object" || channel === null) - return; - if (channel.incoming && channel.incoming.state === "closed") - return; - self2._chanMgr.remove(recipient); - if (channel.server && channel.constructor.name === "Session") - return; - channel.incoming.state = "closed"; - if (channel.readable) - channel.push(null); - if (channel.server) { - if (channel.stderr.writable) - channel.stderr.end(); - } else if (channel.stderr.readable) { - channel.stderr.push(null); - } - if (channel.constructor !== SFTP && (channel.outgoing.state === "open" || channel.outgoing.state === "eof") && !dead) { - channel.close(); - } - if (channel.outgoing.state === "closing") - channel.outgoing.state = "closed"; - const readState = channel._readableState; - const writeState = channel._writableState; - if (writeState && !writeState.ending && !writeState.finished && !dead) - channel.end(); - const chanCallbacks = channel._callbacks; - channel._callbacks = []; - for (let i = 0; i < chanCallbacks.length; ++i) - chanCallbacks[i](true); - if (channel.server) { - if (!channel.readable || channel.destroyed || readState && readState.endEmitted) { - channel.emit("close"); - } else { - channel.once("end", () => channel.emit("close")); - } - } else { - let doClose; - switch (channel.type) { - case "direct-streamlocal@openssh.com": - case "direct-tcpip": - doClose = () => channel.emit("close"); - break; - default: { - const exit = channel._exit; - doClose = () => { - if (exit.code === null) - channel.emit("close", exit.code, exit.signal, exit.dump, exit.desc); - else - channel.emit("close", exit.code); - }; - } - } - if (!channel.readable || channel.destroyed || readState && readState.endEmitted) { - doClose(); - } else { - channel.once("end", doClose); - } - const errReadState = channel.stderr._readableState; - if (!channel.stderr.readable || channel.stderr.destroyed || errReadState && errReadState.endEmitted) { - channel.stderr.emit("close"); - } else { - channel.stderr.once("end", () => channel.stderr.emit("close")); - } - } - } - var ChannelManager = class { - constructor(client) { - this._client = client; - this._channels = {}; - this._cur = -1; - this._count = 0; - } - add(val) { - let id; - if (this._cur < MAX_CHANNEL) { - id = ++this._cur; - } else if (this._count === 0) { - this._cur = 0; - id = 0; - } else { - const channels = this._channels; - for (let i = 0; i < MAX_CHANNEL; ++i) { - if (channels[i] === void 0) { - id = i; - break; - } - } - } - if (id === void 0) - return -1; - this._channels[id] = val || true; - ++this._count; - return id; - } - update(id, val) { - if (typeof id !== "number" || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) - throw new Error(`Invalid channel id: ${id}`); - if (val && this._channels[id]) - this._channels[id] = val; - } - get(id) { - if (typeof id !== "number" || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) - throw new Error(`Invalid channel id: ${id}`); - return this._channels[id]; - } - remove(id) { - if (typeof id !== "number" || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) - throw new Error(`Invalid channel id: ${id}`); - if (this._channels[id]) { - delete this._channels[id]; - if (this._count) - --this._count; - } - } - cleanup(err) { - const channels = this._channels; - this._channels = {}; - this._cur = -1; - this._count = 0; - const chanIDs = Object.keys(channels); - const client = this._client; - for (let i = 0; i < chanIDs.length; ++i) { - const id = +chanIDs[i]; - const channel = channels[id]; - onCHANNEL_CLOSE(client, id, channel._channel || channel, err, true); - } - } - }; - var isRegExp = /* @__PURE__ */ (() => { - const toString = Object.prototype.toString; - return (val) => toString.call(val) === "[object RegExp]"; - })(); - function generateAlgorithmList(algoList, defaultList, supportedList) { - if (Array.isArray(algoList) && algoList.length > 0) { - for (let i = 0; i < algoList.length; ++i) { - if (supportedList.indexOf(algoList[i]) === -1) - throw new Error(`Unsupported algorithm: ${algoList[i]}`); - } - return algoList; - } - if (typeof algoList === "object" && algoList !== null) { - const keys = Object.keys(algoList); - let list = defaultList; - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - let val = algoList[key]; - switch (key) { - case "append": - if (!Array.isArray(val)) - val = [val]; - if (Array.isArray(val)) { - for (let j = 0; j < val.length; ++j) { - const append = val[j]; - if (typeof append === "string") { - if (!append || list.indexOf(append) !== -1) - continue; - if (supportedList.indexOf(append) === -1) - throw new Error(`Unsupported algorithm: ${append}`); - if (list === defaultList) - list = list.slice(); - list.push(append); - } else if (isRegExp(append)) { - for (let k = 0; k < supportedList.length; ++k) { - const algo = supportedList[k]; - if (append.test(algo)) { - if (list.indexOf(algo) !== -1) - continue; - if (list === defaultList) - list = list.slice(); - list.push(algo); - } - } - } - } - } - break; - case "prepend": - if (!Array.isArray(val)) - val = [val]; - if (Array.isArray(val)) { - for (let j = val.length; j >= 0; --j) { - const prepend = val[j]; - if (typeof prepend === "string") { - if (!prepend || list.indexOf(prepend) !== -1) - continue; - if (supportedList.indexOf(prepend) === -1) - throw new Error(`Unsupported algorithm: ${prepend}`); - if (list === defaultList) - list = list.slice(); - list.unshift(prepend); - } else if (isRegExp(prepend)) { - for (let k = supportedList.length; k >= 0; --k) { - const algo = supportedList[k]; - if (prepend.test(algo)) { - if (list.indexOf(algo) !== -1) - continue; - if (list === defaultList) - list = list.slice(); - list.unshift(algo); - } - } - } - } - } - break; - case "remove": - if (!Array.isArray(val)) - val = [val]; - if (Array.isArray(val)) { - for (let j = 0; j < val.length; ++j) { - const search = val[j]; - if (typeof search === "string") { - if (!search) - continue; - const idx = list.indexOf(search); - if (idx === -1) - continue; - if (list === defaultList) - list = list.slice(); - list.splice(idx, 1); - } else if (isRegExp(search)) { - for (let k = 0; k < list.length; ++k) { - if (search.test(list[k])) { - if (list === defaultList) - list = list.slice(); - list.splice(k, 1); - --k; - } - } - } - } - } - break; - } - } - return list; - } - return defaultList; - } - module2.exports = { - ChannelManager, - generateAlgorithmList, - onChannelOpenFailure, - onCHANNEL_CLOSE, - isWritable: (stream2) => { - return stream2 && stream2.writable && stream2._readableState && stream2._readableState.ended === false; - } - }; - } -}); - -// node_modules/ssh2/lib/client.js -var require_client2 = __commonJS({ - "node_modules/ssh2/lib/client.js"(exports2, module2) { - "use strict"; - var { - createHash, - getHashes, - randomFillSync - } = require("crypto"); - var { Socket } = require("net"); - var { lookup: dnsLookup } = require("dns"); - var EventEmitter = require("events"); - var HASHES = getHashes(); - var { - COMPAT, - CHANNEL_EXTENDED_DATATYPE: { STDERR }, - CHANNEL_OPEN_FAILURE, - DEFAULT_CIPHER, - DEFAULT_COMPRESSION, - DEFAULT_KEX, - DEFAULT_MAC, - DEFAULT_SERVER_HOST_KEY, - DISCONNECT_REASON, - DISCONNECT_REASON_BY_VALUE, - SUPPORTED_CIPHER, - SUPPORTED_COMPRESSION, - SUPPORTED_KEX, - SUPPORTED_MAC, - SUPPORTED_SERVER_HOST_KEY - } = require_constants6(); - var { init: cryptoInit } = require_crypto(); - var Protocol = require_Protocol(); - var { parseKey } = require_keyParser(); - var { SFTP } = require_SFTP(); - var { - bufferCopy, - makeBufferParser, - makeError, - readUInt32BE, - sigSSHToASN1, - writeUInt32BE - } = require_utils4(); - var { AgentContext, createAgent, isAgent } = require_agent2(); - var { - Channel, - MAX_WINDOW, - PACKET_SIZE, - windowAdjust, - WINDOW_THRESHOLD - } = require_Channel(); - var { - ChannelManager, - generateAlgorithmList, - isWritable, - onChannelOpenFailure, - onCHANNEL_CLOSE - } = require_utils5(); - var bufferParser = makeBufferParser(); - var sigParser = makeBufferParser(); - var RE_OPENSSH = /^OpenSSH_(?:(?![0-4])\d)|(?:\d{2,})/; - var noop3 = (err) => { - }; - var Client = class extends EventEmitter { - constructor() { - super(); - this.config = { - host: void 0, - port: void 0, - localAddress: void 0, - localPort: void 0, - forceIPv4: void 0, - forceIPv6: void 0, - keepaliveCountMax: void 0, - keepaliveInterval: void 0, - readyTimeout: void 0, - ident: void 0, - username: void 0, - password: void 0, - privateKey: void 0, - tryKeyboard: void 0, - agent: void 0, - allowAgentFwd: void 0, - authHandler: void 0, - hostHashAlgo: void 0, - hostHashCb: void 0, - strictVendor: void 0, - debug: void 0 - }; - this._agent = void 0; - this._readyTimeout = void 0; - this._chanMgr = void 0; - this._callbacks = void 0; - this._forwarding = void 0; - this._forwardingUnix = void 0; - this._acceptX11 = void 0; - this._agentFwdEnabled = void 0; - this._remoteVer = void 0; - this._protocol = void 0; - this._sock = void 0; - this._resetKA = void 0; - } - connect(cfg) { - if (this._sock && isWritable(this._sock)) { - this.once("close", () => { - this.connect(cfg); - }); - this.end(); - return this; - } - this.config.host = cfg.hostname || cfg.host || "localhost"; - this.config.port = cfg.port || 22; - this.config.localAddress = typeof cfg.localAddress === "string" ? cfg.localAddress : void 0; - this.config.localPort = typeof cfg.localPort === "string" || typeof cfg.localPort === "number" ? cfg.localPort : void 0; - this.config.forceIPv4 = cfg.forceIPv4 || false; - this.config.forceIPv6 = cfg.forceIPv6 || false; - this.config.keepaliveCountMax = typeof cfg.keepaliveCountMax === "number" && cfg.keepaliveCountMax >= 0 ? cfg.keepaliveCountMax : 3; - this.config.keepaliveInterval = typeof cfg.keepaliveInterval === "number" && cfg.keepaliveInterval > 0 ? cfg.keepaliveInterval : 0; - this.config.readyTimeout = typeof cfg.readyTimeout === "number" && cfg.readyTimeout >= 0 ? cfg.readyTimeout : 2e4; - this.config.ident = typeof cfg.ident === "string" || Buffer.isBuffer(cfg.ident) ? cfg.ident : void 0; - const algorithms = { - kex: void 0, - serverHostKey: void 0, - cs: { - cipher: void 0, - mac: void 0, - compress: void 0, - lang: [] - }, - sc: void 0 - }; - let allOfferDefaults = true; - if (typeof cfg.algorithms === "object" && cfg.algorithms !== null) { - algorithms.kex = generateAlgorithmList( - cfg.algorithms.kex, - DEFAULT_KEX, - SUPPORTED_KEX - ); - if (algorithms.kex !== DEFAULT_KEX) - allOfferDefaults = false; - algorithms.serverHostKey = generateAlgorithmList( - cfg.algorithms.serverHostKey, - DEFAULT_SERVER_HOST_KEY, - SUPPORTED_SERVER_HOST_KEY - ); - if (algorithms.serverHostKey !== DEFAULT_SERVER_HOST_KEY) - allOfferDefaults = false; - algorithms.cs.cipher = generateAlgorithmList( - cfg.algorithms.cipher, - DEFAULT_CIPHER, - SUPPORTED_CIPHER - ); - if (algorithms.cs.cipher !== DEFAULT_CIPHER) - allOfferDefaults = false; - algorithms.cs.mac = generateAlgorithmList( - cfg.algorithms.hmac, - DEFAULT_MAC, - SUPPORTED_MAC - ); - if (algorithms.cs.mac !== DEFAULT_MAC) - allOfferDefaults = false; - algorithms.cs.compress = generateAlgorithmList( - cfg.algorithms.compress, - DEFAULT_COMPRESSION, - SUPPORTED_COMPRESSION - ); - if (algorithms.cs.compress !== DEFAULT_COMPRESSION) - allOfferDefaults = false; - if (!allOfferDefaults) - algorithms.sc = algorithms.cs; - } - if (typeof cfg.username === "string") - this.config.username = cfg.username; - else if (typeof cfg.user === "string") - this.config.username = cfg.user; - else - throw new Error("Invalid username"); - this.config.password = typeof cfg.password === "string" ? cfg.password : void 0; - this.config.privateKey = typeof cfg.privateKey === "string" || Buffer.isBuffer(cfg.privateKey) ? cfg.privateKey : void 0; - this.config.localHostname = typeof cfg.localHostname === "string" ? cfg.localHostname : void 0; - this.config.localUsername = typeof cfg.localUsername === "string" ? cfg.localUsername : void 0; - this.config.tryKeyboard = cfg.tryKeyboard === true; - if (typeof cfg.agent === "string" && cfg.agent.length) - this.config.agent = createAgent(cfg.agent); - else if (isAgent(cfg.agent)) - this.config.agent = cfg.agent; - else - this.config.agent = void 0; - this.config.allowAgentFwd = cfg.agentForward === true && this.config.agent !== void 0; - let authHandler = this.config.authHandler = typeof cfg.authHandler === "function" || Array.isArray(cfg.authHandler) ? cfg.authHandler : void 0; - this.config.strictVendor = typeof cfg.strictVendor === "boolean" ? cfg.strictVendor : true; - const debug2 = this.config.debug = typeof cfg.debug === "function" ? cfg.debug : void 0; - if (cfg.agentForward === true && !this.config.allowAgentFwd) { - throw new Error( - "You must set a valid agent path to allow agent forwarding" - ); - } - let callbacks = this._callbacks = []; - this._chanMgr = new ChannelManager(this); - this._forwarding = {}; - this._forwardingUnix = {}; - this._acceptX11 = 0; - this._agentFwdEnabled = false; - this._agent = this.config.agent ? this.config.agent : void 0; - this._remoteVer = void 0; - let privateKey; - if (this.config.privateKey) { - privateKey = parseKey(this.config.privateKey, cfg.passphrase); - if (privateKey instanceof Error) - throw new Error(`Cannot parse privateKey: ${privateKey.message}`); - if (Array.isArray(privateKey)) { - privateKey = privateKey[0]; - } - if (privateKey.getPrivatePEM() === null) { - throw new Error( - "privateKey value does not contain a (valid) private key" - ); - } - } - let hostVerifier; - if (typeof cfg.hostVerifier === "function") { - const hashCb = cfg.hostVerifier; - let hashAlgo; - if (HASHES.indexOf(cfg.hostHash) !== -1) { - hashAlgo = cfg.hostHash; - } - hostVerifier = (key, verify) => { - if (hashAlgo) - key = createHash(hashAlgo).update(key).digest("hex"); - const ret = hashCb(key, verify); - if (ret !== void 0) - verify(ret); - }; - } - const sock = this._sock = cfg.sock || new Socket(); - let ready = false; - let sawHeader = false; - if (this._protocol) - this._protocol.cleanup(); - const DEBUG_HANDLER = !debug2 ? void 0 : (p, display, msg) => { - debug2(`Debug output from server: ${JSON.stringify(msg)}`); - }; - let serverSigAlgs; - const proto = this._protocol = new Protocol({ - ident: this.config.ident, - offer: allOfferDefaults ? void 0 : algorithms, - onWrite: (data) => { - if (isWritable(sock)) - sock.write(data); - }, - onError: (err) => { - if (err.level === "handshake") - clearTimeout(this._readyTimeout); - if (!proto._destruct) - sock.removeAllListeners("data"); - this.emit("error", err); - try { - sock.end(); - } catch { - } - }, - onHeader: (header) => { - sawHeader = true; - this._remoteVer = header.versions.software; - if (header.greeting) - this.emit("greeting", header.greeting); - }, - onHandshakeComplete: (negotiated) => { - this.emit("handshake", negotiated); - if (!ready) { - ready = true; - proto.service("ssh-userauth"); - } - }, - debug: debug2, - hostVerifier, - messageHandlers: { - DEBUG: DEBUG_HANDLER, - DISCONNECT: (p, reason, desc) => { - if (reason !== DISCONNECT_REASON.BY_APPLICATION) { - if (!desc) { - desc = DISCONNECT_REASON_BY_VALUE[reason]; - if (desc === void 0) - desc = `Unexpected disconnection reason: ${reason}`; - } - const err = new Error(desc); - err.code = reason; - this.emit("error", err); - } - sock.end(); - }, - SERVICE_ACCEPT: (p, name) => { - if (name === "ssh-userauth") - tryNextAuth(); - }, - EXT_INFO: (p, exts) => { - if (serverSigAlgs === void 0) { - for (const ext of exts) { - if (ext.name === "server-sig-algs") { - serverSigAlgs = ext.algs; - return; - } - } - serverSigAlgs = null; - } - }, - USERAUTH_BANNER: (p, msg) => { - this.emit("banner", msg); - }, - USERAUTH_SUCCESS: (p) => { - resetKA(); - clearTimeout(this._readyTimeout); - this.emit("ready"); - }, - USERAUTH_FAILURE: (p, authMethods, partialSuccess) => { - if (curAuth.keyAlgos) { - const oldKeyAlgo = curAuth.keyAlgos[0][0]; - if (debug2) - debug2(`Client: ${curAuth.type} (${oldKeyAlgo}) auth failed`); - curAuth.keyAlgos.shift(); - if (curAuth.keyAlgos.length) { - const [keyAlgo, hashAlgo] = curAuth.keyAlgos[0]; - switch (curAuth.type) { - case "agent": - proto.authPK( - curAuth.username, - curAuth.agentCtx.currentKey(), - keyAlgo - ); - return; - case "publickey": - proto.authPK(curAuth.username, curAuth.key, keyAlgo); - return; - case "hostbased": - proto.authHostbased( - curAuth.username, - curAuth.key, - curAuth.localHostname, - curAuth.localUsername, - keyAlgo, - (buf, cb) => { - const signature = curAuth.key.sign(buf, hashAlgo); - if (signature instanceof Error) { - signature.message = `Error while signing with key: ${signature.message}`; - signature.level = "client-authentication"; - this.emit("error", signature); - return tryNextAuth(); - } - cb(signature); - } - ); - return; - } - } else { - curAuth.keyAlgos = void 0; - } - } - if (curAuth.type === "agent") { - const pos = curAuth.agentCtx.pos(); - debug2 && debug2(`Client: Agent key #${pos + 1} failed`); - return tryNextAgentKey(); - } - debug2 && debug2(`Client: ${curAuth.type} auth failed`); - curPartial = partialSuccess; - curAuthsLeft = authMethods; - tryNextAuth(); - }, - USERAUTH_PASSWD_CHANGEREQ: (p, prompt) => { - if (curAuth.type === "password") { - this.emit("change password", prompt, (newPassword) => { - proto.authPassword( - this.config.username, - this.config.password, - newPassword - ); - }); - } - }, - USERAUTH_PK_OK: (p) => { - let keyAlgo; - let hashAlgo; - if (curAuth.keyAlgos) - [keyAlgo, hashAlgo] = curAuth.keyAlgos[0]; - if (curAuth.type === "agent") { - const key = curAuth.agentCtx.currentKey(); - proto.authPK(curAuth.username, key, keyAlgo, (buf, cb) => { - const opts = { hash: hashAlgo }; - curAuth.agentCtx.sign(key, buf, opts, (err, signed) => { - if (err) { - err.level = "agent"; - this.emit("error", err); - } else { - return cb(signed); - } - tryNextAgentKey(); - }); - }); - } else if (curAuth.type === "publickey") { - proto.authPK(curAuth.username, curAuth.key, keyAlgo, (buf, cb) => { - const signature = curAuth.key.sign(buf, hashAlgo); - if (signature instanceof Error) { - signature.message = `Error signing data with key: ${signature.message}`; - signature.level = "client-authentication"; - this.emit("error", signature); - return tryNextAuth(); - } - cb(signature); - }); - } - }, - USERAUTH_INFO_REQUEST: (p, name, instructions, prompts) => { - if (curAuth.type === "keyboard-interactive") { - const nprompts = Array.isArray(prompts) ? prompts.length : 0; - if (nprompts === 0) { - debug2 && debug2( - "Client: Sending automatic USERAUTH_INFO_RESPONSE" - ); - proto.authInfoRes(); - return; - } - curAuth.prompt( - name, - instructions, - "", - prompts, - (answers) => { - proto.authInfoRes(answers); - } - ); - } - }, - REQUEST_SUCCESS: (p, data) => { - if (callbacks.length) - callbacks.shift()(false, data); - }, - REQUEST_FAILURE: (p) => { - if (callbacks.length) - callbacks.shift()(true); - }, - GLOBAL_REQUEST: (p, name, wantReply, data) => { - switch (name) { - case "hostkeys-00@openssh.com": - hostKeysProve(this, data, (err, keys) => { - if (err) - return; - this.emit("hostkeys", keys); - }); - if (wantReply) - proto.requestSuccess(); - break; - default: - if (wantReply) - proto.requestFailure(); - } - }, - CHANNEL_OPEN: (p, info8) => { - onCHANNEL_OPEN(this, info8); - }, - CHANNEL_OPEN_CONFIRMATION: (p, info8) => { - const channel = this._chanMgr.get(info8.recipient); - if (typeof channel !== "function") - return; - const isSFTP = channel.type === "sftp"; - const type = isSFTP ? "session" : channel.type; - const chanInfo = { - type, - incoming: { - id: info8.recipient, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: "open" - }, - outgoing: { - id: info8.sender, - window: info8.window, - packetSize: info8.packetSize, - state: "open" - } - }; - const instance = isSFTP ? new SFTP(this, chanInfo, { debug: debug2 }) : new Channel(this, chanInfo); - this._chanMgr.update(info8.recipient, instance); - channel(void 0, instance); - }, - CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== "function") - return; - const info8 = { reason, description }; - onChannelOpenFailure(this, recipient, info8, channel); - }, - CHANNEL_DATA: (p, recipient, data) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== "object" || channel === null) - return; - if (channel.incoming.window === 0) - return; - channel.incoming.window -= data.length; - if (channel.push(data) === false) { - channel._waitChanDrain = true; - return; - } - if (channel.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(channel); - }, - CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => { - if (type !== STDERR) - return; - const channel = this._chanMgr.get(recipient); - if (typeof channel !== "object" || channel === null) - return; - if (channel.incoming.window === 0) - return; - channel.incoming.window -= data.length; - if (!channel.stderr.push(data)) { - channel._waitChanDrain = true; - return; - } - if (channel.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(channel); - }, - CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== "object" || channel === null) - return; - channel.outgoing.window += amount; - if (channel._waitWindow) { - channel._waitWindow = false; - if (channel._chunk) { - channel._write(channel._chunk, null, channel._chunkcb); - } else if (channel._chunkcb) { - channel._chunkcb(); - } else if (channel._chunkErr) { - channel.stderr._write( - channel._chunkErr, - null, - channel._chunkcbErr - ); - } else if (channel._chunkcbErr) { - channel._chunkcbErr(); - } - } - }, - CHANNEL_SUCCESS: (p, recipient) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== "object" || channel === null) - return; - this._resetKA(); - if (channel._callbacks.length) - channel._callbacks.shift()(false); - }, - CHANNEL_FAILURE: (p, recipient) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== "object" || channel === null) - return; - this._resetKA(); - if (channel._callbacks.length) - channel._callbacks.shift()(true); - }, - CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== "object" || channel === null) - return; - const exit = channel._exit; - if (exit.code !== void 0) - return; - switch (type) { - case "exit-status": - channel.emit("exit", exit.code = data); - return; - case "exit-signal": - channel.emit( - "exit", - exit.code = null, - exit.signal = `SIG${data.signal}`, - exit.dump = data.coreDumped, - exit.desc = data.errorMessage - ); - return; - } - if (wantReply) - p.channelFailure(channel.outgoing.id); - }, - CHANNEL_EOF: (p, recipient) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== "object" || channel === null) - return; - if (channel.incoming.state !== "open") - return; - channel.incoming.state = "eof"; - if (channel.readable) - channel.push(null); - if (channel.stderr.readable) - channel.stderr.push(null); - }, - CHANNEL_CLOSE: (p, recipient) => { - onCHANNEL_CLOSE(this, recipient, this._chanMgr.get(recipient)); - } - } - }); - sock.pause(); - const kainterval = this.config.keepaliveInterval; - const kacountmax = this.config.keepaliveCountMax; - let kacount = 0; - let katimer; - const sendKA = () => { - if (++kacount > kacountmax) { - clearInterval(katimer); - if (sock.readable) { - const err = new Error("Keepalive timeout"); - err.level = "client-timeout"; - this.emit("error", err); - sock.destroy(); - } - return; - } - if (isWritable(sock)) { - callbacks.push(resetKA); - proto.ping(); - } else { - clearInterval(katimer); - } - }; - function resetKA() { - if (kainterval > 0) { - kacount = 0; - clearInterval(katimer); - if (isWritable(sock)) - katimer = setInterval(sendKA, kainterval); - } - } - this._resetKA = resetKA; - const onDone = /* @__PURE__ */ (() => { - let called = false; - return () => { - if (called) - return; - called = true; - if (wasConnected && !sawHeader) { - const err = makeError("Connection lost before handshake", "protocol", true); - this.emit("error", err); - } - }; - })(); - const onConnect = /* @__PURE__ */ (() => { - let called = false; - return () => { - if (called) - return; - called = true; - wasConnected = true; - debug2 && debug2("Socket connected"); - this.emit("connect"); - cryptoInit.then(() => { - proto.start(); - sock.on("data", (data) => { - try { - proto.parse(data, 0, data.length); - } catch (ex) { - this.emit("error", ex); - try { - if (isWritable(sock)) - sock.end(); - } catch { - } - } - }); - if (sock.stderr && typeof sock.stderr.resume === "function") - sock.stderr.resume(); - sock.resume(); - }).catch((err) => { - this.emit("error", err); - try { - if (isWritable(sock)) - sock.end(); - } catch { - } - }); - }; - })(); - let wasConnected = false; - sock.on("connect", onConnect).on("timeout", () => { - this.emit("timeout"); - }).on("error", (err) => { - debug2 && debug2(`Socket error: ${err.message}`); - clearTimeout(this._readyTimeout); - err.level = "client-socket"; - this.emit("error", err); - }).on("end", () => { - debug2 && debug2("Socket ended"); - onDone(); - proto.cleanup(); - clearTimeout(this._readyTimeout); - clearInterval(katimer); - this.emit("end"); - }).on("close", () => { - debug2 && debug2("Socket closed"); - onDone(); - proto.cleanup(); - clearTimeout(this._readyTimeout); - clearInterval(katimer); - this.emit("close"); - const callbacks_ = callbacks; - callbacks = this._callbacks = []; - const err = new Error("No response from server"); - for (let i = 0; i < callbacks_.length; ++i) - callbacks_[i](err); - this._chanMgr.cleanup(err); - }); - let curAuth; - let curPartial = null; - let curAuthsLeft = null; - const authsAllowed = ["none"]; - if (this.config.password !== void 0) - authsAllowed.push("password"); - if (privateKey !== void 0) - authsAllowed.push("publickey"); - if (this._agent !== void 0) - authsAllowed.push("agent"); - if (this.config.tryKeyboard) - authsAllowed.push("keyboard-interactive"); - if (privateKey !== void 0 && this.config.localHostname !== void 0 && this.config.localUsername !== void 0) { - authsAllowed.push("hostbased"); - } - if (Array.isArray(authHandler)) - authHandler = makeSimpleAuthHandler(authHandler); - else if (typeof authHandler !== "function") - authHandler = makeSimpleAuthHandler(authsAllowed); - let hasSentAuth = false; - const doNextAuth = (nextAuth) => { - if (hasSentAuth) - return; - hasSentAuth = true; - if (nextAuth === false) { - const err = new Error("All configured authentication methods failed"); - err.level = "client-authentication"; - this.emit("error", err); - this.end(); - return; - } - if (typeof nextAuth === "string") { - const type = nextAuth; - if (authsAllowed.indexOf(type) === -1) - return skipAuth(`Authentication method not allowed: ${type}`); - const username = this.config.username; - switch (type) { - case "password": - nextAuth = { type, username, password: this.config.password }; - break; - case "publickey": - nextAuth = { type, username, key: privateKey }; - break; - case "hostbased": - nextAuth = { - type, - username, - key: privateKey, - localHostname: this.config.localHostname, - localUsername: this.config.localUsername - }; - break; - case "agent": - nextAuth = { - type, - username, - agentCtx: new AgentContext(this._agent) - }; - break; - case "keyboard-interactive": - nextAuth = { - type, - username, - prompt: (...args) => this.emit("keyboard-interactive", ...args) - }; - break; - case "none": - nextAuth = { type, username }; - break; - default: - return skipAuth( - `Skipping unsupported authentication method: ${nextAuth}` - ); - } - } else if (typeof nextAuth !== "object" || nextAuth === null) { - return skipAuth( - `Skipping invalid authentication attempt: ${nextAuth}` - ); - } else { - const username = nextAuth.username; - if (typeof username !== "string") { - return skipAuth( - `Skipping invalid authentication attempt: ${nextAuth}` - ); - } - const type = nextAuth.type; - switch (type) { - case "password": { - const { password } = nextAuth; - if (typeof password !== "string" && !Buffer.isBuffer(password)) - return skipAuth("Skipping invalid password auth attempt"); - nextAuth = { type, username, password }; - break; - } - case "publickey": { - const key = parseKey(nextAuth.key, nextAuth.passphrase); - if (key instanceof Error) - return skipAuth("Skipping invalid key auth attempt"); - if (!key.isPrivateKey()) - return skipAuth("Skipping non-private key"); - nextAuth = { type, username, key }; - break; - } - case "hostbased": { - const { localHostname, localUsername } = nextAuth; - const key = parseKey(nextAuth.key, nextAuth.passphrase); - if (key instanceof Error || typeof localHostname !== "string" || typeof localUsername !== "string") { - return skipAuth("Skipping invalid hostbased auth attempt"); - } - if (!key.isPrivateKey()) - return skipAuth("Skipping non-private key"); - nextAuth = { type, username, key, localHostname, localUsername }; - break; - } - case "agent": { - let agent = nextAuth.agent; - if (typeof agent === "string" && agent.length) { - agent = createAgent(agent); - } else if (!isAgent(agent)) { - return skipAuth( - `Skipping invalid agent: ${nextAuth.agent}` - ); - } - nextAuth = { type, username, agentCtx: new AgentContext(agent) }; - break; - } - case "keyboard-interactive": { - const { prompt } = nextAuth; - if (typeof prompt !== "function") { - return skipAuth( - "Skipping invalid keyboard-interactive auth attempt" - ); - } - nextAuth = { type, username, prompt }; - break; - } - case "none": - nextAuth = { type, username }; - break; - default: - return skipAuth( - `Skipping unsupported authentication method: ${nextAuth}` - ); - } - } - curAuth = nextAuth; - try { - const username = curAuth.username; - switch (curAuth.type) { - case "password": - proto.authPassword(username, curAuth.password); - break; - case "publickey": { - let keyAlgo; - curAuth.keyAlgos = getKeyAlgos(this, curAuth.key, serverSigAlgs); - if (curAuth.keyAlgos) { - if (curAuth.keyAlgos.length) { - keyAlgo = curAuth.keyAlgos[0][0]; - } else { - return skipAuth( - "Skipping key authentication (no mutual hash algorithm)" - ); - } - } - proto.authPK(username, curAuth.key, keyAlgo); - break; - } - case "hostbased": { - let keyAlgo; - let hashAlgo; - curAuth.keyAlgos = getKeyAlgos(this, curAuth.key, serverSigAlgs); - if (curAuth.keyAlgos) { - if (curAuth.keyAlgos.length) { - [keyAlgo, hashAlgo] = curAuth.keyAlgos[0]; - } else { - return skipAuth( - "Skipping hostbased authentication (no mutual hash algorithm)" - ); - } - } - proto.authHostbased( - username, - curAuth.key, - curAuth.localHostname, - curAuth.localUsername, - keyAlgo, - (buf, cb) => { - const signature = curAuth.key.sign(buf, hashAlgo); - if (signature instanceof Error) { - signature.message = `Error while signing with key: ${signature.message}`; - signature.level = "client-authentication"; - this.emit("error", signature); - return tryNextAuth(); - } - cb(signature); - } - ); - break; - } - case "agent": - curAuth.agentCtx.init((err) => { - if (err) { - err.level = "agent"; - this.emit("error", err); - return tryNextAuth(); - } - tryNextAgentKey(); - }); - break; - case "keyboard-interactive": - proto.authKeyboard(username); - break; - case "none": - proto.authNone(username); - break; - } - } finally { - hasSentAuth = false; - } - }; - function skipAuth(msg) { - debug2 && debug2(msg); - process.nextTick(tryNextAuth); - } - function tryNextAuth() { - hasSentAuth = false; - const auth2 = authHandler(curAuthsLeft, curPartial, doNextAuth); - if (hasSentAuth || auth2 === void 0) - return; - doNextAuth(auth2); - } - const tryNextAgentKey = () => { - if (curAuth.type === "agent") { - const key = curAuth.agentCtx.nextKey(); - if (key === false) { - debug2 && debug2("Agent: No more keys left to try"); - debug2 && debug2("Client: agent auth failed"); - tryNextAuth(); - } else { - const pos = curAuth.agentCtx.pos(); - let keyAlgo; - curAuth.keyAlgos = getKeyAlgos(this, key, serverSigAlgs); - if (curAuth.keyAlgos) { - if (curAuth.keyAlgos.length) { - keyAlgo = curAuth.keyAlgos[0][0]; - } else { - debug2 && debug2( - `Agent: Skipping key #${pos + 1} (no mutual hash algorithm)` - ); - tryNextAgentKey(); - return; - } - } - debug2 && debug2(`Agent: Trying key #${pos + 1}`); - proto.authPK(curAuth.username, key, keyAlgo); - } - } - }; - const startTimeout = () => { - if (this.config.readyTimeout > 0) { - this._readyTimeout = setTimeout(() => { - const err = new Error("Timed out while waiting for handshake"); - err.level = "client-timeout"; - this.emit("error", err); - sock.destroy(); - }, this.config.readyTimeout); - } - }; - if (!cfg.sock) { - let host = this.config.host; - const forceIPv4 = this.config.forceIPv4; - const forceIPv6 = this.config.forceIPv6; - debug2 && debug2(`Client: Trying ${host} on port ${this.config.port} ...`); - const doConnect = () => { - startTimeout(); - sock.connect({ - host, - port: this.config.port, - localAddress: this.config.localAddress, - localPort: this.config.localPort - }); - sock.setMaxListeners(0); - sock.setTimeout(typeof cfg.timeout === "number" ? cfg.timeout : 0); - }; - if (!forceIPv4 && !forceIPv6 || forceIPv4 && forceIPv6) { - doConnect(); - } else { - dnsLookup(host, forceIPv4 ? 4 : 6, (err, address, family) => { - if (err) { - const type = forceIPv4 ? "IPv4" : "IPv6"; - const error3 = new Error( - `Error while looking up ${type} address for '${host}': ${err}` - ); - clearTimeout(this._readyTimeout); - error3.level = "client-dns"; - this.emit("error", error3); - this.emit("close"); - return; - } - host = address; - doConnect(); - }); - } - } else { - startTimeout(); - if (typeof sock.connecting === "boolean") { - if (!sock.connecting) { - onConnect(); - } - } else { - onConnect(); - } - } - return this; - } - end() { - if (this._sock && isWritable(this._sock)) { - this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION); - this._sock.end(); - } - return this; - } - destroy() { - this._sock && isWritable(this._sock) && this._sock.destroy(); - return this; - } - exec(cmd, opts, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error("Not connected"); - if (typeof opts === "function") { - cb = opts; - opts = {}; - } - const extraOpts = { allowHalfOpen: opts.allowHalfOpen !== false }; - openChannel(this, "session", extraOpts, (err, chan) => { - if (err) { - cb(err); - return; - } - const todo = []; - function reqCb(err2) { - if (err2) { - chan.close(); - cb(err2); - return; - } - if (todo.length) - todo.shift()(); - } - if (this.config.allowAgentFwd === true || opts && opts.agentForward === true && this._agent !== void 0) { - todo.push(() => reqAgentFwd(chan, reqCb)); - } - if (typeof opts === "object" && opts !== null) { - if (typeof opts.env === "object" && opts.env !== null) - reqEnv(chan, opts.env); - if (typeof opts.pty === "object" && opts.pty !== null || opts.pty === true) { - todo.push(() => reqPty(chan, opts.pty, reqCb)); - } - if (typeof opts.x11 === "object" && opts.x11 !== null || opts.x11 === "number" || opts.x11 === true) { - todo.push(() => reqX11(chan, opts.x11, reqCb)); - } - } - todo.push(() => reqExec(chan, cmd, opts, cb)); - todo.shift()(); - }); - return this; - } - shell(wndopts, opts, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error("Not connected"); - if (typeof wndopts === "function") { - cb = wndopts; - wndopts = opts = void 0; - } else if (typeof opts === "function") { - cb = opts; - opts = void 0; - } - if (wndopts && (wndopts.x11 !== void 0 || wndopts.env !== void 0)) { - opts = wndopts; - wndopts = void 0; - } - openChannel(this, "session", (err, chan) => { - if (err) { - cb(err); - return; - } - const todo = []; - function reqCb(err2) { - if (err2) { - chan.close(); - cb(err2); - return; - } - if (todo.length) - todo.shift()(); - } - if (this.config.allowAgentFwd === true || opts && opts.agentForward === true && this._agent !== void 0) { - todo.push(() => reqAgentFwd(chan, reqCb)); - } - if (wndopts !== false) - todo.push(() => reqPty(chan, wndopts, reqCb)); - if (typeof opts === "object" && opts !== null) { - if (typeof opts.env === "object" && opts.env !== null) - reqEnv(chan, opts.env); - if (typeof opts.x11 === "object" && opts.x11 !== null || opts.x11 === "number" || opts.x11 === true) { - todo.push(() => reqX11(chan, opts.x11, reqCb)); - } - } - todo.push(() => reqShell(chan, cb)); - todo.shift()(); - }); - return this; - } - subsys(name, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error("Not connected"); - openChannel(this, "session", (err, chan) => { - if (err) { - cb(err); - return; - } - reqSubsystem(chan, name, (err2, stream2) => { - if (err2) { - cb(err2); - return; - } - cb(void 0, stream2); - }); - }); - return this; - } - forwardIn(bindAddr, bindPort, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error("Not connected"); - const wantReply = typeof cb === "function"; - if (wantReply) { - this._callbacks.push((had_err, data) => { - if (had_err) { - cb(had_err !== true ? had_err : new Error(`Unable to bind to ${bindAddr}:${bindPort}`)); - return; - } - let realPort = bindPort; - if (bindPort === 0 && data && data.length >= 4) { - realPort = readUInt32BE(data, 0); - if (!(this._protocol._compatFlags & COMPAT.DYN_RPORT_BUG)) - bindPort = realPort; - } - this._forwarding[`${bindAddr}:${bindPort}`] = realPort; - cb(void 0, realPort); - }); - } - this._protocol.tcpipForward(bindAddr, bindPort, wantReply); - return this; - } - unforwardIn(bindAddr, bindPort, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error("Not connected"); - const wantReply = typeof cb === "function"; - if (wantReply) { - this._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true ? had_err : new Error(`Unable to unbind from ${bindAddr}:${bindPort}`)); - return; - } - delete this._forwarding[`${bindAddr}:${bindPort}`]; - cb(); - }); - } - this._protocol.cancelTcpipForward(bindAddr, bindPort, wantReply); - return this; - } - forwardOut(srcIP, srcPort, dstIP, dstPort, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error("Not connected"); - const cfg = { - srcIP, - srcPort, - dstIP, - dstPort - }; - if (typeof cb !== "function") - cb = noop3; - openChannel(this, "direct-tcpip", cfg, cb); - return this; - } - openssh_noMoreSessions(cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error("Not connected"); - const wantReply = typeof cb === "function"; - if (!this.config.strictVendor || this.config.strictVendor && RE_OPENSSH.test(this._remoteVer)) { - if (wantReply) { - this._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true ? had_err : new Error("Unable to disable future sessions")); - return; - } - cb(); - }); - } - this._protocol.openssh_noMoreSessions(wantReply); - return this; - } - if (!wantReply) - return this; - process.nextTick( - cb, - new Error( - "strictVendor enabled and server is not OpenSSH or compatible version" - ) - ); - return this; - } - openssh_forwardInStreamLocal(socketPath, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error("Not connected"); - const wantReply = typeof cb === "function"; - if (!this.config.strictVendor || this.config.strictVendor && RE_OPENSSH.test(this._remoteVer)) { - if (wantReply) { - this._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true ? had_err : new Error(`Unable to bind to ${socketPath}`)); - return; - } - this._forwardingUnix[socketPath] = true; - cb(); - }); - } - this._protocol.openssh_streamLocalForward(socketPath, wantReply); - return this; - } - if (!wantReply) - return this; - process.nextTick( - cb, - new Error( - "strictVendor enabled and server is not OpenSSH or compatible version" - ) - ); - return this; - } - openssh_unforwardInStreamLocal(socketPath, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error("Not connected"); - const wantReply = typeof cb === "function"; - if (!this.config.strictVendor || this.config.strictVendor && RE_OPENSSH.test(this._remoteVer)) { - if (wantReply) { - this._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true ? had_err : new Error(`Unable to unbind from ${socketPath}`)); - return; - } - delete this._forwardingUnix[socketPath]; - cb(); - }); - } - this._protocol.openssh_cancelStreamLocalForward(socketPath, wantReply); - return this; - } - if (!wantReply) - return this; - process.nextTick( - cb, - new Error( - "strictVendor enabled and server is not OpenSSH or compatible version" - ) - ); - return this; - } - openssh_forwardOutStreamLocal(socketPath, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error("Not connected"); - if (typeof cb !== "function") - cb = noop3; - if (!this.config.strictVendor || this.config.strictVendor && RE_OPENSSH.test(this._remoteVer)) { - openChannel(this, "direct-streamlocal@openssh.com", { socketPath }, cb); - return this; - } - process.nextTick( - cb, - new Error( - "strictVendor enabled and server is not OpenSSH or compatible version" - ) - ); - return this; - } - sftp(env, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error("Not connected"); - if (typeof env === "function") { - cb = env; - env = void 0; - } - openChannel(this, "sftp", (err, sftp) => { - if (err) { - cb(err); - return; - } - const reqSubsystemCb = (err2, sftp_) => { - if (err2) { - cb(err2); - return; - } - function removeListeners() { - sftp.removeListener("ready", onReady); - sftp.removeListener("error", onError); - sftp.removeListener("exit", onExit); - sftp.removeListener("close", onExit); - } - function onReady() { - removeListeners(); - cb(void 0, sftp); - } - function onError(err3) { - removeListeners(); - cb(err3); - } - function onExit(code, signal) { - removeListeners(); - let msg; - if (typeof code === "number") - msg = `Received exit code ${code} while establishing SFTP session`; - else if (signal !== void 0) - msg = `Received signal ${signal} while establishing SFTP session`; - else - msg = "Received unexpected SFTP session termination"; - const err3 = new Error(msg); - err3.code = code; - err3.signal = signal; - cb(err3); - } - sftp.on("ready", onReady).on("error", onError).on("exit", onExit).on("close", onExit); - sftp._init(); - }; - if (typeof env === "object" && env !== null) { - reqEnv(sftp, env, (err2) => { - if (err2) { - cb(err2); - return; - } - reqSubsystem(sftp, "sftp", reqSubsystemCb); - }); - } else { - reqSubsystem(sftp, "sftp", reqSubsystemCb); - } - }); - return this; - } - setNoDelay(noDelay) { - if (this._sock && typeof this._sock.setNoDelay === "function") - this._sock.setNoDelay(noDelay); - return this; - } - }; - function openChannel(self2, type, opts, cb) { - const initWindow = MAX_WINDOW; - const maxPacket = PACKET_SIZE; - if (typeof opts === "function") { - cb = opts; - opts = {}; - } - const wrapper = (err, stream2) => { - cb(err, stream2); - }; - wrapper.type = type; - const localChan = self2._chanMgr.add(wrapper); - if (localChan === -1) { - cb(new Error("No free channels available")); - return; - } - switch (type) { - case "session": - case "sftp": - self2._protocol.session(localChan, initWindow, maxPacket); - break; - case "direct-tcpip": - self2._protocol.directTcpip(localChan, initWindow, maxPacket, opts); - break; - case "direct-streamlocal@openssh.com": - self2._protocol.openssh_directStreamLocal( - localChan, - initWindow, - maxPacket, - opts - ); - break; - default: - throw new Error(`Unsupported channel type: ${type}`); - } - } - function reqX11(chan, screen, cb) { - const cfg = { - single: false, - protocol: "MIT-MAGIC-COOKIE-1", - cookie: void 0, - screen: 0 - }; - if (typeof screen === "function") { - cb = screen; - } else if (typeof screen === "object" && screen !== null) { - if (typeof screen.single === "boolean") - cfg.single = screen.single; - if (typeof screen.screen === "number") - cfg.screen = screen.screen; - if (typeof screen.protocol === "string") - cfg.protocol = screen.protocol; - if (typeof screen.cookie === "string") - cfg.cookie = screen.cookie; - else if (Buffer.isBuffer(screen.cookie)) - cfg.cookie = screen.cookie.hexSlice(0, screen.cookie.length); - } - if (cfg.cookie === void 0) - cfg.cookie = randomCookie(); - const wantReply = typeof cb === "function"; - if (chan.outgoing.state !== "open") { - if (wantReply) - cb(new Error("Channel is not open")); - return; - } - if (wantReply) { - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true ? had_err : new Error("Unable to request X11")); - return; - } - chan._hasX11 = true; - ++chan._client._acceptX11; - chan.once("close", () => { - if (chan._client._acceptX11) - --chan._client._acceptX11; - }); - cb(); - }); - } - chan._client._protocol.x11Forward(chan.outgoing.id, cfg, wantReply); - } - function reqPty(chan, opts, cb) { - let rows = 24; - let cols = 80; - let width = 640; - let height = 480; - let term = "vt100"; - let modes = null; - if (typeof opts === "function") { - cb = opts; - } else if (typeof opts === "object" && opts !== null) { - if (typeof opts.rows === "number") - rows = opts.rows; - if (typeof opts.cols === "number") - cols = opts.cols; - if (typeof opts.width === "number") - width = opts.width; - if (typeof opts.height === "number") - height = opts.height; - if (typeof opts.term === "string") - term = opts.term; - if (typeof opts.modes === "object") - modes = opts.modes; - } - const wantReply = typeof cb === "function"; - if (chan.outgoing.state !== "open") { - if (wantReply) - cb(new Error("Channel is not open")); - return; - } - if (wantReply) { - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true ? had_err : new Error("Unable to request a pseudo-terminal")); - return; - } - cb(); - }); - } - chan._client._protocol.pty( - chan.outgoing.id, - rows, - cols, - height, - width, - term, - modes, - wantReply - ); - } - function reqAgentFwd(chan, cb) { - const wantReply = typeof cb === "function"; - if (chan.outgoing.state !== "open") { - wantReply && cb(new Error("Channel is not open")); - return; - } - if (chan._client._agentFwdEnabled) { - wantReply && cb(false); - return; - } - chan._client._agentFwdEnabled = true; - chan._callbacks.push((had_err) => { - if (had_err) { - chan._client._agentFwdEnabled = false; - if (wantReply) { - cb(had_err !== true ? had_err : new Error("Unable to request agent forwarding")); - } - return; - } - if (wantReply) - cb(); - }); - chan._client._protocol.openssh_agentForward(chan.outgoing.id, true); - } - function reqShell(chan, cb) { - if (chan.outgoing.state !== "open") { - cb(new Error("Channel is not open")); - return; - } - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true ? had_err : new Error("Unable to open shell")); - return; - } - chan.subtype = "shell"; - cb(void 0, chan); - }); - chan._client._protocol.shell(chan.outgoing.id, true); - } - function reqExec(chan, cmd, opts, cb) { - if (chan.outgoing.state !== "open") { - cb(new Error("Channel is not open")); - return; - } - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true ? had_err : new Error("Unable to exec")); - return; - } - chan.subtype = "exec"; - chan.allowHalfOpen = opts.allowHalfOpen !== false; - cb(void 0, chan); - }); - chan._client._protocol.exec(chan.outgoing.id, cmd, true); - } - function reqEnv(chan, env, cb) { - const wantReply = typeof cb === "function"; - if (chan.outgoing.state !== "open") { - if (wantReply) - cb(new Error("Channel is not open")); - return; - } - if (wantReply) { - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true ? had_err : new Error("Unable to set environment")); - return; - } - cb(); - }); - } - const keys = Object.keys(env || {}); - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - const val = env[key]; - chan._client._protocol.env(chan.outgoing.id, key, val, wantReply); - } - } - function reqSubsystem(chan, name, cb) { - if (chan.outgoing.state !== "open") { - cb(new Error("Channel is not open")); - return; - } - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true ? had_err : new Error(`Unable to start subsystem: ${name}`)); - return; - } - chan.subtype = "subsystem"; - cb(void 0, chan); - }); - chan._client._protocol.subsystem(chan.outgoing.id, name, true); - } - function onCHANNEL_OPEN(self2, info8) { - let localChan = -1; - let reason; - const accept = () => { - const chanInfo = { - type: info8.type, - incoming: { - id: localChan, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: "open" - }, - outgoing: { - id: info8.sender, - window: info8.window, - packetSize: info8.packetSize, - state: "open" - } - }; - const stream2 = new Channel(self2, chanInfo); - self2._chanMgr.update(localChan, stream2); - self2._protocol.channelOpenConfirm( - info8.sender, - localChan, - MAX_WINDOW, - PACKET_SIZE - ); - return stream2; - }; - const reject = () => { - if (reason === void 0) { - if (localChan === -1) - reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; - else - reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED; - } - if (localChan !== -1) - self2._chanMgr.remove(localChan); - self2._protocol.channelOpenFail(info8.sender, reason, ""); - }; - const reserveChannel = () => { - localChan = self2._chanMgr.add(); - if (localChan === -1) { - reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; - if (self2.config.debug) { - self2.config.debug( - "Client: Automatic rejection of incoming channel open: no channels available" - ); - } - } - return localChan !== -1; - }; - const data = info8.data; - switch (info8.type) { - case "forwarded-tcpip": { - const val = self2._forwarding[`${data.destIP}:${data.destPort}`]; - if (val !== void 0 && reserveChannel()) { - if (data.destPort === 0) - data.destPort = val; - self2.emit("tcp connection", data, accept, reject); - return; - } - break; - } - case "forwarded-streamlocal@openssh.com": - if (self2._forwardingUnix[data.socketPath] !== void 0 && reserveChannel()) { - self2.emit("unix connection", data, accept, reject); - return; - } - break; - case "auth-agent@openssh.com": - if (self2._agentFwdEnabled && typeof self2._agent.getStream === "function" && reserveChannel()) { - self2._agent.getStream((err, stream2) => { - if (err) - return reject(); - const upstream = accept(); - upstream.pipe(stream2).pipe(upstream); - }); - return; - } - break; - case "x11": - if (self2._acceptX11 !== 0 && reserveChannel()) { - self2.emit("x11", data, accept, reject); - return; - } - break; - default: - reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE; - if (self2.config.debug) { - self2.config.debug( - `Client: Automatic rejection of unsupported incoming channel open type: ${info8.type}` - ); - } - } - if (reason === void 0) { - reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; - if (self2.config.debug) { - self2.config.debug( - "Client: Automatic rejection of unexpected incoming channel open for: " + info8.type - ); - } - } - reject(); - } - var randomCookie = (() => { - const buffer = Buffer.allocUnsafe(16); - return () => { - randomFillSync(buffer, 0, 16); - return buffer.hexSlice(0, 16); - }; - })(); - function makeSimpleAuthHandler(authList) { - if (!Array.isArray(authList)) - throw new Error("authList must be an array"); - let a = 0; - return (authsLeft, partialSuccess, cb) => { - if (a === authList.length) - return false; - return authList[a++]; - }; - } - function hostKeysProve(client, keys_, cb) { - if (!client._sock || !isWritable(client._sock)) - return; - if (typeof cb !== "function") - cb = noop3; - if (!Array.isArray(keys_)) - throw new TypeError("Invalid keys argument type"); - const keys = []; - for (const key of keys_) { - const parsed = parseKey(key); - if (parsed instanceof Error) - throw parsed; - keys.push(parsed); - } - if (!client.config.strictVendor || client.config.strictVendor && RE_OPENSSH.test(client._remoteVer)) { - client._callbacks.push((had_err, data) => { - if (had_err) { - cb(had_err !== true ? had_err : new Error("Server failed to prove supplied keys")); - return; - } - const ret = []; - let keyIdx = 0; - bufferParser.init(data, 0); - while (bufferParser.avail()) { - if (keyIdx === keys.length) - break; - const key = keys[keyIdx++]; - const keyPublic = key.getPublicSSH(); - const sigEntry = bufferParser.readString(); - sigParser.init(sigEntry, 0); - const type = sigParser.readString(true); - let value = sigParser.readString(); - let algo; - if (type !== key.type) { - if (key.type === "ssh-rsa") { - switch (type) { - case "rsa-sha2-256": - algo = "sha256"; - break; - case "rsa-sha2-512": - algo = "sha512"; - break; - default: - continue; - } - } else { - continue; - } - } - const sessionID = client._protocol._kex.sessionID; - const verifyData = Buffer.allocUnsafe( - 4 + 29 + 4 + sessionID.length + 4 + keyPublic.length - ); - let p = 0; - writeUInt32BE(verifyData, 29, p); - verifyData.utf8Write("hostkeys-prove-00@openssh.com", p += 4, 29); - writeUInt32BE(verifyData, sessionID.length, p += 29); - bufferCopy(sessionID, verifyData, 0, sessionID.length, p += 4); - writeUInt32BE(verifyData, keyPublic.length, p += sessionID.length); - bufferCopy(keyPublic, verifyData, 0, keyPublic.length, p += 4); - if (!(value = sigSSHToASN1(value, type))) - continue; - if (key.verify(verifyData, value, algo) === true) - ret.push(key); - } - sigParser.clear(); - bufferParser.clear(); - cb(null, ret); - }); - client._protocol.openssh_hostKeysProve(keys); - return; - } - process.nextTick( - cb, - new Error( - "strictVendor enabled and server is not OpenSSH or compatible version" - ) - ); - } - function getKeyAlgos(client, key, serverSigAlgs) { - switch (key.type) { - case "ssh-rsa": - if (client._protocol._compatFlags & COMPAT.IMPLY_RSA_SHA2_SIGALGS) { - if (!Array.isArray(serverSigAlgs)) - serverSigAlgs = ["rsa-sha2-256", "rsa-sha2-512"]; - else - serverSigAlgs = ["rsa-sha2-256", "rsa-sha2-512", ...serverSigAlgs]; - } - if (Array.isArray(serverSigAlgs)) { - if (serverSigAlgs.indexOf("rsa-sha2-256") !== -1) - return [["rsa-sha2-256", "sha256"]]; - if (serverSigAlgs.indexOf("rsa-sha2-512") !== -1) - return [["rsa-sha2-512", "sha512"]]; - if (serverSigAlgs.indexOf("ssh-rsa") === -1) - return []; - } - return [["ssh-rsa", "sha1"]]; - } - } - module2.exports = Client; - } -}); - -// node_modules/ssh2/lib/http-agents.js -var require_http_agents = __commonJS({ - "node_modules/ssh2/lib/http-agents.js"(exports2) { - "use strict"; - var { Agent: HttpAgent } = require("http"); - var { Agent: HttpsAgent } = require("https"); - var { connect: tlsConnect } = require("tls"); - var Client; - for (const ctor of [HttpAgent, HttpsAgent]) { - class SSHAgent extends ctor { - constructor(connectCfg, agentOptions) { - super(agentOptions); - this._connectCfg = connectCfg; - this._defaultSrcIP = agentOptions && agentOptions.srcIP || "localhost"; - } - createConnection(options, cb) { - const srcIP = options && options.localAddress || this._defaultSrcIP; - const srcPort = options && options.localPort || 0; - const dstIP = options.host; - const dstPort = options.port; - if (Client === void 0) - Client = require_client2(); - const client = new Client(); - let triedForward = false; - client.on("ready", () => { - client.forwardOut(srcIP, srcPort, dstIP, dstPort, (err, stream2) => { - triedForward = true; - if (err) { - client.end(); - return cb(err); - } - stream2.once("close", () => client.end()); - cb(null, decorateStream(stream2, ctor, options)); - }); - }).on("error", cb).on("close", () => { - if (!triedForward) - cb(new Error("Unexpected connection close")); - }).connect(this._connectCfg); - } - } - exports2[ctor === HttpAgent ? "SSHTTPAgent" : "SSHTTPSAgent"] = SSHAgent; - } - function noop3() { - } - function decorateStream(stream2, ctor, options) { - if (ctor === HttpAgent) { - stream2.setKeepAlive = noop3; - stream2.setNoDelay = noop3; - stream2.setTimeout = noop3; - stream2.ref = noop3; - stream2.unref = noop3; - stream2.destroySoon = stream2.destroy; - return stream2; - } - options.socket = stream2; - const wrapped = tlsConnect(options); - const onClose = /* @__PURE__ */ (() => { - let called = false; - return () => { - if (called) - return; - called = true; - if (stream2.isPaused()) - stream2.resume(); - }; - })(); - wrapped.on("end", onClose).on("close", onClose); - return wrapped; - } - } -}); - -// node_modules/ssh2/lib/server.js -var require_server = __commonJS({ - "node_modules/ssh2/lib/server.js"(exports2, module2) { - "use strict"; - var { Server: netServer } = require("net"); - var EventEmitter = require("events"); - var { listenerCount } = EventEmitter; - var { - CHANNEL_OPEN_FAILURE, - DEFAULT_CIPHER, - DEFAULT_COMPRESSION, - DEFAULT_KEX, - DEFAULT_MAC, - DEFAULT_SERVER_HOST_KEY, - DISCONNECT_REASON, - DISCONNECT_REASON_BY_VALUE, - SUPPORTED_CIPHER, - SUPPORTED_COMPRESSION, - SUPPORTED_KEX, - SUPPORTED_MAC, - SUPPORTED_SERVER_HOST_KEY - } = require_constants6(); - var { init: cryptoInit } = require_crypto(); - var { KexInit } = require_kex(); - var { parseKey } = require_keyParser(); - var Protocol = require_Protocol(); - var { SFTP } = require_SFTP(); - var { writeUInt32BE } = require_utils4(); - var { - Channel, - MAX_WINDOW, - PACKET_SIZE, - windowAdjust, - WINDOW_THRESHOLD - } = require_Channel(); - var { - ChannelManager, - generateAlgorithmList, - isWritable, - onChannelOpenFailure, - onCHANNEL_CLOSE - } = require_utils5(); - var MAX_PENDING_AUTHS = 10; - var AuthContext = class extends EventEmitter { - constructor(protocol, username, service, method, cb) { - super(); - this.username = this.user = username; - this.service = service; - this.method = method; - this._initialResponse = false; - this._finalResponse = false; - this._multistep = false; - this._cbfinal = (allowed, methodsLeft, isPartial) => { - if (!this._finalResponse) { - this._finalResponse = true; - cb(this, allowed, methodsLeft, isPartial); - } - }; - this._protocol = protocol; - } - accept() { - this._cleanup && this._cleanup(); - this._initialResponse = true; - this._cbfinal(true); - } - reject(methodsLeft, isPartial) { - this._cleanup && this._cleanup(); - this._initialResponse = true; - this._cbfinal(false, methodsLeft, isPartial); - } - }; - var KeyboardAuthContext = class extends AuthContext { - constructor(protocol, username, service, method, submethods, cb) { - super(protocol, username, service, method, cb); - this._multistep = true; - this._cb = void 0; - this._onInfoResponse = (responses) => { - const callback = this._cb; - if (callback) { - this._cb = void 0; - callback(responses); - } - }; - this.submethods = submethods; - this.on("abort", () => { - this._cb && this._cb(new Error("Authentication request aborted")); - }); - } - prompt(prompts, title, instructions, cb) { - if (!Array.isArray(prompts)) - prompts = [prompts]; - if (typeof title === "function") { - cb = title; - title = instructions = void 0; - } else if (typeof instructions === "function") { - cb = instructions; - instructions = void 0; - } else if (typeof cb !== "function") { - cb = void 0; - } - for (let i = 0; i < prompts.length; ++i) { - if (typeof prompts[i] === "string") { - prompts[i] = { - prompt: prompts[i], - echo: true - }; - } - } - this._cb = cb; - this._initialResponse = true; - this._protocol.authInfoReq(title, instructions, prompts); - } - }; - var PKAuthContext = class extends AuthContext { - constructor(protocol, username, service, method, pkInfo, cb) { - super(protocol, username, service, method, cb); - this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key }; - this.hashAlgo = pkInfo.hashAlgo; - this.signature = pkInfo.signature; - this.blob = pkInfo.blob; - } - accept() { - if (!this.signature) { - this._initialResponse = true; - this._protocol.authPKOK(this.key.algo, this.key.data); - } else { - AuthContext.prototype.accept.call(this); - } - } - }; - var HostbasedAuthContext = class extends AuthContext { - constructor(protocol, username, service, method, pkInfo, cb) { - super(protocol, username, service, method, cb); - this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key }; - this.hashAlgo = pkInfo.hashAlgo; - this.signature = pkInfo.signature; - this.blob = pkInfo.blob; - this.localHostname = pkInfo.localHostname; - this.localUsername = pkInfo.localUsername; - } - }; - var PwdAuthContext = class extends AuthContext { - constructor(protocol, username, service, method, password, cb) { - super(protocol, username, service, method, cb); - this.password = password; - this._changeCb = void 0; - } - requestChange(prompt, cb) { - if (this._changeCb) - throw new Error("Change request already in progress"); - if (typeof prompt !== "string") - throw new Error("prompt argument must be a string"); - if (typeof cb !== "function") - throw new Error("Callback argument must be a function"); - this._changeCb = cb; - this._protocol.authPasswdChg(prompt); - } - }; - var Session = class extends EventEmitter { - constructor(client, info8, localChan) { - super(); - this.type = "session"; - this.subtype = void 0; - this.server = true; - this._ending = false; - this._channel = void 0; - this._chanInfo = { - type: "session", - incoming: { - id: localChan, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: "open" - }, - outgoing: { - id: info8.sender, - window: info8.window, - packetSize: info8.packetSize, - state: "open" - } - }; - } - }; - var Server = class extends EventEmitter { - constructor(cfg, listener) { - super(); - if (typeof cfg !== "object" || cfg === null) - throw new Error("Missing configuration object"); - const hostKeys = /* @__PURE__ */ Object.create(null); - const hostKeyAlgoOrder = []; - const hostKeys_ = cfg.hostKeys; - if (!Array.isArray(hostKeys_)) - throw new Error("hostKeys must be an array"); - const cfgAlgos = typeof cfg.algorithms === "object" && cfg.algorithms !== null ? cfg.algorithms : {}; - const hostKeyAlgos = generateAlgorithmList( - cfgAlgos.serverHostKey, - DEFAULT_SERVER_HOST_KEY, - SUPPORTED_SERVER_HOST_KEY - ); - for (let i = 0; i < hostKeys_.length; ++i) { - let privateKey; - if (Buffer.isBuffer(hostKeys_[i]) || typeof hostKeys_[i] === "string") - privateKey = parseKey(hostKeys_[i]); - else - privateKey = parseKey(hostKeys_[i].key, hostKeys_[i].passphrase); - if (privateKey instanceof Error) - throw new Error(`Cannot parse privateKey: ${privateKey.message}`); - if (Array.isArray(privateKey)) { - privateKey = privateKey[0]; - } - if (privateKey.getPrivatePEM() === null) - throw new Error("privateKey value contains an invalid private key"); - if (hostKeyAlgoOrder.includes(privateKey.type)) - continue; - if (privateKey.type === "ssh-rsa") { - let sha1Pos = hostKeyAlgos.indexOf("ssh-rsa"); - const sha256Pos = hostKeyAlgos.indexOf("rsa-sha2-256"); - const sha512Pos = hostKeyAlgos.indexOf("rsa-sha2-512"); - if (sha1Pos === -1) { - sha1Pos = Infinity; - } - [sha1Pos, sha256Pos, sha512Pos].sort(compareNumbers).forEach((pos) => { - if (pos === -1) - return; - let type; - switch (pos) { - case sha1Pos: - type = "ssh-rsa"; - break; - case sha256Pos: - type = "rsa-sha2-256"; - break; - case sha512Pos: - type = "rsa-sha2-512"; - break; - default: - return; - } - hostKeys[type] = privateKey; - hostKeyAlgoOrder.push(type); - }); - } else { - hostKeys[privateKey.type] = privateKey; - hostKeyAlgoOrder.push(privateKey.type); - } - } - const algorithms = { - kex: generateAlgorithmList( - cfgAlgos.kex, - DEFAULT_KEX, - SUPPORTED_KEX - ).concat(["kex-strict-s-v00@openssh.com"]), - serverHostKey: hostKeyAlgoOrder, - cs: { - cipher: generateAlgorithmList( - cfgAlgos.cipher, - DEFAULT_CIPHER, - SUPPORTED_CIPHER - ), - mac: generateAlgorithmList(cfgAlgos.hmac, DEFAULT_MAC, SUPPORTED_MAC), - compress: generateAlgorithmList( - cfgAlgos.compress, - DEFAULT_COMPRESSION, - SUPPORTED_COMPRESSION - ), - lang: [] - }, - sc: void 0 - }; - algorithms.sc = algorithms.cs; - if (typeof listener === "function") - this.on("connection", listener); - const origDebug = typeof cfg.debug === "function" ? cfg.debug : void 0; - const ident = cfg.ident ? Buffer.from(cfg.ident) : void 0; - const offer = new KexInit(algorithms); - this._srv = new netServer((socket) => { - if (this._connections >= this.maxConnections) { - socket.destroy(); - return; - } - ++this._connections; - socket.once("close", () => { - --this._connections; - }); - let debug2; - if (origDebug) { - const debugPrefix = `[${process.hrtime().join(".")}] `; - debug2 = (msg) => { - origDebug(`${debugPrefix}${msg}`); - }; - } - new Client(socket, hostKeys, ident, offer, debug2, this, cfg); - }).on("error", (err) => { - this.emit("error", err); - }).on("listening", () => { - this.emit("listening"); - }).on("close", () => { - this.emit("close"); - }); - this._connections = 0; - this.maxConnections = Infinity; - } - injectSocket(socket) { - this._srv.emit("connection", socket); - } - listen(...args) { - this._srv.listen(...args); - return this; - } - address() { - return this._srv.address(); - } - getConnections(cb) { - this._srv.getConnections(cb); - return this; - } - close(cb) { - this._srv.close(cb); - return this; - } - ref() { - this._srv.ref(); - return this; - } - unref() { - this._srv.unref(); - return this; - } - }; - Server.KEEPALIVE_CLIENT_INTERVAL = 15e3; - Server.KEEPALIVE_CLIENT_COUNT_MAX = 3; - var Client = class extends EventEmitter { - constructor(socket, hostKeys, ident, offer, debug2, server, srvCfg) { - super(); - let exchanges = 0; - let acceptedAuthSvc = false; - let pendingAuths = []; - let authCtx; - let kaTimer; - let onPacket; - const unsentGlobalRequestsReplies = []; - this._sock = socket; - this._chanMgr = new ChannelManager(this); - this._debug = debug2; - this.noMoreSessions = false; - this.authenticated = false; - function onClientPreHeaderError(err) { - } - this.on("error", onClientPreHeaderError); - const DEBUG_HANDLER = !debug2 ? void 0 : (p, display, msg) => { - debug2(`Debug output from client: ${JSON.stringify(msg)}`); - }; - const kaIntvl = typeof srvCfg.keepaliveInterval === "number" && isFinite(srvCfg.keepaliveInterval) && srvCfg.keepaliveInterval > 0 ? srvCfg.keepaliveInterval : typeof Server.KEEPALIVE_CLIENT_INTERVAL === "number" && isFinite(Server.KEEPALIVE_CLIENT_INTERVAL) && Server.KEEPALIVE_CLIENT_INTERVAL > 0 ? Server.KEEPALIVE_CLIENT_INTERVAL : -1; - const kaCountMax = typeof srvCfg.keepaliveCountMax === "number" && isFinite(srvCfg.keepaliveCountMax) && srvCfg.keepaliveCountMax >= 0 ? srvCfg.keepaliveCountMax : typeof Server.KEEPALIVE_CLIENT_COUNT_MAX === "number" && isFinite(Server.KEEPALIVE_CLIENT_COUNT_MAX) && Server.KEEPALIVE_CLIENT_COUNT_MAX >= 0 ? Server.KEEPALIVE_CLIENT_COUNT_MAX : -1; - let kaCurCount = 0; - if (kaIntvl !== -1 && kaCountMax !== -1) { - this.once("ready", () => { - const onClose = () => { - clearInterval(kaTimer); - }; - this.on("close", onClose).on("end", onClose); - kaTimer = setInterval(() => { - if (++kaCurCount > kaCountMax) { - clearInterval(kaTimer); - const err = new Error("Keepalive timeout"); - err.level = "client-timeout"; - this.emit("error", err); - this.end(); - } else { - proto.ping(); - } - }, kaIntvl); - }); - onPacket = () => { - kaTimer && kaTimer.refresh(); - kaCurCount = 0; - }; - } - const proto = this._protocol = new Protocol({ - server: true, - hostKeys, - ident, - offer, - onPacket, - greeting: srvCfg.greeting, - banner: srvCfg.banner, - onWrite: (data) => { - if (isWritable(socket)) - socket.write(data); - }, - onError: (err) => { - if (!proto._destruct) - socket.removeAllListeners("data"); - this.emit("error", err); - try { - socket.end(); - } catch { - } - }, - onHeader: (header) => { - this.removeListener("error", onClientPreHeaderError); - const info8 = { - ip: socket.remoteAddress, - family: socket.remoteFamily, - port: socket.remotePort, - header - }; - if (!server.emit("connection", this, info8)) { - proto.disconnect(DISCONNECT_REASON.BY_APPLICATION); - socket.end(); - return; - } - if (header.greeting) - this.emit("greeting", header.greeting); - }, - onHandshakeComplete: (negotiated) => { - if (++exchanges > 1) - this.emit("rekey"); - this.emit("handshake", negotiated); - }, - debug: debug2, - messageHandlers: { - DEBUG: DEBUG_HANDLER, - DISCONNECT: (p, reason, desc) => { - if (reason !== DISCONNECT_REASON.BY_APPLICATION) { - if (!desc) { - desc = DISCONNECT_REASON_BY_VALUE[reason]; - if (desc === void 0) - desc = `Unexpected disconnection reason: ${reason}`; - } - const err = new Error(desc); - err.code = reason; - this.emit("error", err); - } - socket.end(); - }, - CHANNEL_OPEN: (p, info8) => { - if (info8.type === "session" && this.noMoreSessions || !this.authenticated) { - const reasonCode = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; - return proto.channelOpenFail(info8.sender, reasonCode); - } - let localChan = -1; - let reason; - let replied = false; - let accept; - const reject = () => { - if (replied) - return; - replied = true; - if (reason === void 0) { - if (localChan === -1) - reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; - else - reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED; - } - if (localChan !== -1) - this._chanMgr.remove(localChan); - proto.channelOpenFail(info8.sender, reason, ""); - }; - const reserveChannel = () => { - localChan = this._chanMgr.add(); - if (localChan === -1) { - reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; - if (debug2) { - debug2("Automatic rejection of incoming channel open: no channels available"); - } - } - return localChan !== -1; - }; - const data = info8.data; - switch (info8.type) { - case "session": - if (listenerCount(this, "session") && reserveChannel()) { - accept = () => { - if (replied) - return; - replied = true; - const instance = new Session(this, info8, localChan); - this._chanMgr.update(localChan, instance); - proto.channelOpenConfirm( - info8.sender, - localChan, - MAX_WINDOW, - PACKET_SIZE - ); - return instance; - }; - this.emit("session", accept, reject); - return; - } - break; - case "direct-tcpip": - if (listenerCount(this, "tcpip") && reserveChannel()) { - accept = () => { - if (replied) - return; - replied = true; - const chanInfo = { - type: void 0, - incoming: { - id: localChan, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: "open" - }, - outgoing: { - id: info8.sender, - window: info8.window, - packetSize: info8.packetSize, - state: "open" - } - }; - const stream2 = new Channel(this, chanInfo, { server: true }); - this._chanMgr.update(localChan, stream2); - proto.channelOpenConfirm( - info8.sender, - localChan, - MAX_WINDOW, - PACKET_SIZE - ); - return stream2; - }; - this.emit("tcpip", accept, reject, data); - return; - } - break; - case "direct-streamlocal@openssh.com": - if (listenerCount(this, "openssh.streamlocal") && reserveChannel()) { - accept = () => { - if (replied) - return; - replied = true; - const chanInfo = { - type: void 0, - incoming: { - id: localChan, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: "open" - }, - outgoing: { - id: info8.sender, - window: info8.window, - packetSize: info8.packetSize, - state: "open" - } - }; - const stream2 = new Channel(this, chanInfo, { server: true }); - this._chanMgr.update(localChan, stream2); - proto.channelOpenConfirm( - info8.sender, - localChan, - MAX_WINDOW, - PACKET_SIZE - ); - return stream2; - }; - this.emit("openssh.streamlocal", accept, reject, data); - return; - } - break; - default: - reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE; - if (debug2) { - debug2(`Automatic rejection of unsupported incoming channel open type: ${info8.type}`); - } - } - if (reason === void 0) { - reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; - if (debug2) { - debug2(`Automatic rejection of unexpected incoming channel open for: ${info8.type}`); - } - } - reject(); - }, - CHANNEL_OPEN_CONFIRMATION: (p, info8) => { - const channel = this._chanMgr.get(info8.recipient); - if (typeof channel !== "function") - return; - const chanInfo = { - type: channel.type, - incoming: { - id: info8.recipient, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: "open" - }, - outgoing: { - id: info8.sender, - window: info8.window, - packetSize: info8.packetSize, - state: "open" - } - }; - const instance = new Channel(this, chanInfo, { server: true }); - this._chanMgr.update(info8.recipient, instance); - channel(void 0, instance); - }, - CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== "function") - return; - const info8 = { reason, description }; - onChannelOpenFailure(this, recipient, info8, channel); - }, - CHANNEL_DATA: (p, recipient, data) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== "object" || channel === null) - return; - if (channel.constructor === Session) { - channel = channel._channel; - if (!channel) - return; - } - if (channel.incoming.window === 0) - return; - channel.incoming.window -= data.length; - if (channel.push(data) === false) { - channel._waitChanDrain = true; - return; - } - if (channel.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(channel); - }, - CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => { - }, - CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== "object" || channel === null) - return; - if (channel.constructor === Session) { - channel = channel._channel; - if (!channel) - return; - } - channel.outgoing.window += amount; - if (channel._waitWindow) { - channel._waitWindow = false; - if (channel._chunk) { - channel._write(channel._chunk, null, channel._chunkcb); - } else if (channel._chunkcb) { - channel._chunkcb(); - } else if (channel._chunkErr) { - channel.stderr._write( - channel._chunkErr, - null, - channel._chunkcbErr - ); - } else if (channel._chunkcbErr) { - channel._chunkcbErr(); - } - } - }, - CHANNEL_SUCCESS: (p, recipient) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== "object" || channel === null) - return; - if (channel.constructor === Session) { - channel = channel._channel; - if (!channel) - return; - } - if (channel._callbacks.length) - channel._callbacks.shift()(false); - }, - CHANNEL_FAILURE: (p, recipient) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== "object" || channel === null) - return; - if (channel.constructor === Session) { - channel = channel._channel; - if (!channel) - return; - } - if (channel._callbacks.length) - channel._callbacks.shift()(true); - }, - CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => { - const session = this._chanMgr.get(recipient); - if (typeof session !== "object" || session === null) - return; - let replied = false; - let accept; - let reject; - if (session.constructor !== Session) { - if (wantReply) - proto.channelFailure(session.outgoing.id); - return; - } - if (wantReply) { - if (type !== "shell" && type !== "exec" && type !== "subsystem") { - accept = () => { - if (replied || session._ending || session._channel) - return; - replied = true; - proto.channelSuccess(session._chanInfo.outgoing.id); - }; - } - reject = () => { - if (replied || session._ending || session._channel) - return; - replied = true; - proto.channelFailure(session._chanInfo.outgoing.id); - }; - } - if (session._ending) { - reject && reject(); - return; - } - switch (type) { - // "pre-real session start" requests - case "env": - if (listenerCount(session, "env")) { - session.emit("env", accept, reject, { - key: data.name, - val: data.value - }); - return; - } - break; - case "pty-req": - if (listenerCount(session, "pty")) { - session.emit("pty", accept, reject, data); - return; - } - break; - case "window-change": - if (listenerCount(session, "window-change")) - session.emit("window-change", accept, reject, data); - else - reject && reject(); - break; - case "x11-req": - if (listenerCount(session, "x11")) { - session.emit("x11", accept, reject, data); - return; - } - break; - // "post-real session start" requests - case "signal": - if (listenerCount(session, "signal")) { - session.emit("signal", accept, reject, { - name: data - }); - return; - } - break; - // XXX: is `auth-agent-req@openssh.com` really "post-real session - // start"? - case "auth-agent-req@openssh.com": - if (listenerCount(session, "auth-agent")) { - session.emit("auth-agent", accept, reject); - return; - } - break; - // "real session start" requests - case "shell": - if (listenerCount(session, "shell")) { - accept = () => { - if (replied || session._ending || session._channel) - return; - replied = true; - if (wantReply) - proto.channelSuccess(session._chanInfo.outgoing.id); - const channel = new Channel( - this, - session._chanInfo, - { server: true } - ); - channel.subtype = session.subtype = type; - session._channel = channel; - return channel; - }; - session.emit("shell", accept, reject); - return; - } - break; - case "exec": - if (listenerCount(session, "exec")) { - accept = () => { - if (replied || session._ending || session._channel) - return; - replied = true; - if (wantReply) - proto.channelSuccess(session._chanInfo.outgoing.id); - const channel = new Channel( - this, - session._chanInfo, - { server: true } - ); - channel.subtype = session.subtype = type; - session._channel = channel; - return channel; - }; - session.emit("exec", accept, reject, { - command: data - }); - return; - } - break; - case "subsystem": { - let useSFTP = data === "sftp"; - accept = () => { - if (replied || session._ending || session._channel) - return; - replied = true; - if (wantReply) - proto.channelSuccess(session._chanInfo.outgoing.id); - let instance; - if (useSFTP) { - instance = new SFTP(this, session._chanInfo, { - server: true, - debug: debug2 - }); - } else { - instance = new Channel( - this, - session._chanInfo, - { server: true } - ); - instance.subtype = session.subtype = `${type}:${data}`; - } - session._channel = instance; - return instance; - }; - if (data === "sftp") { - if (listenerCount(session, "sftp")) { - session.emit("sftp", accept, reject); - return; - } - useSFTP = false; - } - if (listenerCount(session, "subsystem")) { - session.emit("subsystem", accept, reject, { - name: data - }); - return; - } - break; - } - } - debug2 && debug2( - `Automatic rejection of incoming channel request: ${type}` - ); - reject && reject(); - }, - CHANNEL_EOF: (p, recipient) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== "object" || channel === null) - return; - if (channel.constructor === Session) { - if (!channel._ending) { - channel._ending = true; - channel.emit("eof"); - channel.emit("end"); - } - channel = channel._channel; - if (!channel) - return; - } - if (channel.incoming.state !== "open") - return; - channel.incoming.state = "eof"; - if (channel.readable) - channel.push(null); - }, - CHANNEL_CLOSE: (p, recipient) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== "object" || channel === null) - return; - if (channel.constructor === Session) { - channel._ending = true; - channel.emit("close"); - channel = channel._channel; - if (!channel) - return; - } - onCHANNEL_CLOSE(this, recipient, channel); - }, - // Begin service/auth-related ========================================== - SERVICE_REQUEST: (p, service) => { - if (exchanges === 0 || acceptedAuthSvc || this.authenticated || service !== "ssh-userauth") { - proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE); - socket.end(); - return; - } - acceptedAuthSvc = true; - proto.serviceAccept(service); - }, - USERAUTH_REQUEST: (p, username, service, method, methodData) => { - if (exchanges === 0 || this.authenticated || authCtx && (authCtx.username !== username || authCtx.service !== service) || method !== "password" && method !== "publickey" && method !== "hostbased" && method !== "keyboard-interactive" && method !== "none" || pendingAuths.length === MAX_PENDING_AUTHS) { - proto.disconnect(DISCONNECT_REASON.PROTOCOL_ERROR); - socket.end(); - return; - } else if (service !== "ssh-connection") { - proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE); - socket.end(); - return; - } - let ctx; - switch (method) { - case "keyboard-interactive": - ctx = new KeyboardAuthContext( - proto, - username, - service, - method, - methodData, - onAuthDecide - ); - break; - case "publickey": - ctx = new PKAuthContext( - proto, - username, - service, - method, - methodData, - onAuthDecide - ); - break; - case "hostbased": - ctx = new HostbasedAuthContext( - proto, - username, - service, - method, - methodData, - onAuthDecide - ); - break; - case "password": - if (authCtx && authCtx instanceof PwdAuthContext && authCtx._changeCb) { - const cb = authCtx._changeCb; - authCtx._changeCb = void 0; - cb(methodData.newPassword); - return; - } - ctx = new PwdAuthContext( - proto, - username, - service, - method, - methodData, - onAuthDecide - ); - break; - case "none": - ctx = new AuthContext( - proto, - username, - service, - method, - onAuthDecide - ); - break; - } - if (authCtx) { - if (!authCtx._initialResponse) { - return pendingAuths.push(ctx); - } else if (authCtx._multistep && !authCtx._finalResponse) { - authCtx._cleanup && authCtx._cleanup(); - authCtx.emit("abort"); - } - } - authCtx = ctx; - if (listenerCount(this, "authentication")) - this.emit("authentication", authCtx); - else - authCtx.reject(); - }, - USERAUTH_INFO_RESPONSE: (p, responses) => { - if (authCtx && authCtx instanceof KeyboardAuthContext) - authCtx._onInfoResponse(responses); - }, - // End service/auth-related ============================================ - GLOBAL_REQUEST: (p, name, wantReply, data) => { - const reply = { - type: null, - buf: null - }; - function setReply(type, buf) { - reply.type = type; - reply.buf = buf; - sendReplies(); - } - if (wantReply) - unsentGlobalRequestsReplies.push(reply); - if ((name === "tcpip-forward" || name === "cancel-tcpip-forward" || name === "no-more-sessions@openssh.com" || name === "streamlocal-forward@openssh.com" || name === "cancel-streamlocal-forward@openssh.com") && listenerCount(this, "request") && this.authenticated) { - let accept; - let reject; - if (wantReply) { - let replied = false; - accept = (chosenPort) => { - if (replied) - return; - replied = true; - let bufPort; - if (name === "tcpip-forward" && data.bindPort === 0 && typeof chosenPort === "number") { - bufPort = Buffer.allocUnsafe(4); - writeUInt32BE(bufPort, chosenPort, 0); - } - setReply("SUCCESS", bufPort); - }; - reject = () => { - if (replied) - return; - replied = true; - setReply("FAILURE"); - }; - } - if (name === "no-more-sessions@openssh.com") { - this.noMoreSessions = true; - accept && accept(); - return; - } - this.emit("request", accept, reject, name, data); - } else if (wantReply) { - setReply("FAILURE"); - } - } - } - }); - socket.pause(); - cryptoInit.then(() => { - proto.start(); - socket.on("data", (data) => { - try { - proto.parse(data, 0, data.length); - } catch (ex) { - this.emit("error", ex); - try { - if (isWritable(socket)) - socket.end(); - } catch { - } - } - }); - socket.resume(); - }).catch((err) => { - this.emit("error", err); - try { - if (isWritable(socket)) - socket.end(); - } catch { - } - }); - socket.on("error", (err) => { - err.level = "socket"; - this.emit("error", err); - }).once("end", () => { - debug2 && debug2("Socket ended"); - proto.cleanup(); - this.emit("end"); - }).once("close", () => { - debug2 && debug2("Socket closed"); - proto.cleanup(); - this.emit("close"); - const err = new Error("No response from server"); - this._chanMgr.cleanup(err); - }); - const onAuthDecide = (ctx, allowed, methodsLeft, isPartial) => { - if (authCtx === ctx && !this.authenticated) { - if (allowed) { - authCtx = void 0; - this.authenticated = true; - proto.authSuccess(); - pendingAuths = []; - this.emit("ready"); - } else { - proto.authFailure(methodsLeft, isPartial); - if (pendingAuths.length) { - authCtx = pendingAuths.pop(); - if (listenerCount(this, "authentication")) - this.emit("authentication", authCtx); - else - authCtx.reject(); - } - } - } - }; - function sendReplies() { - while (unsentGlobalRequestsReplies.length > 0 && unsentGlobalRequestsReplies[0].type) { - const reply = unsentGlobalRequestsReplies.shift(); - if (reply.type === "SUCCESS") - proto.requestSuccess(reply.buf); - if (reply.type === "FAILURE") - proto.requestFailure(); - } - } - } - end() { - if (this._sock && isWritable(this._sock)) { - this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION); - this._sock.end(); - } - return this; - } - x11(originAddr, originPort, cb) { - const opts = { originAddr, originPort }; - openChannel(this, "x11", opts, cb); - return this; - } - forwardOut(boundAddr, boundPort, remoteAddr, remotePort, cb) { - const opts = { boundAddr, boundPort, remoteAddr, remotePort }; - openChannel(this, "forwarded-tcpip", opts, cb); - return this; - } - openssh_forwardOutStreamLocal(socketPath, cb) { - const opts = { socketPath }; - openChannel(this, "forwarded-streamlocal@openssh.com", opts, cb); - return this; - } - rekey(cb) { - let error3; - try { - this._protocol.rekey(); - } catch (ex) { - error3 = ex; - } - if (typeof cb === "function") { - if (error3) - process.nextTick(cb, error3); - else - this.once("rekey", cb); - } - } - setNoDelay(noDelay) { - if (this._sock && typeof this._sock.setNoDelay === "function") - this._sock.setNoDelay(noDelay); - return this; - } - }; - function openChannel(self2, type, opts, cb) { - const initWindow = MAX_WINDOW; - const maxPacket = PACKET_SIZE; - if (typeof opts === "function") { - cb = opts; - opts = {}; - } - const wrapper = (err, stream2) => { - cb(err, stream2); - }; - wrapper.type = type; - const localChan = self2._chanMgr.add(wrapper); - if (localChan === -1) { - cb(new Error("No free channels available")); - return; - } - switch (type) { - case "forwarded-tcpip": - self2._protocol.forwardedTcpip(localChan, initWindow, maxPacket, opts); - break; - case "x11": - self2._protocol.x11(localChan, initWindow, maxPacket, opts); - break; - case "forwarded-streamlocal@openssh.com": - self2._protocol.openssh_forwardedStreamLocal( - localChan, - initWindow, - maxPacket, - opts - ); - break; - default: - throw new Error(`Unsupported channel type: ${type}`); - } - } - function compareNumbers(a, b) { - return a - b; - } - module2.exports = Server; - module2.exports.IncomingClient = Client; - } -}); - -// node_modules/ssh2/lib/keygen.js -var require_keygen = __commonJS({ - "node_modules/ssh2/lib/keygen.js"(exports2, module2) { - "use strict"; - var { - createCipheriv, - generateKeyPair: generateKeyPair_, - generateKeyPairSync: generateKeyPairSync_, - getCurves, - randomBytes - } = require("crypto"); - var { Ber } = require_lib3(); - var bcrypt_pbkdf = require_bcrypt_pbkdf().pbkdf; - var { CIPHER_INFO } = require_crypto(); - var SALT_LEN = 16; - var DEFAULT_ROUNDS = 16; - var curves = getCurves(); - var ciphers = new Map(Object.entries(CIPHER_INFO)); - function makeArgs(type, opts) { - if (typeof type !== "string") - throw new TypeError("Key type must be a string"); - const publicKeyEncoding = { type: "spki", format: "der" }; - const privateKeyEncoding = { type: "pkcs8", format: "der" }; - switch (type.toLowerCase()) { - case "rsa": { - if (typeof opts !== "object" || opts === null) - throw new TypeError("Missing options object for RSA key"); - const modulusLength = opts.bits; - if (!Number.isInteger(modulusLength)) - throw new TypeError("RSA bits must be an integer"); - if (modulusLength <= 0 || modulusLength > 16384) - throw new RangeError("RSA bits must be non-zero and <= 16384"); - return ["rsa", { modulusLength, publicKeyEncoding, privateKeyEncoding }]; - } - case "ecdsa": { - if (typeof opts !== "object" || opts === null) - throw new TypeError("Missing options object for ECDSA key"); - if (!Number.isInteger(opts.bits)) - throw new TypeError("ECDSA bits must be an integer"); - let namedCurve; - switch (opts.bits) { - case 256: - namedCurve = "prime256v1"; - break; - case 384: - namedCurve = "secp384r1"; - break; - case 521: - namedCurve = "secp521r1"; - break; - default: - throw new Error("ECDSA bits must be 256, 384, or 521"); - } - if (!curves.includes(namedCurve)) - throw new Error("Unsupported ECDSA bits value"); - return ["ec", { namedCurve, publicKeyEncoding, privateKeyEncoding }]; - } - case "ed25519": - return ["ed25519", { publicKeyEncoding, privateKeyEncoding }]; - default: - throw new Error(`Unsupported key type: ${type}`); - } - } - function parseDERs(keyType, pub, priv) { - switch (keyType) { - case "rsa": { - let reader = new Ber.Reader(priv); - reader.readSequence(); - if (reader.readInt() !== 0) - throw new Error("Unsupported version in RSA private key"); - reader.readSequence(); - if (reader.readOID() !== "1.2.840.113549.1.1.1") - throw new Error("Bad RSA private OID"); - if (reader.readByte() !== Ber.Null) - throw new Error("Malformed RSA private key (expected null)"); - if (reader.readByte() !== 0) { - throw new Error( - "Malformed RSA private key (expected zero-length null)" - ); - } - reader = new Ber.Reader(reader.readString(Ber.OctetString, true)); - reader.readSequence(); - if (reader.readInt() !== 0) - throw new Error("Unsupported version in RSA private key"); - const n = reader.readString(Ber.Integer, true); - const e = reader.readString(Ber.Integer, true); - const d = reader.readString(Ber.Integer, true); - const p = reader.readString(Ber.Integer, true); - const q = reader.readString(Ber.Integer, true); - reader.readString(Ber.Integer, true); - reader.readString(Ber.Integer, true); - const iqmp = reader.readString(Ber.Integer, true); - const keyName = Buffer.from("ssh-rsa"); - const privBuf = Buffer.allocUnsafe( - 4 + keyName.length + 4 + n.length + 4 + e.length + 4 + d.length + 4 + iqmp.length + 4 + p.length + 4 + q.length - ); - let pos = 0; - privBuf.writeUInt32BE(keyName.length, pos += 0); - privBuf.set(keyName, pos += 4); - privBuf.writeUInt32BE(n.length, pos += keyName.length); - privBuf.set(n, pos += 4); - privBuf.writeUInt32BE(e.length, pos += n.length); - privBuf.set(e, pos += 4); - privBuf.writeUInt32BE(d.length, pos += e.length); - privBuf.set(d, pos += 4); - privBuf.writeUInt32BE(iqmp.length, pos += d.length); - privBuf.set(iqmp, pos += 4); - privBuf.writeUInt32BE(p.length, pos += iqmp.length); - privBuf.set(p, pos += 4); - privBuf.writeUInt32BE(q.length, pos += p.length); - privBuf.set(q, pos += 4); - const pubBuf = Buffer.allocUnsafe( - 4 + keyName.length + 4 + e.length + 4 + n.length - ); - pos = 0; - pubBuf.writeUInt32BE(keyName.length, pos += 0); - pubBuf.set(keyName, pos += 4); - pubBuf.writeUInt32BE(e.length, pos += keyName.length); - pubBuf.set(e, pos += 4); - pubBuf.writeUInt32BE(n.length, pos += e.length); - pubBuf.set(n, pos += 4); - return { sshName: keyName.toString(), priv: privBuf, pub: pubBuf }; - } - case "ec": { - let reader = new Ber.Reader(pub); - reader.readSequence(); - reader.readSequence(); - if (reader.readOID() !== "1.2.840.10045.2.1") - throw new Error("Bad ECDSA public OID"); - reader.readOID(); - let pubBin = reader.readString(Ber.BitString, true); - { - let i = 0; - for (; i < pubBin.length && pubBin[i] === 0; ++i) ; - if (i > 0) - pubBin = pubBin.slice(i); - } - reader = new Ber.Reader(priv); - reader.readSequence(); - if (reader.readInt() !== 0) - throw new Error("Unsupported version in ECDSA private key"); - reader.readSequence(); - if (reader.readOID() !== "1.2.840.10045.2.1") - throw new Error("Bad ECDSA private OID"); - const curveOID = reader.readOID(); - let sshCurveName; - switch (curveOID) { - case "1.2.840.10045.3.1.7": - sshCurveName = "nistp256"; - break; - case "1.3.132.0.34": - sshCurveName = "nistp384"; - break; - case "1.3.132.0.35": - sshCurveName = "nistp521"; - break; - default: - throw new Error("Unsupported curve in ECDSA private key"); - } - reader = new Ber.Reader(reader.readString(Ber.OctetString, true)); - reader.readSequence(); - if (reader.readInt() !== 1) - throw new Error("Unsupported version in ECDSA private key"); - const privBin = Buffer.concat([ - Buffer.from([0]), - reader.readString(Ber.OctetString, true) - ]); - const keyName = Buffer.from(`ecdsa-sha2-${sshCurveName}`); - sshCurveName = Buffer.from(sshCurveName); - const privBuf = Buffer.allocUnsafe( - 4 + keyName.length + 4 + sshCurveName.length + 4 + pubBin.length + 4 + privBin.length - ); - let pos = 0; - privBuf.writeUInt32BE(keyName.length, pos += 0); - privBuf.set(keyName, pos += 4); - privBuf.writeUInt32BE(sshCurveName.length, pos += keyName.length); - privBuf.set(sshCurveName, pos += 4); - privBuf.writeUInt32BE(pubBin.length, pos += sshCurveName.length); - privBuf.set(pubBin, pos += 4); - privBuf.writeUInt32BE(privBin.length, pos += pubBin.length); - privBuf.set(privBin, pos += 4); - const pubBuf = Buffer.allocUnsafe( - 4 + keyName.length + 4 + sshCurveName.length + 4 + pubBin.length - ); - pos = 0; - pubBuf.writeUInt32BE(keyName.length, pos += 0); - pubBuf.set(keyName, pos += 4); - pubBuf.writeUInt32BE(sshCurveName.length, pos += keyName.length); - pubBuf.set(sshCurveName, pos += 4); - pubBuf.writeUInt32BE(pubBin.length, pos += sshCurveName.length); - pubBuf.set(pubBin, pos += 4); - return { sshName: keyName.toString(), priv: privBuf, pub: pubBuf }; - } - case "ed25519": { - let reader = new Ber.Reader(pub); - reader.readSequence(); - reader.readSequence(); - if (reader.readOID() !== "1.3.101.112") - throw new Error("Bad ED25519 public OID"); - let pubBin = reader.readString(Ber.BitString, true); - { - let i = 0; - for (; i < pubBin.length && pubBin[i] === 0; ++i) ; - if (i > 0) - pubBin = pubBin.slice(i); - } - reader = new Ber.Reader(priv); - reader.readSequence(); - if (reader.readInt() !== 0) - throw new Error("Unsupported version in ED25519 private key"); - reader.readSequence(); - if (reader.readOID() !== "1.3.101.112") - throw new Error("Bad ED25519 private OID"); - reader = new Ber.Reader(reader.readString(Ber.OctetString, true)); - const privBin = reader.readString(Ber.OctetString, true); - const keyName = Buffer.from("ssh-ed25519"); - const privBuf = Buffer.allocUnsafe( - 4 + keyName.length + 4 + pubBin.length + 4 + (privBin.length + pubBin.length) - ); - let pos = 0; - privBuf.writeUInt32BE(keyName.length, pos += 0); - privBuf.set(keyName, pos += 4); - privBuf.writeUInt32BE(pubBin.length, pos += keyName.length); - privBuf.set(pubBin, pos += 4); - privBuf.writeUInt32BE( - privBin.length + pubBin.length, - pos += pubBin.length - ); - privBuf.set(privBin, pos += 4); - privBuf.set(pubBin, pos += privBin.length); - const pubBuf = Buffer.allocUnsafe( - 4 + keyName.length + 4 + pubBin.length - ); - pos = 0; - pubBuf.writeUInt32BE(keyName.length, pos += 0); - pubBuf.set(keyName, pos += 4); - pubBuf.writeUInt32BE(pubBin.length, pos += keyName.length); - pubBuf.set(pubBin, pos += 4); - return { sshName: keyName.toString(), priv: privBuf, pub: pubBuf }; - } - } - } - function convertKeys(keyType, pub, priv, opts) { - let format = "new"; - let encrypted; - let comment = ""; - if (typeof opts === "object" && opts !== null) { - if (typeof opts.comment === "string" && opts.comment) - comment = opts.comment; - if (typeof opts.format === "string" && opts.format) - format = opts.format; - if (opts.passphrase) { - let passphrase; - if (typeof opts.passphrase === "string") - passphrase = Buffer.from(opts.passphrase); - else if (Buffer.isBuffer(opts.passphrase)) - passphrase = opts.passphrase; - else - throw new Error("Invalid passphrase"); - if (opts.cipher === void 0) - throw new Error("Missing cipher name"); - const cipher = ciphers.get(opts.cipher); - if (cipher === void 0) - throw new Error("Invalid cipher name"); - if (format === "new") { - let rounds = DEFAULT_ROUNDS; - if (opts.rounds !== void 0) { - if (!Number.isInteger(opts.rounds)) - throw new TypeError("rounds must be an integer"); - if (opts.rounds > 0) - rounds = opts.rounds; - } - const gen = Buffer.allocUnsafe(cipher.keyLen + cipher.ivLen); - const salt = randomBytes(SALT_LEN); - const r = bcrypt_pbkdf( - passphrase, - passphrase.length, - salt, - salt.length, - gen, - gen.length, - rounds - ); - if (r !== 0) - return new Error("Failed to generate information to encrypt key"); - const kdfOptions = Buffer.allocUnsafe(4 + salt.length + 4); - { - let pos = 0; - kdfOptions.writeUInt32BE(salt.length, pos += 0); - kdfOptions.set(salt, pos += 4); - kdfOptions.writeUInt32BE(rounds, pos += salt.length); - } - encrypted = { - cipher, - cipherName: opts.cipher, - kdfName: "bcrypt", - kdfOptions, - key: gen.slice(0, cipher.keyLen), - iv: gen.slice(cipher.keyLen) - }; - } - } - } - switch (format) { - case "new": { - let privateB64 = "-----BEGIN OPENSSH PRIVATE KEY-----\n"; - let publicB64; - const cipherName = Buffer.from(encrypted ? encrypted.cipherName : "none"); - const kdfName = Buffer.from(encrypted ? encrypted.kdfName : "none"); - const kdfOptions = encrypted ? encrypted.kdfOptions : Buffer.alloc(0); - const blockLen = encrypted ? encrypted.cipher.blockLen : 8; - const parsed = parseDERs(keyType, pub, priv); - const checkInt = randomBytes(4); - const commentBin = Buffer.from(comment); - const privBlobLen = 4 + 4 + parsed.priv.length + 4 + commentBin.length; - let padding = []; - for (let i = 1; (privBlobLen + padding.length) % blockLen; ++i) - padding.push(i & 255); - padding = Buffer.from(padding); - let privBlob = Buffer.allocUnsafe(privBlobLen + padding.length); - let extra; - { - let pos = 0; - privBlob.set(checkInt, pos += 0); - privBlob.set(checkInt, pos += 4); - privBlob.set(parsed.priv, pos += 4); - privBlob.writeUInt32BE(commentBin.length, pos += parsed.priv.length); - privBlob.set(commentBin, pos += 4); - privBlob.set(padding, pos += commentBin.length); - } - if (encrypted) { - const options = { authTagLength: encrypted.cipher.authLen }; - const cipher = createCipheriv( - encrypted.cipher.sslName, - encrypted.key, - encrypted.iv, - options - ); - cipher.setAutoPadding(false); - privBlob = Buffer.concat([cipher.update(privBlob), cipher.final()]); - if (encrypted.cipher.authLen > 0) - extra = cipher.getAuthTag(); - else - extra = Buffer.alloc(0); - encrypted.key.fill(0); - encrypted.iv.fill(0); - } else { - extra = Buffer.alloc(0); - } - const magicBytes = Buffer.from("openssh-key-v1\0"); - const privBin = Buffer.allocUnsafe( - magicBytes.length + 4 + cipherName.length + 4 + kdfName.length + 4 + kdfOptions.length + 4 + 4 + parsed.pub.length + 4 + privBlob.length + extra.length - ); - { - let pos = 0; - privBin.set(magicBytes, pos += 0); - privBin.writeUInt32BE(cipherName.length, pos += magicBytes.length); - privBin.set(cipherName, pos += 4); - privBin.writeUInt32BE(kdfName.length, pos += cipherName.length); - privBin.set(kdfName, pos += 4); - privBin.writeUInt32BE(kdfOptions.length, pos += kdfName.length); - privBin.set(kdfOptions, pos += 4); - privBin.writeUInt32BE(1, pos += kdfOptions.length); - privBin.writeUInt32BE(parsed.pub.length, pos += 4); - privBin.set(parsed.pub, pos += 4); - privBin.writeUInt32BE(privBlob.length, pos += parsed.pub.length); - privBin.set(privBlob, pos += 4); - privBin.set(extra, pos += privBlob.length); - } - { - const b64 = privBin.base64Slice(0, privBin.length); - let formatted = b64.replace(/.{64}/g, "$&\n"); - if (b64.length & 63) - formatted += "\n"; - privateB64 += formatted; - } - { - const b64 = parsed.pub.base64Slice(0, parsed.pub.length); - publicB64 = `${parsed.sshName} ${b64}${comment ? ` ${comment}` : ""}`; - } - privateB64 += "-----END OPENSSH PRIVATE KEY-----\n"; - return { - private: privateB64, - public: publicB64 - }; - } - default: - throw new Error("Invalid output key format"); - } - } - function noop3() { - } - module2.exports = { - generateKeyPair: (keyType, opts, cb) => { - if (typeof opts === "function") { - cb = opts; - opts = void 0; - } - if (typeof cb !== "function") - cb = noop3; - const args = makeArgs(keyType, opts); - generateKeyPair_(...args, (err, pub, priv) => { - if (err) - return cb(err); - let ret; - try { - ret = convertKeys(args[0], pub, priv, opts); - } catch (ex) { - return cb(ex); - } - cb(null, ret); - }); - }, - generateKeyPairSync: (keyType, opts) => { - const args = makeArgs(keyType, opts); - const { publicKey: pub, privateKey: priv } = generateKeyPairSync_(...args); - return convertKeys(args[0], pub, priv, opts); - } - }; - } -}); - -// node_modules/ssh2/lib/index.js -var require_lib5 = __commonJS({ - "node_modules/ssh2/lib/index.js"(exports2, module2) { - "use strict"; - var { - AgentProtocol, - BaseAgent, - createAgent, - CygwinAgent, - OpenSSHAgent, - PageantAgent - } = require_agent2(); - var { - SSHTTPAgent: HTTPAgent, - SSHTTPSAgent: HTTPSAgent - } = require_http_agents(); - var { parseKey } = require_keyParser(); - var { - flagsToString, - OPEN_MODE, - STATUS_CODE, - stringToFlags - } = require_SFTP(); - module2.exports = { - AgentProtocol, - BaseAgent, - createAgent, - Client: require_client2(), - CygwinAgent, - HTTPAgent, - HTTPSAgent, - OpenSSHAgent, - PageantAgent, - Server: require_server(), - utils: { - parseKey, - ...require_keygen(), - sftp: { - flagsToString, - OPEN_MODE, - STATUS_CODE, - stringToFlags - } - } - }; - } -}); - -// node_modules/docker-modem/lib/ssh.js -var require_ssh = __commonJS({ - "node_modules/docker-modem/lib/ssh.js"(exports2, module2) { - var Client = require_lib5().Client; - var http2 = require("http"); - module2.exports = function(opt) { - var conn = new Client(); - var agent = new http2.Agent(); - agent.createConnection = function(options, fn) { - try { - conn.once("ready", function() { - conn.exec("docker system dial-stdio", function(err, stream2) { - if (err) { - handleError(err, fn); - } - fn(null, stream2); - stream2.addListener("error", (err2) => { - handleError(err2, fn); - }); - stream2.once("close", () => { - conn.end(); - agent.destroy(); - }); - }); - }).on("error", (err) => { - handleError(err, fn); - }).connect(opt); - conn.once("end", () => agent.destroy()); - } catch (err) { - handleError(err); - } - }; - function handleError(err, cb) { - conn.end(); - agent.destroy(); - if (cb) { - cb(err); - } else { - throw err; - } - } - return agent; - }; - } -}); - -// 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/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); - if (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 = arguments[i] != null ? arguments[i] : {}; - if (i % 2) { - ownKeys(Object(source), true).forEach(function(key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function(key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - return target; - } - function _defineProperty(obj, key, value) { - 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, descriptor.key, descriptor); - } - } - function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) _defineProperties(Constructor.prototype, protoProps); - if (staticProps) _defineProperties(Constructor, staticProps); - return Constructor; - } - 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 join(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 concat(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({}, options, { - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - })); - } - }]); - return BufferList; - })(); - } -}); - -// 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(stream2, err) { - var rState = stream2._readableState; - var wState = stream2._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream2.destroy(err); - else stream2.emit("error", err); - } - module2.exports = { - destroy, - undestroy, - errorOrDestroy - }; - } -}); - -// node_modules/readable-stream/errors.js -var require_errors3 = __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 endsWith(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 (endsWith(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_state = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/state.js"(exports2, module2) { - "use strict"; - var ERR_INVALID_OPT_VALUE = require_errors3().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 inherits(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 inherits(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 { - util = require("util"); - if (typeof util.inherits !== "function") throw ""; - module2.exports = util.inherits; - } catch (e) { - module2.exports = require_inherits_browser(); - } - var util; - } -}); - -// 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/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 = Writable2; - function CorkedRequest(state) { - var _this = this; - this.next = null; - this.entry = null; - this.finish = function() { - onCorkedFinish(_this, state); - }; - } - var Duplex; - Writable2.WritableState = WritableState; - var internalUtil = { - deprecate: require_node() - }; - var Stream = require_stream(); - var Buffer2 = require("buffer").Buffer; - var OurUint8Array = global.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_errors3().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()(Writable2, Stream); - function nop() { - } - function WritableState(options, stream2, isDuplex) { - Duplex = Duplex || require_stream_duplex(); - options = options || {}; - if (typeof isDuplex !== "boolean") isDuplex = stream2 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(er) { - onwrite(stream2, er); - }; - 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(Writable2, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable2) return false; - return object && object._writableState instanceof WritableState; - } - }); - } else { - realHasInstance = function realHasInstance2(object) { - return object instanceof this; - }; - } - function Writable2(options) { - Duplex = Duplex || require_stream_duplex(); - var isDuplex = this instanceof Duplex; - if (!isDuplex && !realHasInstance.call(Writable2, this)) return new Writable2(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); - } - Writable2.prototype.pipe = function() { - errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); - }; - function writeAfterEnd(stream2, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); - errorOrDestroy(stream2, er); - process.nextTick(cb, er); - } - function validChunk(stream2, state, chunk, cb) { - var er; - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== "string" && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer"], chunk); - } - if (er) { - errorOrDestroy(stream2, er); - process.nextTick(cb, er); - return false; - } - return true; - } - Writable2.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; - }; - Writable2.prototype.cork = function() { - this._writableState.corked++; - }; - Writable2.prototype.uncork = function() { - var state = this._writableState; - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } - }; - Writable2.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(Writable2.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(Writable2.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(stream2, 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(stream2, state, false, len, chunk, encoding, cb); - } - return ret; - } - function doWrite(stream2, 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) stream2._writev(chunk, state.onwrite); - else stream2._write(chunk, encoding, state.onwrite); - state.sync = false; - } - function onwriteError(stream2, state, sync, er, cb) { - --state.pendingcb; - if (sync) { - process.nextTick(cb, er); - process.nextTick(finishMaybe, stream2, state); - stream2._writableState.errorEmitted = true; - errorOrDestroy(stream2, er); - } else { - cb(er); - stream2._writableState.errorEmitted = true; - errorOrDestroy(stream2, er); - finishMaybe(stream2, state); - } - } - function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; - } - function onwrite(stream2, er) { - var state = stream2._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== "function") throw new ERR_MULTIPLE_CALLBACK(); - onwriteStateUpdate(state); - if (er) onwriteError(stream2, state, sync, er, cb); - else { - var finished = needFinish(state) || stream2.destroyed; - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream2, state); - } - if (sync) { - process.nextTick(afterWrite, stream2, state, finished, cb); - } else { - afterWrite(stream2, state, finished, cb); - } - } - } - function afterWrite(stream2, state, finished, cb) { - if (!finished) onwriteDrain(stream2, state); - state.pendingcb--; - cb(); - finishMaybe(stream2, state); - } - function onwriteDrain(stream2, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream2.emit("drain"); - } - } - function clearBuffer(stream2, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - if (stream2._writev && entry && entry.next) { - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - buffer.allBuffers = allBuffers; - doWrite(stream2, state, true, state.length, buffer, "", 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(stream2, 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; - } - Writable2.prototype._write = function(chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED("_write()")); - }; - Writable2.prototype._writev = null; - Writable2.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(Writable2.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(stream2, state) { - stream2._final(function(err) { - state.pendingcb--; - if (err) { - errorOrDestroy(stream2, err); - } - state.prefinished = true; - stream2.emit("prefinish"); - finishMaybe(stream2, state); - }); - } - function prefinish(stream2, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream2._final === "function" && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - process.nextTick(callFinal, stream2, state); - } else { - state.prefinished = true; - stream2.emit("prefinish"); - } - } - } - function finishMaybe(stream2, state) { - var need = needFinish(state); - if (need) { - prefinish(stream2, state); - if (state.pendingcb === 0) { - state.finished = true; - stream2.emit("finish"); - if (state.autoDestroy) { - var rState = stream2._readableState; - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream2.destroy(); - } - } - } - } - return need; - } - function endWritable(stream2, state, cb) { - state.ending = true; - finishMaybe(stream2, state); - if (cb) { - if (state.finished) process.nextTick(cb); - else stream2.once("finish", cb); - } - state.ended = true; - stream2.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(Writable2.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; - } - }); - Writable2.prototype.destroy = destroyImpl.destroy; - Writable2.prototype._undestroy = destroyImpl.undestroy; - Writable2.prototype._destroy = function(err, cb) { - cb(err); - }; - } -}); - -// 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 Writable2 = require_stream_writable(); - require_inherits()(Duplex, Readable2); - { - keys = objectKeys(Writable2.prototype); - for (v = 0; v < keys.length; v++) { - method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable2.prototype[method]; - } - } - var keys; - var method; - var v; - function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable2.call(this, options); - Writable2.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/string_decoder/node_modules/safe-buffer/index.js -var require_safe_buffer = __commonJS({ - "node_modules/string_decoder/node_modules/safe-buffer/index.js"(exports2, module2) { - var buffer = require("buffer"); - var Buffer2 = buffer.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 = buffer; - } else { - copyProps(buffer, 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(size, fill, encoding) { - if (typeof size !== "number") { - throw new TypeError("Argument must be a number"); - } - var buf = Buffer2(size); - 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(size) { - if (typeof size !== "number") { - throw new TypeError("Argument must be a number"); - } - return Buffer2(size); - }; - SafeBuffer.allocUnsafeSlow = function(size) { - if (typeof size !== "number") { - throw new TypeError("Argument must be a number"); - } - return buffer.SlowBuffer(size); - }; - } -}); - -// 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 j = buf.length - 1; - if (j < i) return 0; - var nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self2.lastNeed = nb - 1; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self2.lastNeed = nb - 2; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - 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_errors3().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 noop3() { - } - function isRequest(stream2) { - return stream2.setHeader && typeof stream2.abort === "function"; - } - function eos(stream2, opts, callback) { - if (typeof opts === "function") return eos(stream2, null, opts); - if (!opts) opts = {}; - callback = once(callback || noop3); - var readable = opts.readable || opts.readable !== false && stream2.readable; - var writable = opts.writable || opts.writable !== false && stream2.writable; - var onlegacyfinish = function onlegacyfinish2() { - if (!stream2.writable) onfinish(); - }; - var writableEnded = stream2._writableState && stream2._writableState.finished; - var onfinish = function onfinish2() { - writable = false; - writableEnded = true; - if (!readable) callback.call(stream2); - }; - var readableEnded = stream2._readableState && stream2._readableState.endEmitted; - var onend = function onend2() { - readable = false; - readableEnded = true; - if (!writable) callback.call(stream2); - }; - var onerror = function onerror2(err) { - callback.call(stream2, err); - }; - var onclose = function onclose2() { - var err; - if (readable && !readableEnded) { - if (!stream2._readableState || !stream2._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream2, err); - } - if (writable && !writableEnded) { - if (!stream2._writableState || !stream2._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream2, err); - } - }; - var onrequest = function onrequest2() { - stream2.req.on("finish", onfinish); - }; - if (isRequest(stream2)) { - stream2.on("complete", onfinish); - stream2.on("abort", onclose); - if (stream2.req) onrequest(); - else stream2.on("request", onrequest); - } else if (writable && !stream2._writableState) { - stream2.on("end", onlegacyfinish); - stream2.on("close", onlegacyfinish); - } - stream2.on("end", onend); - stream2.on("finish", onfinish); - if (opts.error !== false) stream2.on("error", onerror); - stream2.on("close", onclose); - return function() { - stream2.removeListener("complete", onfinish); - stream2.removeListener("abort", onclose); - stream2.removeListener("request", onrequest); - if (stream2.req) stream2.req.removeListener("finish", onfinish); - stream2.removeListener("end", onlegacyfinish); - stream2.removeListener("close", onlegacyfinish); - stream2.removeListener("finish", onfinish); - stream2.removeListener("end", onend); - stream2.removeListener("error", onerror); - stream2.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) { - if (key in obj) { - Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); - } else { - obj[key] = value; - } - return obj; - } - var finished = require_end_of_stream(); - var kLastResolve = /* @__PURE__ */ Symbol("lastResolve"); - var kLastReject = /* @__PURE__ */ Symbol("lastReject"); - var kError = /* @__PURE__ */ Symbol("error"); - var kEnded = /* @__PURE__ */ Symbol("ended"); - var kLastPromise = /* @__PURE__ */ Symbol("lastPromise"); - var kHandlePromise = /* @__PURE__ */ Symbol("handlePromise"); - var kStream = /* @__PURE__ */ 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 error3 = this[kError]; - if (error3 !== null) { - return Promise.reject(error3); - } - 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(stream2) { - var _Object$create; - var iterator2 = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { - value: stream2, - 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: stream2._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(stream2, 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; - }); - stream2.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(gen, resolve, reject, _next, _throw, key, arg) { - try { - var info8 = gen[key](arg); - var value = info8.value; - } catch (error3) { - reject(error3); - return; - } - if (info8.done) { - resolve(value); - } else { - Promise.resolve(value).then(_next, _throw); - } - } - function _asyncToGenerator(fn) { - return function() { - var self2 = this, args = arguments; - return new Promise(function(resolve, reject) { - var gen = fn.apply(self2, args); - function _next(value) { - asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); - } - function _throw(err) { - asyncGeneratorStep(gen, 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); - if (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 = arguments[i] != null ? arguments[i] : {}; - if (i % 2) { - ownKeys(Object(source), true).forEach(function(key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function(key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - return target; - } - function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); - } else { - obj[key] = value; - } - return obj; - } - var ERR_INVALID_ARG_TYPE = require_errors3().codes.ERR_INVALID_ARG_TYPE; - function from(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 _ref = yield iterator2.next(), value = _ref.value, done = _ref.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 = from; - } -}); - -// 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 = global.Uint8Array || function() { - }; - function _uint8ArrayToBuffer(chunk) { - return Buffer2.from(chunk); - } - function _isUint8Array(obj) { - return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array; - } - var debugUtil = require("util"); - var debug2; - if (debugUtil && debugUtil.debuglog) { - debug2 = debugUtil.debuglog("stream"); - } else { - debug2 = function debug3() { - }; - } - var BufferList = require_buffer_list(); - var destroyImpl = require_destroy(); - var _require = require_state(); - var getHighWaterMark = _require.getHighWaterMark; - var _require$codes = require_errors3().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 from; - require_inherits()(Readable2, Stream); - var errorOrDestroy = destroyImpl.errorOrDestroy; - var kProxyEvents = ["error", "close", "destroy", "pause", "resume"]; - function prependListener(emitter, event, fn) { - if (typeof emitter.prependListener === "function") return emitter.prependListener(event, fn); - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn); - else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn); - else emitter._events[event] = [fn, emitter._events[event]]; - } - function ReadableState(options, stream2, isDuplex) { - Duplex = Duplex || require_stream_duplex(); - options = options || {}; - if (typeof isDuplex !== "boolean") isDuplex = stream2 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(stream2, chunk, encoding, addToFront, skipChunkCheck) { - debug2("readableAddChunk", chunk); - var state = stream2._readableState; - if (chunk === null) { - state.reading = false; - onEofChunk(stream2, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - if (er) { - errorOrDestroy(stream2, er); - } 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(stream2, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT()); - else addChunk(stream2, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream2, 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(stream2, state, chunk, false); - else maybeReadMore(stream2, state); - } else { - addChunk(stream2, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - maybeReadMore(stream2, state); - } - } - return !state.ended && (state.length < state.highWaterMark || state.length === 0); - } - function addChunk(stream2, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream2.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(stream2); - } - maybeReadMore(stream2, state); - } - function chunkInvalid(state, chunk) { - var er; - if (!_isUint8Array(chunk) && typeof chunk !== "string" && chunk !== void 0 && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer", "Uint8Array"], chunk); - } - return er; - } - 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) { - debug2("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)) { - debug2("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; - debug2("need readable", doRead); - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug2("length less than watermark", doRead); - } - if (state.ended || state.reading) { - doRead = false; - debug2("reading or ended", doRead); - } else if (doRead) { - debug2("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(stream2, state) { - debug2("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(stream2); - } else { - state.needReadable = false; - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_(stream2); - } - } - } - function emitReadable(stream2) { - var state = stream2._readableState; - debug2("emitReadable", state.needReadable, state.emittedReadable); - state.needReadable = false; - if (!state.emittedReadable) { - debug2("emitReadable", state.flowing); - state.emittedReadable = true; - process.nextTick(emitReadable_, stream2); - } - } - function emitReadable_(stream2) { - var state = stream2._readableState; - debug2("emitReadable_", state.destroyed, state.length, state.ended); - if (!state.destroyed && (state.length || state.ended)) { - stream2.emit("readable"); - state.emittedReadable = false; - } - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow(stream2); - } - function maybeReadMore(stream2, state) { - if (!state.readingMore) { - state.readingMore = true; - process.nextTick(maybeReadMore_, stream2, state); - } - } - function maybeReadMore_(stream2, state) { - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug2("maybeReadMore read 0"); - stream2.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; - debug2("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) { - debug2("onunpipe"); - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } - function onend() { - debug2("onend"); - dest.end(); - } - var ondrain = pipeOnDrain(src); - dest.on("drain", ondrain); - var cleanedUp = false; - function cleanup() { - debug2("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) { - debug2("ondata"); - var ret = dest.write(chunk); - debug2("dest.write", ret); - if (ret === false) { - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug2("false write response, pause", state.awaitDrain); - state.awaitDrain++; - } - src.pause(); - } - } - function onerror(er) { - debug2("onerror", er); - unpipe(); - dest.removeListener("error", onerror); - if (EElistenerCount(dest, "error") === 0) errorOrDestroy(dest, er); - } - prependListener(dest, "error", onerror); - function onclose() { - dest.removeListener("finish", onfinish); - unpipe(); - } - dest.once("close", onclose); - function onfinish() { - debug2("onfinish"); - dest.removeListener("close", onclose); - unpipe(); - } - dest.once("finish", onfinish); - function unpipe() { - debug2("unpipe"); - src.unpipe(dest); - } - dest.emit("pipe", src); - if (!state.flowing) { - debug2("pipe resume"); - src.resume(); - } - return dest; - }; - function pipeOnDrain(src) { - return function pipeOnDrainFunctionResult() { - var state = src._readableState; - debug2("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 index = indexOf(state.pipes, dest); - if (index === -1) return this; - state.pipes.splice(index, 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, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - 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; - debug2("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, fn) { - var res = Stream.prototype.removeListener.call(this, ev, fn); - 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) { - debug2("readable nexttick read 0"); - self2.read(0); - } - Readable2.prototype.resume = function() { - var state = this._readableState; - if (!state.flowing) { - debug2("resume"); - state.flowing = !state.readableListening; - resume(this, state); - } - state.paused = false; - return this; - }; - function resume(stream2, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - process.nextTick(resume_, stream2, state); - } - } - function resume_(stream2, state) { - debug2("resume", state.reading); - if (!state.reading) { - stream2.read(0); - } - state.resumeScheduled = false; - stream2.emit("resume"); - flow(stream2); - if (state.flowing && !state.reading) stream2.read(0); - } - Readable2.prototype.pause = function() { - debug2("call pause flowing=%j", this._readableState.flowing); - if (this._readableState.flowing !== false) { - debug2("pause"); - this._readableState.flowing = false; - this.emit("pause"); - } - this._readableState.paused = true; - return this; - }; - function flow(stream2) { - var state = stream2._readableState; - debug2("flow", state.flowing); - while (state.flowing && stream2.read() !== null) { - ; - } - } - Readable2.prototype.wrap = function(stream2) { - var _this = this; - var state = this._readableState; - var paused = false; - stream2.on("end", function() { - debug2("wrapped end"); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } - _this.push(null); - }); - stream2.on("data", function(chunk) { - debug2("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; - stream2.pause(); - } - }); - for (var i in stream2) { - if (this[i] === void 0 && typeof stream2[i] === "function") { - this[i] = /* @__PURE__ */ (function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream2[method].apply(stream2, arguments); - }; - })(i); - } - } - for (var n = 0; n < kProxyEvents.length; n++) { - stream2.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } - this._read = function(n2) { - debug2("wrapped _read", n2); - if (paused) { - paused = false; - stream2.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(stream2) { - var state = stream2._readableState; - debug2("endReadable", state.endEmitted); - if (!state.endEmitted) { - state.ended = true; - process.nextTick(endReadableNT, state, stream2); - } - } - function endReadableNT(state, stream2) { - debug2("endReadableNT", state.endEmitted, state.length); - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream2.readable = false; - stream2.emit("end"); - if (state.autoDestroy) { - var wState = stream2._writableState; - if (!wState || wState.autoDestroy && wState.finished) { - stream2.destroy(); - } - } - } - } - if (typeof Symbol === "function") { - Readable2.from = function(iterable, opts) { - if (from === void 0) { - from = require_from(); - } - return from(Readable2, iterable, opts); - }; - } - function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; - } - } -}); - -// 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_errors3().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(er, data) { - var ts = this._transformState; - ts.transforming = false; - var cb = ts.writecb; - if (cb === null) { - return this.emit("error", new ERR_MULTIPLE_CALLBACK()); - } - ts.writechunk = null; - ts.writecb = null; - if (data != null) - this.push(data); - cb(er); - var rs = this._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.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(er, data) { - done(_this, er, 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 ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } - }; - Transform.prototype._read = function(n) { - var ts = this._transformState; - if (ts.writechunk !== null && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - ts.needTransform = true; - } - }; - Transform.prototype._destroy = function(err, cb) { - Duplex.prototype._destroy.call(this, err, function(err2) { - cb(err2); - }); - }; - function done(stream2, er, data) { - if (er) return stream2.emit("error", er); - if (data != null) - stream2.push(data); - if (stream2._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); - if (stream2._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); - return stream2.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_errors3().codes; - var ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS; - var ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; - function noop3(err) { - if (err) throw err; - } - function isRequest(stream2) { - return stream2.setHeader && typeof stream2.abort === "function"; - } - function destroyer(stream2, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream2.on("close", function() { - closed = true; - }); - if (eos === void 0) eos = require_end_of_stream(); - eos(stream2, { - 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 (isRequest(stream2)) return stream2.abort(); - if (typeof stream2.destroy === "function") return stream2.destroy(); - callback(err || new ERR_STREAM_DESTROYED("pipe")); - }; - } - function call(fn) { - fn(); - } - function pipe(from, to) { - return from.pipe(to); - } - function popCallback(streams) { - if (!streams.length) return noop3; - if (typeof streams[streams.length - 1] !== "function") return noop3; - 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 error3; - var destroys = streams.map(function(stream2, i) { - var reading = i < streams.length - 1; - var writing = i > 0; - return destroyer(stream2, reading, writing, function(err) { - if (!error3) error3 = err; - if (err) destroys.forEach(call); - if (reading) return; - destroys.forEach(call); - callback(error3); - }); - }); - return streams.reduce(pipe); - } - module2.exports = pipeline; - } -}); - -// node_modules/readable-stream/readable.js -var require_readable2 = __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/docker-modem/lib/http_duplex.js -var require_http_duplex = __commonJS({ - "node_modules/docker-modem/lib/http_duplex.js"(exports2, module2) { - module2.exports = HttpDuplex; - var util = require("util"); - var stream2 = require_readable2(); - util.inherits(HttpDuplex, stream2.Duplex); - function HttpDuplex(req, res, options) { - var self2 = this; - if (!(self2 instanceof HttpDuplex)) return new HttpDuplex(req, res, options); - stream2.Duplex.call(self2, options); - self2._output = null; - self2.connect(req, res); - } - HttpDuplex.prototype.connect = function(req, res) { - var self2 = this; - self2.req = req; - self2._output = res; - self2.emit("response", res); - res.on("data", function(c) { - if (!self2.push(c)) self2._output.pause(); - }); - res.on("end", function() { - self2.push(null); - }); - }; - HttpDuplex.prototype._read = function(n) { - if (this._output) this._output.resume(); - }; - HttpDuplex.prototype._write = function(chunk, encoding, cb) { - this.req.write(chunk, encoding); - cb(); - }; - HttpDuplex.prototype.end = function(chunk, encoding, cb) { - this._output.socket.destroySoon(); - return this.req.end(chunk, encoding, cb); - }; - HttpDuplex.prototype.destroy = function() { - this.req.destroy(); - this._output.socket.destroy(); - }; - HttpDuplex.prototype.destroySoon = function() { - this.req.destroy(); - this._output.socket.destroy(); - }; - } -}); - -// node_modules/ms/index.js -var require_ms = __commonJS({ - "node_modules/ms/index.js"(exports2, module2) { - var s = 1e3; - var m = s * 60; - var h = m * 60; - var d = h * 24; - var w = d * 7; - var y = d * 365.25; - module2.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === "string" && val.length > 0) { - return parse3(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 parse3(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 * y; - case "weeks": - case "week": - case "w": - return n * w; - 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 * m; - 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 >= m) { - return Math.round(ms / m) + "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 >= m) { - return plural(ms, msAbs, m, "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 hash = 0; - for (let i = 0; i < namespace.length; i++) { - hash = (hash << 5) - hash + namespace.charCodeAt(i); - hash |= 0; - } - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; - function debug2(...args) { - if (!debug2.enabled) { - return; - } - const self2 = debug2; - 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 index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - if (match === "%%") { - return "%"; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === "function") { - const val = args[index]; - match = formatter.call(self2, val); - args.splice(index, 1); - index--; - } - return match; - }); - createDebug.formatArgs.call(self2, args); - const logFn = self2.log || createDebug.log; - logFn.apply(self2, args); - } - debug2.namespace = namespace; - debug2.useColors = createDebug.useColors(); - debug2.color = createDebug.selectColor(namespace); - debug2.extend = extend; - debug2.destroy = createDebug.destroy; - Object.defineProperty(debug2, "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(debug2); - } - return debug2; - } - function extend(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 split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean); - for (const ns of split) { - if (ns[0] === "-") { - createDebug.skips.push(ns.slice(1)); - } else { - createDebug.names.push(ns); - } - } - } - 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 skip of createDebug.skips) { - if (matchesTemplate(name, skip)) { - return false; - } - } - for (const ns of createDebug.names) { - if (matchesTemplate(name, ns)) { - 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 m; - 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 && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[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 index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, (match) => { - if (match === "%%") { - return; - } - index++; - if (match === "%c") { - lastC = index; - } - }); - 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 (error3) { - } - } - function load() { - let r; - try { - r = exports2.storage.getItem("debug") || exports2.storage.getItem("DEBUG"); - } catch (error3) { - } - if (!r && typeof process !== "undefined" && "env" in process) { - r = process.env.DEBUG; - } - return r; - } - function localstorage() { - try { - return localStorage; - } catch (error3) { - } - } - module2.exports = require_common()(exports2); - var { formatters } = module2.exports; - formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (error3) { - return "[UnexpectedJSONParseError]: " + error3.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 os = 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 = os.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((sign) => sign 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 version = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10); - switch (env.TERM_PROGRAM) { - case "iTerm.app": - return version >= 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(stream2) { - const level = supportsColor(stream2, stream2 && stream2.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_node2 = __commonJS({ - "node_modules/debug/src/node.js"(exports2, module2) { - var tty = require("tty"); - var util = require("util"); - exports2.init = init; - exports2.log = log; - exports2.formatArgs = formatArgs; - exports2.save = save; - exports2.load = load; - exports2.useColors = useColors; - exports2.destroy = util.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 (error3) { - } - 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, (_, k) => { - return k.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(util.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(debug2) { - debug2.inspectOpts = {}; - const keys = Object.keys(exports2.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug2.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 util.inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" "); - }; - formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util.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_node2(); - } - } -}); - -// node_modules/split-ca/index.js -var require_split_ca = __commonJS({ - "node_modules/split-ca/index.js"(exports2, module2) { - var fs3 = require("fs"); - module2.exports = function(filepath, split, encoding) { - split = typeof split !== "undefined" ? split : "\n"; - encoding = typeof encoding !== "undefined" ? encoding : "utf8"; - var ca = []; - var chain = fs3.readFileSync(filepath, encoding); - if (chain.indexOf("-END CERTIFICATE-") < 0 || chain.indexOf("-BEGIN CERTIFICATE-") < 0) { - throw Error("File does not contain 'BEGIN CERTIFICATE' or 'END CERTIFICATE'"); - } - chain = chain.split(split); - var cert = []; - var _i, _len; - for (_i = 0, _len = chain.length; _i < _len; _i++) { - var line = chain[_i]; - if (!(line.length !== 0)) { - continue; - } - cert.push(line); - if (line.match(/-END CERTIFICATE-/)) { - ca.push(cert.join(split)); - cert = []; - } - } - return ca; - }; - } -}); - -// node_modules/docker-modem/lib/modem.js -var require_modem = __commonJS({ - "node_modules/docker-modem/lib/modem.js"(exports2, module2) { - var querystring = require("querystring"); - var http2 = require_http(); - var fs3 = require("fs"); - var path = require("path"); - var url = require("url"); - var ssh = require_ssh(); - var HttpDuplex = require_http_duplex(); - var debug2 = require_src()("modem"); - var utils = require_utils3(); - var util = require("util"); - var splitca = require_split_ca(); - var os = require("os"); - var isWin = os.type() === "Windows_NT"; - var stream2 = require("stream"); - var defaultOpts = function() { - var host; - var opts = {}; - if (!process.env.DOCKER_HOST) { - opts.socketPath = isWin ? "//./pipe/docker_engine" : findDefaultUnixSocket; - } else if (process.env.DOCKER_HOST.indexOf("unix://") === 0) { - opts.socketPath = process.env.DOCKER_HOST.substring(7) || findDefaultUnixSocket; - } else if (process.env.DOCKER_HOST.indexOf("npipe://") === 0) { - opts.socketPath = process.env.DOCKER_HOST.substring(8) || "//./pipe/docker_engine"; - } else { - var hostStr = process.env.DOCKER_HOST; - if (hostStr.indexOf("//") < 0) { - hostStr = "tcp://" + hostStr; - } - try { - host = new url.URL(hostStr); - } catch (err) { - throw new Error("DOCKER_HOST env variable should be something like tcp://localhost:1234"); - } - opts.port = host.port; - if (process.env.DOCKER_TLS_VERIFY === "1" || opts.port === "2376") { - opts.protocol = "https"; - } else if (host.protocol === "ssh:") { - opts.protocol = "ssh"; - opts.username = host.username; - opts.sshOptions = { - agent: process.env.SSH_AUTH_SOCK - }; - } else { - opts.protocol = "http"; - } - if (process.env.DOCKER_PATH_PREFIX) { - opts.pathPrefix = process.env.DOCKER_PATH_PREFIX; - } else { - opts.pathPrefix = "/"; - } - opts.host = host.hostname; - if (process.env.DOCKER_CERT_PATH) { - opts.ca = splitca(path.join(process.env.DOCKER_CERT_PATH, "ca.pem")); - opts.cert = fs3.readFileSync(path.join(process.env.DOCKER_CERT_PATH, "cert.pem")); - opts.key = fs3.readFileSync(path.join(process.env.DOCKER_CERT_PATH, "key.pem")); - } - if (process.env.DOCKER_CLIENT_TIMEOUT) { - opts.timeout = parseInt(process.env.DOCKER_CLIENT_TIMEOUT, 10); - } - } - return opts; - }; - var findDefaultUnixSocket = function() { - return new Promise(function(resolve) { - var userDockerSocket = path.join(os.homedir(), ".docker", "run", "docker.sock"); - fs3.access(userDockerSocket, function(err) { - if (err) resolve("/var/run/docker.sock"); - else resolve(userDockerSocket); - }); - }); - }; - var Modem = function(options) { - var optDefaults = defaultOpts(); - var opts = Object.assign({}, optDefaults, options); - this.host = opts.host; - if (!this.host) { - this.socketPath = opts.socketPath; - } - this.port = opts.port; - this.pathPrefix = opts.pathPrefix; - this.username = opts.username; - this.password = opts.password; - this.version = opts.version; - this.key = opts.key; - this.cert = opts.cert; - this.ca = opts.ca; - this.timeout = opts.timeout; - this.connectionTimeout = opts.connectionTimeout; - this.checkServerIdentity = opts.checkServerIdentity; - this.agent = opts.agent; - this.headers = opts.headers || {}; - this.sshOptions = Object.assign({}, options ? options.sshOptions : {}, optDefaults.sshOptions); - if (this.sshOptions.agentForward === void 0) { - this.sshOptions.agentForward = opts.agentForward; - } - if (this.key && this.cert && this.ca) { - this.protocol = "https"; - } - this.protocol = opts.protocol || this.protocol || "http"; - }; - Modem.prototype.dial = function(options, callback) { - var opts, address, data; - if (options.options) { - opts = options.options; - } - if (opts && opts.authconfig) { - delete opts.authconfig; - } - if (opts && opts.abortSignal) { - delete opts.abortSignal; - } - if (this.version) { - options.path = "/" + this.version + options.path; - } - if (this.host) { - var parsed = url.parse(this.host); - address = url.format({ - protocol: parsed.protocol || this.protocol, - hostname: parsed.hostname || this.host, - port: this.port, - pathname: parsed.pathname || this.pathPrefix - }); - address = url.resolve(address, options.path); - } else { - address = options.path; - } - if (options.path.indexOf("?") !== -1) { - if (opts && Object.keys(opts).length > 0) { - address += this.buildQuerystring(opts._query || opts); - } else { - address = address.substring(0, address.length - 1); - } - } - var optionsf = { - path: address, - method: options.method, - headers: options.headers || Object.assign({}, this.headers), - key: this.key, - cert: this.cert, - ca: this.ca - }; - if (this.checkServerIdentity) { - optionsf.checkServerIdentity = this.checkServerIdentity; - } - if (this.agent) { - optionsf.agent = this.agent; - } - if (options.authconfig) { - optionsf.headers["X-Registry-Auth"] = options.authconfig.key || options.authconfig.base64 || Buffer.from(JSON.stringify(options.authconfig)).toString("base64").replace(/\+/g, "-").replace(/\//g, "_"); - } - if (options.registryconfig) { - optionsf.headers["X-Registry-Config"] = options.registryconfig.base64 || Buffer.from(JSON.stringify(options.registryconfig)).toString("base64"); - } - if (options.abortSignal) { - optionsf.signal = options.abortSignal; - } - if (options.file) { - if (typeof options.file === "string") { - data = fs3.createReadStream(path.resolve(options.file)); - } else { - data = options.file; - } - optionsf.headers["Content-Type"] = options?.headers?.["Content-Type"] ?? "application/tar"; - } else if (opts && options.method === "POST") { - data = JSON.stringify(opts._body || opts); - if (options.allowEmpty) { - optionsf.headers["Content-Type"] = options?.headers?.["Content-Type"] ?? "application/json"; - } else { - if (data !== "{}" && data !== '""') { - optionsf.headers["Content-Type"] = options?.headers?.["Content-Type"] ?? "application/json"; - } else { - data = void 0; - } - } - } - if (typeof data === "string") { - optionsf.headers["Content-Length"] = Buffer.byteLength(data); - } else if (Buffer.isBuffer(data) === true) { - optionsf.headers["Content-Length"] = data.length; - } else if (optionsf.method === "PUT" || options.hijack || options.openStdin) { - optionsf.headers["Transfer-Encoding"] = "chunked"; - } - if (options.hijack) { - optionsf.headers.Connection = "Upgrade"; - optionsf.headers.Upgrade = optionsf.headers.Upgrade ?? "tcp"; - } - if (this.socketPath) { - this.getSocketPath().then((socketPath) => { - optionsf.socketPath = socketPath; - this.buildRequest(optionsf, options, data, callback); - }); - } else { - var urlp = url.parse(address); - optionsf.hostname = urlp.hostname; - optionsf.port = urlp.port; - optionsf.path = urlp.path; - this.buildRequest(optionsf, options, data, callback); - } - }; - Modem.prototype.getSocketPath = function() { - if (!this.socketPath) return; - if (this.socketPathCache) return Promise.resolve(this.socketPathCache); - var socketPathValue = typeof this.socketPath === "function" ? this.socketPath() : this.socketPath; - this.socketPathCache = socketPathValue; - return Promise.resolve(socketPathValue); - }; - Modem.prototype.buildRequest = function(options, context3, data, callback) { - var self2 = this; - var connectionTimeoutTimer; - var finished = false; - var opts = self2.protocol === "ssh" ? Object.assign(options, { - agent: ssh(Object.assign({}, self2.sshOptions, { - "host": self2.host, - "port": self2.port, - "username": self2.username, - "password": self2.password - })), - protocol: "http:" - }) : options; - var req = null; - try { - req = http2[self2.protocol === "ssh" ? "http" : self2.protocol].request(opts, function() { - }); - } catch (e) { - callback(e); - return; - } - debug2("Sending: %s", util.inspect(options, { - showHidden: true, - depth: null - })); - if (self2.connectionTimeout) { - connectionTimeoutTimer = setTimeout(function() { - debug2("Connection Timeout of %s ms exceeded", self2.connectionTimeout); - req.destroy(); - }, self2.connectionTimeout); - } - if (self2.timeout) { - req.setTimeout(self2.timeout); - req.on("timeout", function() { - debug2("Timeout of %s ms exceeded", self2.timeout); - req.destroy(); - }); - } - if (context3.hijack === true) { - clearTimeout(connectionTimeoutTimer); - req.on("upgrade", function(res, sock, head) { - if (finished === false) { - finished = true; - if (head.length > 0) { - sock.unshift(head); - } - return callback(null, sock); - } - }); - } - req.on("connect", function() { - clearTimeout(connectionTimeoutTimer); - }); - req.on("disconnect", function() { - clearTimeout(connectionTimeoutTimer); - }); - req.on("response", function(res) { - clearTimeout(connectionTimeoutTimer); - if (context3.isStream === true) { - if (finished === false) { - finished = true; - self2.buildPayload(null, context3.isStream, context3.statusCodes, context3.openStdin, req, res, null, callback); - } - } else { - if (options.signal != null) { - stream2.addAbortSignal(options.signal, res); - } - var chunks = []; - res.on("data", function(chunk) { - chunks.push(chunk); - }); - res.on("end", function() { - var buffer = Buffer.concat(chunks); - var result = buffer.toString(); - debug2("Received: %s", result); - var json = utils.parseJSON(result) || buffer; - if (finished === false) { - finished = true; - self2.buildPayload(null, context3.isStream, context3.statusCodes, false, req, res, json, callback); - } - }); - } - }); - req.on("error", function(error3) { - clearTimeout(connectionTimeoutTimer); - if (finished === false) { - finished = true; - self2.buildPayload(error3, context3.isStream, context3.statusCodes, false, {}, {}, null, callback); - } - }); - if (typeof data === "string" || Buffer.isBuffer(data)) { - req.write(data); - } else if (data) { - data.on("error", function(error3) { - req.destroy(error3); - }); - data.pipe(req); - } - if (!context3.openStdin && (typeof data === "string" || data === void 0 || Buffer.isBuffer(data))) { - req.end(); - } - }; - Modem.prototype.buildPayload = function(err, isStream, statusCodes, openStdin, req, res, json, cb) { - if (err) return cb(err, null); - if (statusCodes[res.statusCode] !== true) { - getCause(isStream, res, json, function(err2, cause) { - if (err2) { - return cb(err2, null); - } - var msg = new Error( - "(HTTP code " + res.statusCode + ") " + (statusCodes[res.statusCode] || "unexpected") + " - " + (cause.message || cause.error || cause) + " " - ); - msg.reason = statusCodes[res.statusCode]; - msg.statusCode = res.statusCode; - msg.json = json; - cb(msg, null); - }); - } else { - if (openStdin) { - cb(null, new HttpDuplex(req, res)); - } else if (isStream) { - cb(null, res); - } else { - cb(null, json); - } - } - function getCause(isStream2, res2, json2, callback) { - var chunks = ""; - var done = false; - if (isStream2) { - res2.on("data", function(chunk) { - chunks += chunk; - }); - res2.on("error", function(err2) { - handler2(err2, null); - }); - res2.on("end", function() { - handler2(null, utils.parseJSON(chunks) || chunks); - }); - } else { - callback(null, json2); - } - function handler2(err2, data) { - if (done === false) { - if (err2) { - callback(err2); - } else { - callback(null, data); - } - } - done = true; - } - } - }; - Modem.prototype.demuxStream = function(streama, stdout, stderr) { - var pendingStreamType = null; - var pendingDataLength = null; - var buffer = Buffer.from(""); - function processData(data) { - if (data) { - buffer = Buffer.concat([buffer, data]); - } - if (pendingStreamType === null) { - if (buffer.length >= 8) { - var header = bufferSlice(8); - var streamType = header.readUInt8(0); - var dataLength = header.readUInt32BE(4); - if (streamType !== 0 && streamType !== 1 && streamType !== 2) { - var remaining = Buffer.concat([header, buffer]); - stdout.write(remaining); - buffer = Buffer.from(""); - pendingStreamType = null; - pendingDataLength = null; - streama.removeListener("data", processData); - streama.on("data", function(chunk) { - stdout.write(chunk); - }); - return; - } - pendingStreamType = streamType; - pendingDataLength = dataLength; - processData(); - } - } else { - if (buffer.length >= pendingDataLength) { - var content = bufferSlice(pendingDataLength); - if (pendingStreamType === 1) { - stdout.write(content); - } else { - stderr.write(content); - } - pendingStreamType = null; - pendingDataLength = null; - processData(); - } - } - } - function bufferSlice(end) { - var out = buffer.subarray(0, end); - buffer = Buffer.from(buffer.subarray(end, buffer.length)); - return out; - } - streama.on("data", processData); - }; - Modem.prototype.followProgress = function(streama, onFinished, onProgress) { - var buf = ""; - var output = []; - var finished = false; - streama.on("data", onStreamEvent); - streama.on("error", onStreamError); - streama.on("end", onStreamEnd); - streama.on("close", onStreamEnd); - function onStreamEvent(data) { - buf += data.toString(); - pump(); - function pump() { - var pos; - while ((pos = buf.indexOf("\n")) >= 0) { - if (pos == 0) { - buf = buf.slice(1); - continue; - } - processLine(buf.slice(0, pos)); - buf = buf.slice(pos + 1); - } - } - function processLine(line) { - if (line[line.length - 1] == "\r") line = line.substr(0, line.length - 1); - if (line.length > 0) { - var obj = JSON.parse(line); - output.push(obj); - if (onProgress) { - onProgress(obj); - } - } - } - } - ; - function onStreamError(err) { - finished = true; - streama.removeListener("data", onStreamEvent); - streama.removeListener("error", onStreamError); - streama.removeListener("end", onStreamEnd); - streama.removeListener("close", onStreamEnd); - onFinished(err, output); - } - function onStreamEnd() { - if (!finished) onFinished(null, output); - finished = true; - } - }; - Modem.prototype.buildQuerystring = function(opts) { - var clone = {}; - Object.keys(opts).map(function(key, i) { - if (opts[key] && typeof opts[key] === "object" && !Array.isArray(opts[key])) { - clone[key] = JSON.stringify(opts[key]); - } else { - clone[key] = opts[key]; - } - }); - return querystring.stringify(clone); - }; - module2.exports = Modem; - } -}); - -// node_modules/@balena/dockerignore/ignore.js -var require_ignore = __commonJS({ - "node_modules/@balena/dockerignore/ignore.js"(exports2, module2) { - "use strict"; - var path = require("path"); - var factory = (options) => new IgnoreBase(options); - factory.default = factory; - module2.exports = factory; - function make_array(subject) { - return Array.isArray(subject) ? subject : [subject]; - } - var REGEX_TRAILING_SLASH = /(?<=.)\/$/; - var REGEX_TRAILING_BACKSLASH = /(?<=.)\\$/; - var REGEX_TRAILING_PATH_SEP = path.sep === "\\" ? REGEX_TRAILING_BACKSLASH : REGEX_TRAILING_SLASH; - var KEY_IGNORE = typeof Symbol !== "undefined" ? /* @__PURE__ */ Symbol.for("dockerignore") : "dockerignore"; - function cleanPath(file) { - return path.normalize(file).replace(REGEX_TRAILING_PATH_SEP, ""); - } - function toSlash(file) { - if (path.sep === "/") { - return file; - } - return file.replace(/\\/g, "/"); - } - function fromSlash(file) { - if (path.sep === "/") { - return file; - } - return file.replace(/\//g, path.sep); - } - var IgnoreBase = class { - constructor({ - // https://github.com/kaelzhang/node-ignore/blob/5.1.4/index.js#L372 - ignorecase = true - } = {}) { - this._rules = []; - this._ignorecase = ignorecase; - this[KEY_IGNORE] = true; - this._initCache(); - } - _initCache() { - this._cache = {}; - } - // @param {Array.|string|Ignore} pattern - add(pattern) { - this._added = false; - if (typeof pattern === "string") { - pattern = pattern.split(/\r?\n/g); - } - make_array(pattern).forEach(this._addPattern, this); - if (this._added) { - this._initCache(); - } - return this; - } - // legacy - addPattern(pattern) { - return this.add(pattern); - } - _addPattern(pattern) { - if (pattern && pattern[KEY_IGNORE]) { - this._rules = this._rules.concat(pattern._rules); - this._added = true; - return; - } - if (this._checkPattern(pattern)) { - const rule = this._createRule(pattern.trim()); - if (rule !== null) { - this._added = true; - this._rules.push(rule); - } - } - } - _checkPattern(pattern) { - return pattern && typeof pattern === "string" && pattern.indexOf("#") !== 0 && pattern.trim() !== ""; - } - filter(paths) { - return make_array(paths).filter((path2) => this._filter(path2)); - } - createFilter() { - return (path2) => this._filter(path2); - } - ignores(path2) { - return !this._filter(path2); - } - // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L41-L53 - // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L29-L55 - _createRule(pattern) { - const origin = pattern; - let negative = false; - if (pattern[0] === "!") { - negative = true; - pattern = pattern.substring(1).trim(); - } - if (pattern.length > 0) { - pattern = cleanPath(pattern); - pattern = toSlash(pattern); - if (pattern.length > 1 && pattern[0] === "/") { - pattern = pattern.slice(1); - } - } - if (negative) { - pattern = "!" + pattern; - } - pattern = pattern.trim(); - if (pattern === "") { - return null; - } - pattern = cleanPath(pattern); - if (pattern[0] === "!") { - if (pattern.length === 1) { - return null; - } - negative = true; - pattern = pattern.substring(1); - } else { - negative = false; - } - return { - origin, - pattern, - // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L54 - dirs: pattern.split(path.sep), - negative - }; - } - // @returns `Boolean` true if the `path` is NOT ignored - _filter(path2) { - if (!path2) { - return false; - } - if (path2 in this._cache) { - return this._cache[path2]; - } - return this._cache[path2] = this._test(path2); - } - // @returns {Boolean} true if a file is NOT ignored - // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L62 - _test(file) { - file = fromSlash(file); - const parentPath = cleanPath(path.dirname(file)); - const parentPathDirs = parentPath.split(path.sep); - let matched = false; - this._rules.forEach((rule) => { - let match = this._match(file, rule); - if (!match && parentPath !== ".") { - if (rule.dirs.includes("**")) { - for (let i = rule.dirs.filter((x) => x !== "**").length; i <= parentPathDirs.length; i++) { - match = match || this._match(parentPathDirs.slice(0, i).join(path.sep), rule); - } - } else if (rule.dirs.length <= parentPathDirs.length) { - match = this._match(parentPathDirs.slice(0, rule.dirs.length).join(path.sep), rule); - } - } - if (match) { - matched = !rule.negative; - } - }); - return !matched; - } - // @returns {Boolean} true if a file is matched by a rule - _match(file, rule) { - return this._compile(rule).regexp.test(file); - } - // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L139 - _compile(rule) { - if (rule.regexp) { - return rule; - } - let regStr = "^"; - let escapedSlash = path.sep === "\\" ? "\\\\" : path.sep; - for (let i = 0; i < rule.pattern.length; i++) { - const ch = rule.pattern[i]; - if (ch === "*") { - if (rule.pattern[i + 1] === "*") { - i++; - if (rule.pattern[i + 1] === path.sep) { - i++; - } - if (rule.pattern[i + 1] === void 0) { - regStr += ".*"; - } else { - regStr += `(.*${escapedSlash})?`; - } - } else { - regStr += `[^${escapedSlash}]*`; - } - } else if (ch === "?") { - regStr += `[^${escapedSlash}]`; - } else if (ch === "." || ch === "$") { - regStr += `\\${ch}`; - } else if (ch === "\\") { - if (path.sep === "\\") { - regStr += escapedSlash; - continue; - } - if (rule.pattern[i + 1] !== void 0) { - regStr += "\\" + rule.pattern[i + 1]; - i++; - } else { - regStr += "\\"; - } - } else { - regStr += ch; - } - } - regStr += "$"; - rule.regexp = new RegExp(regStr, this._ignorecase ? "i" : ""); - return rule; - } - }; - } -}); - -// node_modules/chownr/chownr.js -var require_chownr = __commonJS({ - "node_modules/chownr/chownr.js"(exports2, module2) { - "use strict"; - var fs3 = require("fs"); - var path = require("path"); - var LCHOWN = fs3.lchown ? "lchown" : "chown"; - var LCHOWNSYNC = fs3.lchownSync ? "lchownSync" : "chownSync"; - var needEISDIRHandled = fs3.lchown && !process.version.match(/v1[1-9]+\./) && !process.version.match(/v10\.[6-9]/); - var lchownSync = (path2, uid, gid) => { - try { - return fs3[LCHOWNSYNC](path2, uid, gid); - } catch (er) { - if (er.code !== "ENOENT") - throw er; - } - }; - var chownSync = (path2, uid, gid) => { - try { - return fs3.chownSync(path2, uid, gid); - } catch (er) { - if (er.code !== "ENOENT") - throw er; - } - }; - var handleEISDIR = needEISDIRHandled ? (path2, uid, gid, cb) => (er) => { - if (!er || er.code !== "EISDIR") - cb(er); - else - fs3.chown(path2, uid, gid, cb); - } : (_, __, ___, cb) => cb; - var handleEISDirSync = needEISDIRHandled ? (path2, uid, gid) => { - try { - return lchownSync(path2, uid, gid); - } catch (er) { - if (er.code !== "EISDIR") - throw er; - chownSync(path2, uid, gid); - } - } : (path2, uid, gid) => lchownSync(path2, uid, gid); - var nodeVersion = process.version; - var readdir = (path2, options, cb) => fs3.readdir(path2, options, cb); - var readdirSync = (path2, options) => fs3.readdirSync(path2, options); - if (/^v4\./.test(nodeVersion)) - readdir = (path2, options, cb) => fs3.readdir(path2, cb); - var chown = (cpath, uid, gid, cb) => { - fs3[LCHOWN](cpath, uid, gid, handleEISDIR(cpath, uid, gid, (er) => { - cb(er && er.code !== "ENOENT" ? er : null); - })); - }; - var chownrKid = (p, child, uid, gid, cb) => { - if (typeof child === "string") - return fs3.lstat(path.resolve(p, child), (er, stats) => { - if (er) - return cb(er.code !== "ENOENT" ? er : null); - stats.name = child; - chownrKid(p, stats, uid, gid, cb); - }); - if (child.isDirectory()) { - chownr(path.resolve(p, child.name), uid, gid, (er) => { - if (er) - return cb(er); - const cpath = path.resolve(p, child.name); - chown(cpath, uid, gid, cb); - }); - } else { - const cpath = path.resolve(p, child.name); - chown(cpath, uid, gid, cb); - } - }; - var chownr = (p, uid, gid, cb) => { - readdir(p, { withFileTypes: true }, (er, children) => { - if (er) { - if (er.code === "ENOENT") - return cb(); - else if (er.code !== "ENOTDIR" && er.code !== "ENOTSUP") - return cb(er); - } - if (er || !children.length) - return chown(p, uid, gid, cb); - let len = children.length; - let errState = null; - const then = (er2) => { - if (errState) - return; - if (er2) - return cb(errState = er2); - if (--len === 0) - return chown(p, uid, gid, cb); - }; - children.forEach((child) => chownrKid(p, child, uid, gid, then)); - }); - }; - var chownrKidSync = (p, child, uid, gid) => { - if (typeof child === "string") { - try { - const stats = fs3.lstatSync(path.resolve(p, child)); - stats.name = child; - child = stats; - } catch (er) { - if (er.code === "ENOENT") - return; - else - throw er; - } - } - if (child.isDirectory()) - chownrSync(path.resolve(p, child.name), uid, gid); - handleEISDirSync(path.resolve(p, child.name), uid, gid); - }; - var chownrSync = (p, uid, gid) => { - let children; - try { - children = readdirSync(p, { withFileTypes: true }); - } catch (er) { - if (er.code === "ENOENT") - return; - else if (er.code === "ENOTDIR" || er.code === "ENOTSUP") - return handleEISDirSync(p, uid, gid); - else - throw er; - } - if (children && children.length) - children.forEach((child) => chownrKidSync(p, child, uid, gid)); - return handleEISDirSync(p, uid, gid); - }; - module2.exports = chownr; - chownr.sync = chownrSync; - } -}); - -// node_modules/bl/BufferList.js -var require_BufferList = __commonJS({ - "node_modules/bl/BufferList.js"(exports2, module2) { - "use strict"; - var { Buffer: Buffer2 } = require("buffer"); - var symbol = /* @__PURE__ */ Symbol.for("BufferList"); - function BufferList(buf) { - if (!(this instanceof BufferList)) { - return new BufferList(buf); - } - BufferList._init.call(this, buf); - } - BufferList._init = function _init(buf) { - Object.defineProperty(this, symbol, { value: true }); - this._bufs = []; - this.length = 0; - if (buf) { - this.append(buf); - } - }; - BufferList.prototype._new = function _new(buf) { - return new BufferList(buf); - }; - BufferList.prototype._offset = function _offset(offset) { - if (offset === 0) { - return [0, 0]; - } - let tot = 0; - for (let i = 0; i < this._bufs.length; i++) { - const _t = tot + this._bufs[i].length; - if (offset < _t || i === this._bufs.length - 1) { - return [i, offset - tot]; - } - tot = _t; - } - }; - BufferList.prototype._reverseOffset = function(blOffset) { - const bufferId = blOffset[0]; - let offset = blOffset[1]; - for (let i = 0; i < bufferId; i++) { - offset += this._bufs[i].length; - } - return offset; - }; - BufferList.prototype.get = function get(index) { - if (index > this.length || index < 0) { - return void 0; - } - const offset = this._offset(index); - return this._bufs[offset[0]][offset[1]]; - }; - BufferList.prototype.slice = function slice(start, end) { - if (typeof start === "number" && start < 0) { - start += this.length; - } - if (typeof end === "number" && end < 0) { - end += this.length; - } - return this.copy(null, 0, start, end); - }; - BufferList.prototype.copy = function copy(dst, dstStart, srcStart, srcEnd) { - if (typeof srcStart !== "number" || srcStart < 0) { - srcStart = 0; - } - if (typeof srcEnd !== "number" || srcEnd > this.length) { - srcEnd = this.length; - } - if (srcStart >= this.length) { - return dst || Buffer2.alloc(0); - } - if (srcEnd <= 0) { - return dst || Buffer2.alloc(0); - } - const copy2 = !!dst; - const off = this._offset(srcStart); - const len = srcEnd - srcStart; - let bytes = len; - let bufoff = copy2 && dstStart || 0; - let start = off[1]; - if (srcStart === 0 && srcEnd === this.length) { - if (!copy2) { - return this._bufs.length === 1 ? this._bufs[0] : Buffer2.concat(this._bufs, this.length); - } - for (let i = 0; i < this._bufs.length; i++) { - this._bufs[i].copy(dst, bufoff); - bufoff += this._bufs[i].length; - } - return dst; - } - if (bytes <= this._bufs[off[0]].length - start) { - return copy2 ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes) : this._bufs[off[0]].slice(start, start + bytes); - } - if (!copy2) { - dst = Buffer2.allocUnsafe(len); - } - for (let i = off[0]; i < this._bufs.length; i++) { - const l = this._bufs[i].length - start; - if (bytes > l) { - this._bufs[i].copy(dst, bufoff, start); - bufoff += l; - } else { - this._bufs[i].copy(dst, bufoff, start, start + bytes); - bufoff += l; - break; - } - bytes -= l; - if (start) { - start = 0; - } - } - if (dst.length > bufoff) return dst.slice(0, bufoff); - return dst; - }; - BufferList.prototype.shallowSlice = function shallowSlice(start, end) { - start = start || 0; - end = typeof end !== "number" ? this.length : end; - if (start < 0) { - start += this.length; - } - if (end < 0) { - end += this.length; - } - if (start === end) { - return this._new(); - } - const startOffset = this._offset(start); - const endOffset = this._offset(end); - const buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1); - if (endOffset[1] === 0) { - buffers.pop(); - } else { - buffers[buffers.length - 1] = buffers[buffers.length - 1].slice(0, endOffset[1]); - } - if (startOffset[1] !== 0) { - buffers[0] = buffers[0].slice(startOffset[1]); - } - return this._new(buffers); - }; - BufferList.prototype.toString = function toString(encoding, start, end) { - return this.slice(start, end).toString(encoding); - }; - BufferList.prototype.consume = function consume(bytes) { - bytes = Math.trunc(bytes); - if (Number.isNaN(bytes) || bytes <= 0) return this; - while (this._bufs.length) { - if (bytes >= this._bufs[0].length) { - bytes -= this._bufs[0].length; - this.length -= this._bufs[0].length; - this._bufs.shift(); - } else { - this._bufs[0] = this._bufs[0].slice(bytes); - this.length -= bytes; - break; - } - } - return this; - }; - BufferList.prototype.duplicate = function duplicate() { - const copy = this._new(); - for (let i = 0; i < this._bufs.length; i++) { - copy.append(this._bufs[i]); - } - return copy; - }; - BufferList.prototype.append = function append(buf) { - if (buf == null) { - return this; - } - if (buf.buffer) { - this._appendBuffer(Buffer2.from(buf.buffer, buf.byteOffset, buf.byteLength)); - } else if (Array.isArray(buf)) { - for (let i = 0; i < buf.length; i++) { - this.append(buf[i]); - } - } else if (this._isBufferList(buf)) { - for (let i = 0; i < buf._bufs.length; i++) { - this.append(buf._bufs[i]); - } - } else { - if (typeof buf === "number") { - buf = buf.toString(); - } - this._appendBuffer(Buffer2.from(buf)); - } - return this; - }; - BufferList.prototype._appendBuffer = function appendBuffer(buf) { - this._bufs.push(buf); - this.length += buf.length; - }; - BufferList.prototype.indexOf = function(search, offset, encoding) { - if (encoding === void 0 && typeof offset === "string") { - encoding = offset; - offset = void 0; - } - if (typeof search === "function" || Array.isArray(search)) { - throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.'); - } else if (typeof search === "number") { - search = Buffer2.from([search]); - } else if (typeof search === "string") { - search = Buffer2.from(search, encoding); - } else if (this._isBufferList(search)) { - search = search.slice(); - } else if (Array.isArray(search.buffer)) { - search = Buffer2.from(search.buffer, search.byteOffset, search.byteLength); - } else if (!Buffer2.isBuffer(search)) { - search = Buffer2.from(search); - } - offset = Number(offset || 0); - if (isNaN(offset)) { - offset = 0; - } - if (offset < 0) { - offset = this.length + offset; - } - if (offset < 0) { - offset = 0; - } - if (search.length === 0) { - return offset > this.length ? this.length : offset; - } - const blOffset = this._offset(offset); - let blIndex = blOffset[0]; - let buffOffset = blOffset[1]; - for (; blIndex < this._bufs.length; blIndex++) { - const buff = this._bufs[blIndex]; - while (buffOffset < buff.length) { - const availableWindow = buff.length - buffOffset; - if (availableWindow >= search.length) { - const nativeSearchResult = buff.indexOf(search, buffOffset); - if (nativeSearchResult !== -1) { - return this._reverseOffset([blIndex, nativeSearchResult]); - } - buffOffset = buff.length - search.length + 1; - } else { - const revOffset = this._reverseOffset([blIndex, buffOffset]); - if (this._match(revOffset, search)) { - return revOffset; - } - buffOffset++; - } - } - buffOffset = 0; - } - return -1; - }; - BufferList.prototype._match = function(offset, search) { - if (this.length - offset < search.length) { - return false; - } - for (let searchOffset = 0; searchOffset < search.length; searchOffset++) { - if (this.get(offset + searchOffset) !== search[searchOffset]) { - return false; - } - } - return true; - }; - (function() { - const methods = { - readDoubleBE: 8, - readDoubleLE: 8, - readFloatBE: 4, - readFloatLE: 4, - readInt32BE: 4, - readInt32LE: 4, - readUInt32BE: 4, - readUInt32LE: 4, - readInt16BE: 2, - readInt16LE: 2, - readUInt16BE: 2, - readUInt16LE: 2, - readInt8: 1, - readUInt8: 1, - readIntBE: null, - readIntLE: null, - readUIntBE: null, - readUIntLE: null - }; - for (const m in methods) { - (function(m2) { - if (methods[m2] === null) { - BufferList.prototype[m2] = function(offset, byteLength) { - return this.slice(offset, offset + byteLength)[m2](0, byteLength); - }; - } else { - BufferList.prototype[m2] = function(offset = 0) { - return this.slice(offset, offset + methods[m2])[m2](0); - }; - } - })(m); - } - })(); - BufferList.prototype._isBufferList = function _isBufferList(b) { - return b instanceof BufferList || BufferList.isBufferList(b); - }; - BufferList.isBufferList = function isBufferList(b) { - return b != null && b[symbol]; - }; - module2.exports = BufferList; - } -}); - -// node_modules/bl/bl.js -var require_bl = __commonJS({ - "node_modules/bl/bl.js"(exports2, module2) { - "use strict"; - var DuplexStream = require_readable2().Duplex; - var inherits = require_inherits(); - var BufferList = require_BufferList(); - function BufferListStream(callback) { - if (!(this instanceof BufferListStream)) { - return new BufferListStream(callback); - } - if (typeof callback === "function") { - this._callback = callback; - const piper = function piper2(err) { - if (this._callback) { - this._callback(err); - this._callback = null; - } - }.bind(this); - this.on("pipe", function onPipe(src) { - src.on("error", piper); - }); - this.on("unpipe", function onUnpipe(src) { - src.removeListener("error", piper); - }); - callback = null; - } - BufferList._init.call(this, callback); - DuplexStream.call(this); - } - inherits(BufferListStream, DuplexStream); - Object.assign(BufferListStream.prototype, BufferList.prototype); - BufferListStream.prototype._new = function _new(callback) { - return new BufferListStream(callback); - }; - BufferListStream.prototype._write = function _write(buf, encoding, callback) { - this._appendBuffer(buf); - if (typeof callback === "function") { - callback(); - } - }; - BufferListStream.prototype._read = function _read(size) { - if (!this.length) { - return this.push(null); - } - size = Math.min(size, this.length); - this.push(this.slice(0, size)); - this.consume(size); - }; - BufferListStream.prototype.end = function end(chunk) { - DuplexStream.prototype.end.call(this, chunk); - if (this._callback) { - this._callback(null, this.slice()); - this._callback = null; - } - }; - BufferListStream.prototype._destroy = function _destroy(err, cb) { - this._bufs.length = 0; - this.length = 0; - cb(err); - }; - BufferListStream.prototype._isBufferList = function _isBufferList(b) { - return b instanceof BufferListStream || b instanceof BufferList || BufferListStream.isBufferList(b); - }; - BufferListStream.isBufferList = BufferList.isBufferList; - module2.exports = BufferListStream; - module2.exports.BufferListStream = BufferListStream; - module2.exports.BufferList = BufferList; - } -}); - -// node_modules/tar-fs/node_modules/tar-stream/headers.js -var require_headers2 = __commonJS({ - "node_modules/tar-fs/node_modules/tar-stream/headers.js"(exports2) { - var alloc = Buffer.alloc; - var ZEROS = "0000000000000000000"; - var SEVENS = "7777777777777777777"; - var ZERO_OFFSET = "0".charCodeAt(0); - var USTAR_MAGIC = Buffer.from("ustar\0", "binary"); - var USTAR_VER = Buffer.from("00", "binary"); - var GNU_MAGIC = Buffer.from("ustar ", "binary"); - var GNU_VER = Buffer.from(" \0", "binary"); - var MASK = parseInt("7777", 8); - var MAGIC_OFFSET = 257; - var VERSION_OFFSET = 263; - var clamp = function(index, len, defaultValue) { - if (typeof index !== "number") return defaultValue; - index = ~~index; - if (index >= len) return len; - if (index >= 0) return index; - index += len; - if (index >= 0) return index; - return 0; - }; - var toType = function(flag) { - switch (flag) { - case 0: - return "file"; - case 1: - return "link"; - case 2: - return "symlink"; - case 3: - return "character-device"; - case 4: - return "block-device"; - case 5: - return "directory"; - case 6: - return "fifo"; - case 7: - return "contiguous-file"; - case 72: - return "pax-header"; - case 55: - return "pax-global-header"; - case 27: - return "gnu-long-link-path"; - case 28: - case 30: - return "gnu-long-path"; - } - return null; - }; - var toTypeflag = function(flag) { - switch (flag) { - case "file": - return 0; - case "link": - return 1; - case "symlink": - return 2; - case "character-device": - return 3; - case "block-device": - return 4; - case "directory": - return 5; - case "fifo": - return 6; - case "contiguous-file": - return 7; - case "pax-header": - return 72; - } - return 0; - }; - var indexOf = function(block, num, offset, end) { - for (; offset < end; offset++) { - if (block[offset] === num) return offset; - } - return end; - }; - var cksum = function(block) { - var sum = 8 * 32; - for (var i = 0; i < 148; i++) sum += block[i]; - for (var j = 156; j < 512; j++) sum += block[j]; - return sum; - }; - var encodeOct = function(val, n) { - val = val.toString(8); - if (val.length > n) return SEVENS.slice(0, n) + " "; - else return ZEROS.slice(0, n - val.length) + val + " "; - }; - function parse256(buf) { - var positive; - if (buf[0] === 128) positive = true; - else if (buf[0] === 255) positive = false; - else return null; - var tuple = []; - for (var i = buf.length - 1; i > 0; i--) { - var byte = buf[i]; - if (positive) tuple.push(byte); - else tuple.push(255 - byte); - } - var sum = 0; - var l = tuple.length; - for (i = 0; i < l; i++) { - sum += tuple[i] * Math.pow(256, i); - } - return positive ? sum : -1 * sum; - } - var decodeOct = function(val, offset, length) { - val = val.slice(offset, offset + length); - offset = 0; - if (val[offset] & 128) { - return parse256(val); - } else { - while (offset < val.length && val[offset] === 32) offset++; - var end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length); - while (offset < end && val[offset] === 0) offset++; - if (end === offset) return 0; - return parseInt(val.slice(offset, end).toString(), 8); - } - }; - var decodeStr = function(val, offset, length, encoding) { - return val.slice(offset, indexOf(val, 0, offset, offset + length)).toString(encoding); - }; - var addLength = function(str) { - var len = Buffer.byteLength(str); - var digits = Math.floor(Math.log(len) / Math.log(10)) + 1; - if (len + digits >= Math.pow(10, digits)) digits++; - return len + digits + str; - }; - exports2.decodeLongPath = function(buf, encoding) { - return decodeStr(buf, 0, buf.length, encoding); - }; - exports2.encodePax = function(opts) { - var result = ""; - if (opts.name) result += addLength(" path=" + opts.name + "\n"); - if (opts.linkname) result += addLength(" linkpath=" + opts.linkname + "\n"); - var pax = opts.pax; - if (pax) { - for (var key in pax) { - result += addLength(" " + key + "=" + pax[key] + "\n"); - } - } - return Buffer.from(result); - }; - exports2.decodePax = function(buf) { - var result = {}; - while (buf.length) { - var i = 0; - while (i < buf.length && buf[i] !== 32) i++; - var len = parseInt(buf.slice(0, i).toString(), 10); - if (!len) return result; - var b = buf.slice(i + 1, len - 1).toString(); - var keyIndex = b.indexOf("="); - if (keyIndex === -1) return result; - result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1); - buf = buf.slice(len); - } - return result; - }; - exports2.encode = function(opts) { - var buf = alloc(512); - var name = opts.name; - var prefix = ""; - if (opts.typeflag === 5 && name[name.length - 1] !== "/") name += "/"; - if (Buffer.byteLength(name) !== name.length) return null; - while (Buffer.byteLength(name) > 100) { - var i = name.indexOf("/"); - if (i === -1) return null; - prefix += prefix ? "/" + name.slice(0, i) : name.slice(0, i); - name = name.slice(i + 1); - } - if (Buffer.byteLength(name) > 100 || Buffer.byteLength(prefix) > 155) return null; - if (opts.linkname && Buffer.byteLength(opts.linkname) > 100) return null; - buf.write(name); - buf.write(encodeOct(opts.mode & MASK, 6), 100); - buf.write(encodeOct(opts.uid, 6), 108); - buf.write(encodeOct(opts.gid, 6), 116); - buf.write(encodeOct(opts.size, 11), 124); - buf.write(encodeOct(opts.mtime.getTime() / 1e3 | 0, 11), 136); - buf[156] = ZERO_OFFSET + toTypeflag(opts.type); - if (opts.linkname) buf.write(opts.linkname, 157); - USTAR_MAGIC.copy(buf, MAGIC_OFFSET); - USTAR_VER.copy(buf, VERSION_OFFSET); - if (opts.uname) buf.write(opts.uname, 265); - if (opts.gname) buf.write(opts.gname, 297); - buf.write(encodeOct(opts.devmajor || 0, 6), 329); - buf.write(encodeOct(opts.devminor || 0, 6), 337); - if (prefix) buf.write(prefix, 345); - buf.write(encodeOct(cksum(buf), 6), 148); - return buf; - }; - exports2.decode = function(buf, filenameEncoding, allowUnknownFormat) { - var typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET; - var name = decodeStr(buf, 0, 100, filenameEncoding); - var mode = decodeOct(buf, 100, 8); - var uid = decodeOct(buf, 108, 8); - var gid = decodeOct(buf, 116, 8); - var size = decodeOct(buf, 124, 12); - var mtime = decodeOct(buf, 136, 12); - var type = toType(typeflag); - var linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100, filenameEncoding); - var uname = decodeStr(buf, 265, 32); - var gname = decodeStr(buf, 297, 32); - var devmajor = decodeOct(buf, 329, 8); - var devminor = decodeOct(buf, 337, 8); - var c = cksum(buf); - if (c === 8 * 32) return null; - if (c !== decodeOct(buf, 148, 8)) throw new Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?"); - if (USTAR_MAGIC.compare(buf, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0) { - if (buf[345]) name = decodeStr(buf, 345, 155, filenameEncoding) + "/" + name; - } else if (GNU_MAGIC.compare(buf, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0 && GNU_VER.compare(buf, VERSION_OFFSET, VERSION_OFFSET + 2) === 0) { - } else { - if (!allowUnknownFormat) { - throw new Error("Invalid tar header: unknown format."); - } - } - if (typeflag === 0 && name && name[name.length - 1] === "/") typeflag = 5; - return { - name, - mode, - uid, - gid, - size, - mtime: new Date(1e3 * mtime), - type, - linkname, - uname, - gname, - devmajor, - devminor - }; - }; - } -}); - -// node_modules/tar-fs/node_modules/tar-stream/extract.js -var require_extract = __commonJS({ - "node_modules/tar-fs/node_modules/tar-stream/extract.js"(exports2, module2) { - var util = require("util"); - var bl = require_bl(); - var headers = require_headers2(); - var Writable2 = require_readable2().Writable; - var PassThrough = require_readable2().PassThrough; - var noop3 = function() { - }; - var overflow = function(size) { - size &= 511; - return size && 512 - size; - }; - var emptyStream = function(self2, offset) { - var s = new Source(self2, offset); - s.end(); - return s; - }; - var mixinPax = function(header, pax) { - if (pax.path) header.name = pax.path; - if (pax.linkpath) header.linkname = pax.linkpath; - if (pax.size) header.size = parseInt(pax.size, 10); - header.pax = pax; - return header; - }; - var Source = function(self2, offset) { - this._parent = self2; - this.offset = offset; - PassThrough.call(this, { autoDestroy: false }); - }; - util.inherits(Source, PassThrough); - Source.prototype.destroy = function(err) { - this._parent.destroy(err); - }; - var Extract = function(opts) { - if (!(this instanceof Extract)) return new Extract(opts); - Writable2.call(this, opts); - opts = opts || {}; - this._offset = 0; - this._buffer = bl(); - this._missing = 0; - this._partial = false; - this._onparse = noop3; - this._header = null; - this._stream = null; - this._overflow = null; - this._cb = null; - this._locked = false; - this._destroyed = false; - this._pax = null; - this._paxGlobal = null; - this._gnuLongPath = null; - this._gnuLongLinkPath = null; - var self2 = this; - var b = self2._buffer; - var oncontinue = function() { - self2._continue(); - }; - var onunlock = function(err) { - self2._locked = false; - if (err) return self2.destroy(err); - if (!self2._stream) oncontinue(); - }; - var onstreamend = function() { - self2._stream = null; - var drain = overflow(self2._header.size); - if (drain) self2._parse(drain, ondrain); - else self2._parse(512, onheader); - if (!self2._locked) oncontinue(); - }; - var ondrain = function() { - self2._buffer.consume(overflow(self2._header.size)); - self2._parse(512, onheader); - oncontinue(); - }; - var onpaxglobalheader = function() { - var size = self2._header.size; - self2._paxGlobal = headers.decodePax(b.slice(0, size)); - b.consume(size); - onstreamend(); - }; - var onpaxheader = function() { - var size = self2._header.size; - self2._pax = headers.decodePax(b.slice(0, size)); - if (self2._paxGlobal) self2._pax = Object.assign({}, self2._paxGlobal, self2._pax); - b.consume(size); - onstreamend(); - }; - var ongnulongpath = function() { - var size = self2._header.size; - this._gnuLongPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding); - b.consume(size); - onstreamend(); - }; - var ongnulonglinkpath = function() { - var size = self2._header.size; - this._gnuLongLinkPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding); - b.consume(size); - onstreamend(); - }; - var onheader = function() { - var offset = self2._offset; - var header; - try { - header = self2._header = headers.decode(b.slice(0, 512), opts.filenameEncoding, opts.allowUnknownFormat); - } catch (err) { - self2.emit("error", err); - } - b.consume(512); - if (!header) { - self2._parse(512, onheader); - oncontinue(); - return; - } - if (header.type === "gnu-long-path") { - self2._parse(header.size, ongnulongpath); - oncontinue(); - return; - } - if (header.type === "gnu-long-link-path") { - self2._parse(header.size, ongnulonglinkpath); - oncontinue(); - return; - } - if (header.type === "pax-global-header") { - self2._parse(header.size, onpaxglobalheader); - oncontinue(); - return; - } - if (header.type === "pax-header") { - self2._parse(header.size, onpaxheader); - oncontinue(); - return; - } - if (self2._gnuLongPath) { - header.name = self2._gnuLongPath; - self2._gnuLongPath = null; - } - if (self2._gnuLongLinkPath) { - header.linkname = self2._gnuLongLinkPath; - self2._gnuLongLinkPath = null; - } - if (self2._pax) { - self2._header = header = mixinPax(header, self2._pax); - self2._pax = null; - } - self2._locked = true; - if (!header.size || header.type === "directory") { - self2._parse(512, onheader); - self2.emit("entry", header, emptyStream(self2, offset), onunlock); - return; - } - self2._stream = new Source(self2, offset); - self2.emit("entry", header, self2._stream, onunlock); - self2._parse(header.size, onstreamend); - oncontinue(); - }; - this._onheader = onheader; - this._parse(512, onheader); - }; - util.inherits(Extract, Writable2); - Extract.prototype.destroy = function(err) { - if (this._destroyed) return; - this._destroyed = true; - if (err) this.emit("error", err); - this.emit("close"); - if (this._stream) this._stream.emit("close"); - }; - Extract.prototype._parse = function(size, onparse) { - if (this._destroyed) return; - this._offset += size; - this._missing = size; - if (onparse === this._onheader) this._partial = false; - this._onparse = onparse; - }; - Extract.prototype._continue = function() { - if (this._destroyed) return; - var cb = this._cb; - this._cb = noop3; - if (this._overflow) this._write(this._overflow, void 0, cb); - else cb(); - }; - Extract.prototype._write = function(data, enc, cb) { - if (this._destroyed) return; - var s = this._stream; - var b = this._buffer; - var missing = this._missing; - if (data.length) this._partial = true; - if (data.length < missing) { - this._missing -= data.length; - this._overflow = null; - if (s) return s.write(data, cb); - b.append(data); - return cb(); - } - this._cb = cb; - this._missing = 0; - var overflow2 = null; - if (data.length > missing) { - overflow2 = data.slice(missing); - data = data.slice(0, missing); - } - if (s) s.end(data); - else b.append(data); - this._overflow = overflow2; - this._onparse(); - }; - Extract.prototype._final = function(cb) { - if (this._partial) return this.destroy(new Error("Unexpected end of data")); - cb(); - }; - module2.exports = Extract; - } -}); - -// node_modules/fs-constants/index.js -var require_fs_constants = __commonJS({ - "node_modules/fs-constants/index.js"(exports2, module2) { - module2.exports = require("fs").constants || require("constants"); - } -}); - -// node_modules/wrappy/wrappy.js -var require_wrappy = __commonJS({ - "node_modules/wrappy/wrappy.js"(exports2, module2) { - module2.exports = wrappy; - function wrappy(fn, cb) { - if (fn && cb) return wrappy(fn)(cb); - if (typeof fn !== "function") - throw new TypeError("need wrapper function"); - Object.keys(fn).forEach(function(k) { - wrapper[k] = fn[k]; - }); - return wrapper; - function wrapper() { - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; - } - var ret = fn.apply(this, args); - var cb2 = args[args.length - 1]; - if (typeof ret === "function" && ret !== cb2) { - Object.keys(cb2).forEach(function(k) { - ret[k] = cb2[k]; - }); - } - return ret; - } - } - } -}); - -// node_modules/once/once.js -var require_once = __commonJS({ - "node_modules/once/once.js"(exports2, module2) { - var wrappy = require_wrappy(); - module2.exports = wrappy(once); - module2.exports.strict = wrappy(onceStrict); - once.proto = once(function() { - Object.defineProperty(Function.prototype, "once", { - value: function() { - return once(this); - }, - configurable: true - }); - Object.defineProperty(Function.prototype, "onceStrict", { - value: function() { - return onceStrict(this); - }, - configurable: true - }); - }); - function once(fn) { - var f = function() { - if (f.called) return f.value; - f.called = true; - return f.value = fn.apply(this, arguments); - }; - f.called = false; - return f; - } - function onceStrict(fn) { - var f = function() { - if (f.called) - throw new Error(f.onceError); - f.called = true; - return f.value = fn.apply(this, arguments); - }; - var name = fn.name || "Function wrapped with `once`"; - f.onceError = name + " shouldn't be called more than once"; - f.called = false; - return f; - } - } -}); - -// node_modules/end-of-stream/index.js -var require_end_of_stream2 = __commonJS({ - "node_modules/end-of-stream/index.js"(exports2, module2) { - var once = require_once(); - var noop3 = function() { - }; - var qnt = global.Bare ? queueMicrotask : process.nextTick.bind(process); - var isRequest = function(stream2) { - return stream2.setHeader && typeof stream2.abort === "function"; - }; - var isChildProcess = function(stream2) { - return stream2.stdio && Array.isArray(stream2.stdio) && stream2.stdio.length === 3; - }; - var eos = function(stream2, opts, callback) { - if (typeof opts === "function") return eos(stream2, null, opts); - if (!opts) opts = {}; - callback = once(callback || noop3); - var ws = stream2._writableState; - var rs = stream2._readableState; - var readable = opts.readable || opts.readable !== false && stream2.readable; - var writable = opts.writable || opts.writable !== false && stream2.writable; - var cancelled = false; - var onlegacyfinish = function() { - if (!stream2.writable) onfinish(); - }; - var onfinish = function() { - writable = false; - if (!readable) callback.call(stream2); - }; - var onend = function() { - readable = false; - if (!writable) callback.call(stream2); - }; - var onexit = function(exitCode) { - callback.call(stream2, exitCode ? new Error("exited with error code: " + exitCode) : null); - }; - var onerror = function(err) { - callback.call(stream2, err); - }; - var onclose = function() { - qnt(onclosenexttick); - }; - var onclosenexttick = function() { - if (cancelled) return; - if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream2, new Error("premature close")); - if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream2, new Error("premature close")); - }; - var onrequest = function() { - stream2.req.on("finish", onfinish); - }; - if (isRequest(stream2)) { - stream2.on("complete", onfinish); - stream2.on("abort", onclose); - if (stream2.req) onrequest(); - else stream2.on("request", onrequest); - } else if (writable && !ws) { - stream2.on("end", onlegacyfinish); - stream2.on("close", onlegacyfinish); - } - if (isChildProcess(stream2)) stream2.on("exit", onexit); - stream2.on("end", onend); - stream2.on("finish", onfinish); - if (opts.error !== false) stream2.on("error", onerror); - stream2.on("close", onclose); - return function() { - cancelled = true; - stream2.removeListener("complete", onfinish); - stream2.removeListener("abort", onclose); - stream2.removeListener("request", onrequest); - if (stream2.req) stream2.req.removeListener("finish", onfinish); - stream2.removeListener("end", onlegacyfinish); - stream2.removeListener("close", onlegacyfinish); - stream2.removeListener("finish", onfinish); - stream2.removeListener("exit", onexit); - stream2.removeListener("end", onend); - stream2.removeListener("error", onerror); - stream2.removeListener("close", onclose); - }; - }; - module2.exports = eos; - } -}); - -// node_modules/tar-fs/node_modules/tar-stream/pack.js -var require_pack = __commonJS({ - "node_modules/tar-fs/node_modules/tar-stream/pack.js"(exports2, module2) { - var constants = require_fs_constants(); - var eos = require_end_of_stream2(); - var inherits = require_inherits(); - var alloc = Buffer.alloc; - var Readable2 = require_readable2().Readable; - var Writable2 = require_readable2().Writable; - var StringDecoder = require("string_decoder").StringDecoder; - var headers = require_headers2(); - var DMODE = parseInt("755", 8); - var FMODE = parseInt("644", 8); - var END_OF_TAR = alloc(1024); - var noop3 = function() { - }; - var overflow = function(self2, size) { - size &= 511; - if (size) self2.push(END_OF_TAR.slice(0, 512 - size)); - }; - function modeToType(mode) { - switch (mode & constants.S_IFMT) { - case constants.S_IFBLK: - return "block-device"; - case constants.S_IFCHR: - return "character-device"; - case constants.S_IFDIR: - return "directory"; - case constants.S_IFIFO: - return "fifo"; - case constants.S_IFLNK: - return "symlink"; - } - return "file"; - } - var Sink = function(to) { - Writable2.call(this); - this.written = 0; - this._to = to; - this._destroyed = false; - }; - inherits(Sink, Writable2); - Sink.prototype._write = function(data, enc, cb) { - this.written += data.length; - if (this._to.push(data)) return cb(); - this._to._drain = cb; - }; - Sink.prototype.destroy = function() { - if (this._destroyed) return; - this._destroyed = true; - this.emit("close"); - }; - var LinkSink = function() { - Writable2.call(this); - this.linkname = ""; - this._decoder = new StringDecoder("utf-8"); - this._destroyed = false; - }; - inherits(LinkSink, Writable2); - LinkSink.prototype._write = function(data, enc, cb) { - this.linkname += this._decoder.write(data); - cb(); - }; - LinkSink.prototype.destroy = function() { - if (this._destroyed) return; - this._destroyed = true; - this.emit("close"); - }; - var Void = function() { - Writable2.call(this); - this._destroyed = false; - }; - inherits(Void, Writable2); - Void.prototype._write = function(data, enc, cb) { - cb(new Error("No body allowed for this entry")); - }; - Void.prototype.destroy = function() { - if (this._destroyed) return; - this._destroyed = true; - this.emit("close"); - }; - var Pack = function(opts) { - if (!(this instanceof Pack)) return new Pack(opts); - Readable2.call(this, opts); - this._drain = noop3; - this._finalized = false; - this._finalizing = false; - this._destroyed = false; - this._stream = null; - }; - inherits(Pack, Readable2); - Pack.prototype.entry = function(header, buffer, callback) { - if (this._stream) throw new Error("already piping an entry"); - if (this._finalized || this._destroyed) return; - if (typeof buffer === "function") { - callback = buffer; - buffer = null; - } - if (!callback) callback = noop3; - var self2 = this; - if (!header.size || header.type === "symlink") header.size = 0; - if (!header.type) header.type = modeToType(header.mode); - if (!header.mode) header.mode = header.type === "directory" ? DMODE : FMODE; - if (!header.uid) header.uid = 0; - if (!header.gid) header.gid = 0; - if (!header.mtime) header.mtime = /* @__PURE__ */ new Date(); - if (typeof buffer === "string") buffer = Buffer.from(buffer); - if (Buffer.isBuffer(buffer)) { - header.size = buffer.length; - this._encode(header); - var ok = this.push(buffer); - overflow(self2, header.size); - if (ok) process.nextTick(callback); - else this._drain = callback; - return new Void(); - } - if (header.type === "symlink" && !header.linkname) { - var linkSink = new LinkSink(); - eos(linkSink, function(err) { - if (err) { - self2.destroy(); - return callback(err); - } - header.linkname = linkSink.linkname; - self2._encode(header); - callback(); - }); - return linkSink; - } - this._encode(header); - if (header.type !== "file" && header.type !== "contiguous-file") { - process.nextTick(callback); - return new Void(); - } - var sink = new Sink(this); - this._stream = sink; - eos(sink, function(err) { - self2._stream = null; - if (err) { - self2.destroy(); - return callback(err); - } - if (sink.written !== header.size) { - self2.destroy(); - return callback(new Error("size mismatch")); - } - overflow(self2, header.size); - if (self2._finalizing) self2.finalize(); - callback(); - }); - return sink; - }; - Pack.prototype.finalize = function() { - if (this._stream) { - this._finalizing = true; - return; - } - if (this._finalized) return; - this._finalized = true; - this.push(END_OF_TAR); - this.push(null); - }; - Pack.prototype.destroy = function(err) { - if (this._destroyed) return; - this._destroyed = true; - if (err) this.emit("error", err); - this.emit("close"); - if (this._stream && this._stream.destroy) this._stream.destroy(); - }; - Pack.prototype._encode = function(header) { - if (!header.pax) { - var buf = headers.encode(header); - if (buf) { - this.push(buf); - return; - } - } - this._encodePax(header); - }; - Pack.prototype._encodePax = function(header) { - var paxHeader = headers.encodePax({ - name: header.name, - linkname: header.linkname, - pax: header.pax - }); - var newHeader = { - name: "PaxHeader", - mode: header.mode, - uid: header.uid, - gid: header.gid, - size: paxHeader.length, - mtime: header.mtime, - type: "pax-header", - linkname: header.linkname && "PaxHeader", - uname: header.uname, - gname: header.gname, - devmajor: header.devmajor, - devminor: header.devminor - }; - this.push(headers.encode(newHeader)); - this.push(paxHeader); - overflow(this, paxHeader.length); - newHeader.size = header.size; - newHeader.type = header.type; - this.push(headers.encode(newHeader)); - }; - Pack.prototype._read = function(n) { - var drain = this._drain; - this._drain = noop3; - drain(); - }; - module2.exports = Pack; - } -}); - -// node_modules/tar-fs/node_modules/tar-stream/index.js -var require_tar_stream = __commonJS({ - "node_modules/tar-fs/node_modules/tar-stream/index.js"(exports2) { - exports2.extract = require_extract(); - exports2.pack = require_pack(); - } -}); - -// node_modules/pump/index.js -var require_pump = __commonJS({ - "node_modules/pump/index.js"(exports2, module2) { - var once = require_once(); - var eos = require_end_of_stream2(); - var fs3; - try { - fs3 = require("fs"); - } catch (e) { - } - var noop3 = function() { - }; - var ancient = typeof process === "undefined" ? false : /^v?\.0/.test(process.version); - var isFn = function(fn) { - return typeof fn === "function"; - }; - var isFS = function(stream2) { - if (!ancient) return false; - if (!fs3) return false; - return (stream2 instanceof (fs3.ReadStream || noop3) || stream2 instanceof (fs3.WriteStream || noop3)) && isFn(stream2.close); - }; - var isRequest = function(stream2) { - return stream2.setHeader && isFn(stream2.abort); - }; - var destroyer = function(stream2, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream2.on("close", function() { - closed = true; - }); - eos(stream2, { 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 (isFS(stream2)) return stream2.close(noop3); - if (isRequest(stream2)) return stream2.abort(); - if (isFn(stream2.destroy)) return stream2.destroy(); - callback(err || new Error("stream was destroyed")); - }; - }; - var call = function(fn) { - fn(); - }; - var pipe = function(from, to) { - return from.pipe(to); - }; - var pump = function() { - var streams = Array.prototype.slice.call(arguments); - var callback = isFn(streams[streams.length - 1] || noop3) && streams.pop() || noop3; - if (Array.isArray(streams[0])) streams = streams[0]; - if (streams.length < 2) throw new Error("pump requires two streams per minimum"); - var error3; - var destroys = streams.map(function(stream2, i) { - var reading = i < streams.length - 1; - var writing = i > 0; - return destroyer(stream2, reading, writing, function(err) { - if (!error3) error3 = err; - if (err) destroys.forEach(call); - if (reading) return; - destroys.forEach(call); - callback(error3); - }); - }); - return streams.reduce(pipe); - }; - module2.exports = pump; - } -}); - -// node_modules/mkdirp-classic/index.js -var require_mkdirp_classic = __commonJS({ - "node_modules/mkdirp-classic/index.js"(exports2, module2) { - var path = require("path"); - var fs3 = require("fs"); - var _0777 = parseInt("0777", 8); - module2.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; - function mkdirP(p, opts, f, made) { - if (typeof opts === "function") { - f = opts; - opts = {}; - } else if (!opts || typeof opts !== "object") { - opts = { mode: opts }; - } - var mode = opts.mode; - var xfs = opts.fs || fs3; - if (mode === void 0) { - mode = _0777 & ~process.umask(); - } - if (!made) made = null; - var cb = f || function() { - }; - p = path.resolve(p); - xfs.mkdir(p, mode, function(er) { - if (!er) { - made = made || p; - return cb(null, made); - } - switch (er.code) { - case "ENOENT": - mkdirP(path.dirname(p), opts, function(er2, made2) { - if (er2) cb(er2, made2); - else mkdirP(p, opts, cb, made2); - }); - break; - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - xfs.stat(p, function(er2, stat) { - if (er2 || !stat.isDirectory()) cb(er, made); - else cb(null, made); - }); - break; - } - }); - } - mkdirP.sync = function sync(p, opts, made) { - if (!opts || typeof opts !== "object") { - opts = { mode: opts }; - } - var mode = opts.mode; - var xfs = opts.fs || fs3; - if (mode === void 0) { - mode = _0777 & ~process.umask(); - } - if (!made) made = null; - p = path.resolve(p); - try { - xfs.mkdirSync(p, mode); - made = made || p; - } catch (err0) { - switch (err0.code) { - case "ENOENT": - made = sync(path.dirname(p), opts, made); - sync(p, opts, made); - break; - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - var stat; - try { - stat = xfs.statSync(p); - } catch (err1) { - throw err0; - } - if (!stat.isDirectory()) throw err0; - break; - } - } - return made; - }; - } -}); - -// node_modules/tar-fs/index.js -var require_tar_fs = __commonJS({ - "node_modules/tar-fs/index.js"(exports2) { - var chownr = require_chownr(); - var tar = require_tar_stream(); - var pump = require_pump(); - var mkdirp = require_mkdirp_classic(); - var fs3 = require("fs"); - var path = require("path"); - var os = require("os"); - var win32 = os.platform() === "win32"; - var noop3 = function() { - }; - var echo = function(name) { - return name; - }; - var normalize = !win32 ? echo : function(name) { - return name.replace(/\\/g, "/").replace(/[:?<>|]/g, "_"); - }; - var statAll = function(fs4, stat, cwd, ignore, entries, sort) { - var queue = entries || ["."]; - return function loop(callback) { - if (!queue.length) return callback(); - var next = queue.shift(); - var nextAbs = path.join(cwd, next); - stat.call(fs4, nextAbs, function(err, stat2) { - if (err) return callback(err); - if (!stat2.isDirectory()) return callback(null, next, stat2); - fs4.readdir(nextAbs, function(err2, files) { - if (err2) return callback(err2); - if (sort) files.sort(); - for (var i = 0; i < files.length; i++) { - if (!ignore(path.join(cwd, next, files[i]))) queue.push(path.join(next, files[i])); - } - callback(null, next, stat2); - }); - }); - }; - }; - var strip = function(map, level) { - return function(header) { - header.name = header.name.split("/").slice(level).join("/"); - var linkname = header.linkname; - if (linkname && (header.type === "link" || path.isAbsolute(linkname))) { - header.linkname = linkname.split("/").slice(level).join("/"); - } - return map(header); - }; - }; - exports2.pack = function(cwd, opts) { - if (!cwd) cwd = "."; - if (!opts) opts = {}; - var xfs = opts.fs || fs3; - var ignore = opts.ignore || opts.filter || noop3; - var map = opts.map || noop3; - var mapStream = opts.mapStream || echo; - var statNext = statAll(xfs, opts.dereference ? xfs.stat : xfs.lstat, cwd, ignore, opts.entries, opts.sort); - var strict = opts.strict !== false; - var umask = typeof opts.umask === "number" ? ~opts.umask : ~processUmask(); - var dmode = typeof opts.dmode === "number" ? opts.dmode : 0; - var fmode = typeof opts.fmode === "number" ? opts.fmode : 0; - var pack2 = opts.pack || tar.pack(); - var finish = opts.finish || noop3; - if (opts.strip) map = strip(map, opts.strip); - if (opts.readable) { - dmode |= parseInt(555, 8); - fmode |= parseInt(444, 8); - } - if (opts.writable) { - dmode |= parseInt(333, 8); - fmode |= parseInt(222, 8); - } - var onsymlink = function(filename, header) { - xfs.readlink(path.join(cwd, filename), function(err, linkname) { - if (err) return pack2.destroy(err); - header.linkname = normalize(linkname); - pack2.entry(header, onnextentry); - }); - }; - var onstat = function(err, filename, stat) { - if (err) return pack2.destroy(err); - if (!filename) { - if (opts.finalize !== false) pack2.finalize(); - return finish(pack2); - } - if (stat.isSocket()) return onnextentry(); - var header = { - name: normalize(filename), - mode: (stat.mode | (stat.isDirectory() ? dmode : fmode)) & umask, - mtime: stat.mtime, - size: stat.size, - type: "file", - uid: stat.uid, - gid: stat.gid - }; - if (stat.isDirectory()) { - header.size = 0; - header.type = "directory"; - header = map(header) || header; - return pack2.entry(header, onnextentry); - } - if (stat.isSymbolicLink()) { - header.size = 0; - header.type = "symlink"; - header = map(header) || header; - return onsymlink(filename, header); - } - header = map(header) || header; - if (!stat.isFile()) { - if (strict) return pack2.destroy(new Error("unsupported type for " + filename)); - return onnextentry(); - } - var entry = pack2.entry(header, onnextentry); - if (!entry) return; - var rs = mapStream(xfs.createReadStream(path.join(cwd, filename), { start: 0, end: header.size > 0 ? header.size - 1 : header.size }), header); - rs.on("error", function(err2) { - entry.destroy(err2); - }); - pump(rs, entry); - }; - var onnextentry = function(err) { - if (err) return pack2.destroy(err); - statNext(onstat); - }; - onnextentry(); - return pack2; - }; - var head = function(list) { - return list.length ? list[list.length - 1] : null; - }; - var processGetuid = function() { - return process.getuid ? process.getuid() : -1; - }; - var processUmask = function() { - return process.umask ? process.umask() : 0; - }; - exports2.extract = function(cwd, opts) { - if (!cwd) cwd = "."; - if (!opts) opts = {}; - var xfs = opts.fs || fs3; - var ignore = opts.ignore || opts.filter || noop3; - var map = opts.map || noop3; - var mapStream = opts.mapStream || echo; - var own = opts.chown !== false && !win32 && processGetuid() === 0; - var extract2 = opts.extract || tar.extract(); - var stack = []; - var now = /* @__PURE__ */ new Date(); - var umask = typeof opts.umask === "number" ? ~opts.umask : ~processUmask(); - var dmode = typeof opts.dmode === "number" ? opts.dmode : 0; - var fmode = typeof opts.fmode === "number" ? opts.fmode : 0; - var strict = opts.strict !== false; - if (opts.strip) map = strip(map, opts.strip); - if (opts.readable) { - dmode |= parseInt(555, 8); - fmode |= parseInt(444, 8); - } - if (opts.writable) { - dmode |= parseInt(333, 8); - fmode |= parseInt(222, 8); - } - var utimesParent = function(name, cb) { - var top; - while ((top = head(stack)) && name.slice(0, top[0].length) !== top[0]) stack.pop(); - if (!top) return cb(); - xfs.utimes(top[0], now, top[1], cb); - }; - var utimes = function(name, header, cb) { - if (opts.utimes === false) return cb(); - if (header.type === "directory") return xfs.utimes(name, now, header.mtime, cb); - if (header.type === "symlink") return utimesParent(name, cb); - xfs.utimes(name, now, header.mtime, function(err) { - if (err) return cb(err); - utimesParent(name, cb); - }); - }; - var chperm = function(name, header, cb) { - var link = header.type === "symlink"; - var chmod = link ? xfs.lchmod : xfs.chmod; - var chown = link ? xfs.lchown : xfs.chown; - if (!chmod) return cb(); - var mode = (header.mode | (header.type === "directory" ? dmode : fmode)) & umask; - if (chown && own) chown.call(xfs, name, header.uid, header.gid, onchown); - else onchown(null); - function onchown(err) { - if (err) return cb(err); - if (!chmod) return cb(); - chmod.call(xfs, name, mode, cb); - } - }; - extract2.on("entry", function(header, stream2, next) { - header = map(header) || header; - header.name = normalize(header.name); - var name = path.join(cwd, path.join("/", header.name)); - if (ignore(name, header)) { - stream2.resume(); - return next(); - } - var stat = function(err) { - if (err) return next(err); - utimes(name, header, function(err2) { - if (err2) return next(err2); - if (win32) return next(); - chperm(name, header, next); - }); - }; - var onsymlink = function() { - if (win32) return next(); - xfs.unlink(name, function() { - var dst = path.resolve(path.dirname(name), header.linkname); - if (!inCwd(dst, cwd)) return next(new Error(name + " is not a valid symlink")); - xfs.symlink(header.linkname, name, stat); - }); - }; - var onlink = function() { - if (win32) return next(); - xfs.unlink(name, function() { - var srcpath = path.join(cwd, path.join("/", header.linkname)); - xfs.realpath(srcpath, function(err, dst) { - if (err || !inCwd(dst, cwd)) return next(new Error(name + " is not a valid hardlink")); - xfs.link(dst, name, function(err2) { - if (err2 && err2.code === "EPERM" && opts.hardlinkAsFilesFallback) { - stream2 = xfs.createReadStream(srcpath); - return onfile(); - } - stat(err2); - }); - }); - }); - }; - var onfile = function() { - var ws = xfs.createWriteStream(name); - var rs = mapStream(stream2, header); - ws.on("error", function(err) { - rs.destroy(err); - }); - pump(rs, ws, function(err) { - if (err) return next(err); - ws.on("close", stat); - }); - }; - if (header.type === "directory") { - stack.push([name, header.mtime]); - return mkdirfix(name, { - fs: xfs, - own, - uid: header.uid, - gid: header.gid - }, stat); - } - var dir = path.dirname(name); - validate(xfs, dir, path.join(cwd, "."), function(err, valid) { - if (err) return next(err); - if (!valid) return next(new Error(dir + " is not a valid path")); - mkdirfix(dir, { - fs: xfs, - own, - uid: header.uid, - gid: header.gid - }, function(err2) { - if (err2) return next(err2); - switch (header.type) { - case "file": - return onfile(); - case "link": - return onlink(); - case "symlink": - return onsymlink(); - } - if (strict) return next(new Error("unsupported type for " + name + " (" + header.type + ")")); - stream2.resume(); - next(); - }); - }); - }); - if (opts.finish) extract2.on("finish", opts.finish); - return extract2; - }; - function validate(fs4, name, root, cb) { - if (name === root) return cb(null, true); - fs4.lstat(name, function(err, st) { - if (err && err.code !== "ENOENT") return cb(err); - if (err || st.isDirectory()) return validate(fs4, path.join(name, ".."), root, cb); - cb(null, false); - }); - } - function mkdirfix(name, opts, cb) { - mkdirp(name, { fs: opts.fs }, function(err, made) { - if (!err && made && opts.own) { - chownr(made, opts.uid, opts.gid, cb); - } else { - cb(err); - } - }); - } - function inCwd(dst, cwd) { - cwd = path.resolve(cwd); - return cwd === dst || dst.startsWith(cwd + path.sep); - } - } -}); - -// node_modules/dockerode/lib/util.js -var require_util9 = __commonJS({ - "node_modules/dockerode/lib/util.js"(exports2, module2) { - var DockerIgnore = require_ignore(); - var fs3 = require("fs"); - var path = require("path"); - var tar = require_tar_fs(); - var zlib = require("zlib"); - var arr = []; - var each = arr.forEach; - var slice = arr.slice; - module2.exports.extend = function(obj) { - each.call(slice.call(arguments, 1), function(source) { - if (source) { - for (var prop in source) { - obj[prop] = source[prop]; - } - } - }); - return obj; - }; - module2.exports.processArgs = function(opts, callback, defaultOpts) { - if (!callback && typeof opts === "function") { - callback = opts; - opts = null; - } - return { - callback, - opts: module2.exports.extend({}, defaultOpts, opts) - }; - }; - module2.exports.parseRepositoryTag = function(input) { - var separatorPos; - var digestPos = input.indexOf("@"); - var colonPos = input.lastIndexOf(":"); - if (digestPos >= 0) { - separatorPos = digestPos; - } else if (colonPos >= 0) { - separatorPos = colonPos; - } else { - return { - repository: input - }; - } - var tag = input.slice(separatorPos + 1); - if (tag.indexOf("/") === -1) { - return { - repository: input.slice(0, separatorPos), - tag - }; - } - return { - repository: input - }; - }; - module2.exports.prepareBuildContext = function(file, next) { - if (file && file.context) { - fs3.readFile(path.join(file.context, ".dockerignore"), (err, data) => { - let ignoreFn; - let filterFn; - if (!err) { - const dockerIgnore = DockerIgnore({ ignorecase: false }).add(data.toString()); - filterFn = dockerIgnore.createFilter(); - ignoreFn = (path2) => { - return !filterFn(path2); - }; - } - const entries = file.src.slice() || []; - const pack2 = tar.pack(file.context, { - entries: filterFn ? entries.filter(filterFn) : entries, - ignore: ignoreFn - // Only works on directories - }); - next(pack2.pipe(zlib.createGzip())); - }); - } else { - next(file); - } - }; - } -}); - -// node_modules/dockerode/lib/exec.js -var require_exec2 = __commonJS({ - "node_modules/dockerode/lib/exec.js"(exports2, module2) { - var util = require_util9(); - var Exec = function(modem, id) { - this.modem = modem; - this.id = id; - }; - Exec.prototype[require("util").inspect.custom] = function() { - return this; - }; - Exec.prototype.start = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/exec/" + this.id + "/start", - method: "POST", - abortSignal: args.opts.abortSignal, - isStream: true, - allowEmpty: true, - hijack: args.opts.hijack, - openStdin: args.opts.stdin, - statusCodes: { - 200: true, - 204: true, - 404: "no such exec", - 409: "container stopped/paused", - 500: "container not running" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, data); - }); - } - }; - Exec.prototype.resize = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/exec/" + this.id + "/resize?", - method: "POST", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: "no such exec", - 500: "container not running" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, data); - }); - } - }; - Exec.prototype.inspect = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/exec/" + this.id + "/json", - method: "GET", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: "no such exec", - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, data); - }); - } - }; - module2.exports = Exec; - } -}); - -// node_modules/dockerode/lib/container.js -var require_container = __commonJS({ - "node_modules/dockerode/lib/container.js"(exports2, module2) { - var extend = require_util9().extend; - var Exec = require_exec2(); - var util = require_util9(); - var Container2 = function(modem, id) { - this.modem = modem; - this.id = id; - this.defaultOptions = { - top: {}, - start: {}, - commit: {}, - stop: {}, - pause: {}, - unpause: {}, - restart: {}, - resize: {}, - attach: {}, - remove: {}, - copy: {}, - kill: {}, - exec: {}, - rename: {}, - log: {}, - stats: {}, - getArchive: {}, - infoArchive: {}, - putArchive: {}, - update: {}, - wait: {} - }; - }; - Container2.prototype[require("util").inspect.custom] = function() { - return this; - }; - Container2.prototype.inspect = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/containers/" + this.id + "/json?", - method: "GET", - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: "no such container", - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Container2.prototype.rename = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback, this.defaultOptions.rename); - var optsf = { - path: "/containers/" + this.id + "/rename?", - method: "POST", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: "no such container", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Container2.prototype.update = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback, this.defaultOptions.update); - var optsf = { - path: "/containers/" + this.id + "/update", - method: "POST", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 400: "bad parameter", - 404: "no such container", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Container2.prototype.top = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback, this.defaultOptions.top); - var optsf = { - path: "/containers/" + this.id + "/top?", - method: "GET", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: "no such container", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Container2.prototype.changes = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/containers/" + this.id + "/changes", - method: "GET", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: "no such container", - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Container2.prototype.listCheckpoint = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/containers/" + this.id + "/checkpoints?", - method: "GET", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: "no such container", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Container2.prototype.deleteCheckpoint = function(checkpoint, opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/containers/" + this.id + "/checkpoints/" + checkpoint + "?", - method: "DELETE", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - // unofficial, but proxies may return it - 204: true, - 404: "no such container", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Container2.prototype.createCheckpoint = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/containers/" + this.id + "/checkpoints", - method: "POST", - abortSignal: args.opts.abortSignal, - allowEmpty: true, - statusCodes: { - 200: true, - //unofficial, but proxies may return it - 201: true, - 204: true, - 404: "no such container", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Container2.prototype.export = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/containers/" + this.id + "/export", - method: "GET", - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 404: "no such container", - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Container2.prototype.start = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback, this.defaultOptions.start); - var optsf = { - path: "/containers/" + this.id + "/start?", - method: "POST", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - // unofficial, but proxies may return it - 204: true, - 304: "container already started", - 404: "no such container", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Container2.prototype.pause = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback, this.defaultOptions.pause); - var optsf = { - path: "/containers/" + this.id + "/pause", - method: "POST", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - // unofficial, but proxies may return it - 204: true, - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Container2.prototype.unpause = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback, this.defaultOptions.unpause); - var optsf = { - path: "/containers/" + this.id + "/unpause", - method: "POST", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - // unofficial, but proxies may return it - 204: true, - 404: "no such container", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Container2.prototype.exec = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback, this.defaultOptions.exec); - var optsf = { - path: "/containers/" + this.id + "/exec", - method: "POST", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - // unofficial, but proxies may return it - 201: true, - 404: "no such container", - 409: "container stopped/paused", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(new Exec(self2.modem, data.Id)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, new Exec(self2.modem, data.Id)); - }); - } - }; - Container2.prototype.commit = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback, this.defaultOptions.commit); - args.opts.container = this.id; - var optsf = { - path: "/commit?", - method: "POST", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - // unofficial, but proxies may return it - 201: true, - 404: "no such container", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Container2.prototype.stop = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback, this.defaultOptions.stop); - var optsf = { - path: "/containers/" + this.id + "/stop?", - method: "POST", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - // unofficial, but proxies may return it - 204: true, - 304: "container already stopped", - 404: "no such container", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Container2.prototype.restart = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback, this.defaultOptions.restart); - var optsf = { - path: "/containers/" + this.id + "/restart?", - method: "POST", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - // unofficial, but proxies may return it - 204: true, - 404: "no such container", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Container2.prototype.kill = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback, this.defaultOptions.kill); - var optsf = { - path: "/containers/" + this.id + "/kill?", - method: "POST", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - // unofficial, but proxies may return it - 204: true, - 404: "no such container", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Container2.prototype.resize = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback, this.defaultOptions.resize); - var optsf = { - path: "/containers/" + this.id + "/resize?", - method: "POST", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: "bad parameter", - 404: "no such container", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Container2.prototype.attach = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback, this.defaultOptions.attach); - var optsf = { - path: "/containers/" + this.id + "/attach?", - method: "POST", - abortSignal: args.opts.abortSignal, - isStream: true, - hijack: args.opts.hijack, - openStdin: args.opts.stdin, - statusCodes: { - 200: true, - 404: "no such container", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, stream2) { - if (err) { - return reject(err); - } - resolve(stream2); - }); - }); - } else { - this.modem.dial(optsf, function(err, stream2) { - args.callback(err, stream2); - }); - } - }; - Container2.prototype.wait = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback, this.defaultOptions.wait); - var optsf = { - path: "/containers/" + this.id + "/wait?", - method: "POST", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: "bad parameter", - 404: "no such container", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Container2.prototype.remove = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback, this.defaultOptions.remove); - var optsf = { - path: "/containers/" + this.id + "?", - method: "DELETE", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - // unofficial, but proxies may return it - 204: true, - 400: "bad parameter", - 404: "no such container", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Container2.prototype.copy = function(opts, callback) { - var self2 = this; - console.log("container.copy is deprecated since Docker v1.8.x"); - var args = util.processArgs(opts, callback, this.defaultOptions.copy); - var optsf = { - path: "/containers/" + this.id + "/copy", - method: "POST", - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 404: "no such container", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Container2.prototype.getArchive = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback, this.defaultOptions.getArchive); - var optsf = { - path: "/containers/" + this.id + "/archive?", - method: "GET", - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 400: "client error, bad parameters", - 404: "no such container", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Container2.prototype.infoArchive = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback, this.defaultOptions.infoArchive); - var optsf = { - path: "/containers/" + this.id + "/archive?", - method: "HEAD", - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 400: "client error, bad parameters", - 404: "no such container", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Container2.prototype.putArchive = function(file, opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback, this.defaultOptions.putArchive); - var optsf = { - path: "/containers/" + this.id + "/archive?", - method: "PUT", - file, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: "client error, bad parameters", - 403: "client error, permission denied", - 404: "no such container", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Container2.prototype.logs = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback, this.defaultOptions.log); - var optsf = { - path: "/containers/" + this.id + "/logs?", - method: "GET", - abortSignal: args.opts.abortSignal, - isStream: args.opts.follow || false, - statusCodes: { - 200: true, - 404: "no such container", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Container2.prototype.stats = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback, this.defaultOptions.stats); - var isStream = true; - if (args.opts.stream === false) { - isStream = false; - } - var optsf = { - path: "/containers/" + this.id + "/stats?", - method: "GET", - abortSignal: args.opts.abortSignal, - isStream, - statusCodes: { - 200: true, - 404: "no such container", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - module2.exports = Container2; - } -}); - -// node_modules/dockerode/lib/image.js -var require_image = __commonJS({ - "node_modules/dockerode/lib/image.js"(exports2, module2) { - var util = require_util9(); - var Image = function(modem, name) { - this.modem = modem; - this.name = name; - }; - Image.prototype[require("util").inspect.custom] = function() { - return this; - }; - Image.prototype.inspect = function(opts, callback) { - var args = util.processArgs(opts, callback); - var self2 = this; - var opts = { - path: "/images/" + this.name + "/json", - method: "GET", - options: args.opts, - statusCodes: { - 200: true, - 404: "no such image", - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(opts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(opts, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, data); - }); - } - }; - Image.prototype.distribution = function(opts, callback) { - var args = util.processArgs(opts, callback); - var self2 = this; - var fopts = { - path: "/distribution/" + this.name + "/json", - method: "GET", - statusCodes: { - 200: true, - 401: "no such image", - 500: "server error" - }, - authconfig: args.opts ? args.opts.authconfig : void 0 - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(fopts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(fopts, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, data); - }); - } - }; - Image.prototype.history = function(callback) { - var self2 = this; - var opts = { - path: "/images/" + this.name + "/history", - method: "GET", - statusCodes: { - 200: true, - 404: "no such image", - 500: "server error" - } - }; - if (callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(opts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(opts, function(err, data) { - if (err) return callback(err, data); - callback(err, data); - }); - } - }; - Image.prototype.get = function(callback) { - var self2 = this; - var opts = { - path: "/images/" + this.name + "/get", - method: "GET", - isStream: true, - statusCodes: { - 200: true, - 500: "server error" - } - }; - if (callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(opts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(opts, function(err, data) { - if (err) return callback(err, data); - callback(err, data); - }); - } - }; - Image.prototype.push = function(opts, callback, auth2) { - var self2 = this; - var args = util.processArgs(opts, callback); - var isStream = true; - if (args.opts.stream === false) { - isStream = false; - } - var optsf = { - path: "/images/" + this.name + "/push?", - method: "POST", - options: args.opts, - authconfig: args.opts.authconfig || auth2, - abortSignal: args.opts.abortSignal, - isStream, - statusCodes: { - 200: true, - 404: "no such image", - 500: "server error" - } - }; - delete optsf.options.authconfig; - if (callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } - }; - Image.prototype.tag = function(opts, callback) { - var self2 = this; - var optsf = { - path: "/images/" + this.name + "/tag?", - method: "POST", - options: opts, - abortSignal: opts && opts.abortSignal, - statusCodes: { - 200: true, - // unofficial, but proxies may return it - 201: true, - 400: "bad parameter", - 404: "no such image", - 409: "conflict", - 500: "server error" - } - }; - if (callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } - }; - Image.prototype.remove = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/images/" + this.name + "?", - method: "DELETE", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: "no such image", - 409: "conflict", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - module2.exports = Image; - } -}); - -// node_modules/dockerode/lib/volume.js -var require_volume = __commonJS({ - "node_modules/dockerode/lib/volume.js"(exports2, module2) { - var util = require_util9(); - var Volume = function(modem, name) { - this.modem = modem; - this.name = name; - }; - Volume.prototype[require("util").inspect.custom] = function() { - return this; - }; - Volume.prototype.inspect = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/volumes/" + this.name, - method: "GET", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: "no such volume", - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Volume.prototype.remove = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/volumes/" + this.name, - method: "DELETE", - abortSignal: args.opts.abortSignal, - statusCodes: { - 204: true, - 404: "no such volume", - 409: "conflict", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - module2.exports = Volume; - } -}); - -// node_modules/dockerode/lib/network.js -var require_network = __commonJS({ - "node_modules/dockerode/lib/network.js"(exports2, module2) { - var util = require_util9(); - var Network = function(modem, id) { - this.modem = modem; - this.id = id; - }; - Network.prototype[require("util").inspect.custom] = function() { - return this; - }; - Network.prototype.inspect = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var opts = { - path: "/networks/" + this.id + "?", - method: "GET", - statusCodes: { - 200: true, - 404: "no such network", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(opts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(opts, function(err, data) { - args.callback(err, data); - }); - } - }; - Network.prototype.remove = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/networks/" + this.id, - method: "DELETE", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: "no such network", - 409: "conflict", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Network.prototype.connect = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/networks/" + this.id + "/connect", - method: "POST", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 201: true, - 404: "network or container is not found", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Network.prototype.disconnect = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/networks/" + this.id + "/disconnect", - method: "POST", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 201: true, - 404: "network or container is not found", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - module2.exports = Network; - } -}); - -// node_modules/dockerode/lib/service.js -var require_service = __commonJS({ - "node_modules/dockerode/lib/service.js"(exports2, module2) { - var util = require_util9(); - var Service = function(modem, id) { - this.modem = modem; - this.id = id; - }; - Service.prototype[require("util").inspect.custom] = function() { - return this; - }; - Service.prototype.inspect = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/services/" + this.id, - method: "GET", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: "no such service", - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Service.prototype.remove = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/services/" + this.id, - method: "DELETE", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: "no such service", - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Service.prototype.update = function(auth2, opts, callback) { - var self2 = this; - if (!callback) { - var t = typeof opts; - if (t === "function") { - callback = opts; - opts = auth2; - auth2 = opts.authconfig || void 0; - } else if (t === "undefined") { - opts = auth2; - auth2 = opts.authconfig || void 0; - } - } - var optsf = { - path: "/services/" + this.id + "/update?", - method: "POST", - abortSignal: opts && opts.abortSignal, - statusCodes: { - 200: true, - 404: "no such service", - 500: "server error" - }, - authconfig: auth2, - options: opts - }; - if (callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } - }; - Service.prototype.logs = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback, {}); - var optsf = { - path: "/services/" + this.id + "/logs?", - method: "GET", - abortSignal: args.opts.abortSignal, - isStream: args.opts.follow || false, - statusCodes: { - 200: true, - 404: "no such service", - 500: "server error", - 503: "node is not part of a swarm" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - module2.exports = Service; - } -}); - -// node_modules/dockerode/lib/plugin.js -var require_plugin = __commonJS({ - "node_modules/dockerode/lib/plugin.js"(exports2, module2) { - var util = require_util9(); - var Plugin = function(modem, name, remote) { - this.modem = modem; - this.name = name; - this.remote = remote || name; - }; - Plugin.prototype[require("util").inspect.custom] = function() { - return this; - }; - Plugin.prototype.inspect = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/plugins/" + this.name + "/json", - method: "GET", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: "plugin is not installed", - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Plugin.prototype.remove = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/plugins/" + this.name + "?", - method: "DELETE", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: "plugin is not installed", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, data); - }); - } - }; - Plugin.prototype.privileges = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/plugins/privileges?", - method: "GET", - options: { - "remote": this.remote - }, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Plugin.prototype.pull = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - if (args.opts._query && !args.opts._query.name) { - args.opts._query.name = this.name; - } - if (args.opts._query && !args.opts._query.remote) { - args.opts._query.remote = this.remote; - } - var optsf = { - path: "/plugins/pull?", - method: "POST", - abortSignal: args.opts.abortSignal, - isStream: true, - options: args.opts, - statusCodes: { - 200: true, - // unofficial, but proxies may return it - 204: true, - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Plugin.prototype.enable = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/plugins/" + this.name + "/enable?", - method: "POST", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Plugin.prototype.disable = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/plugins/" + this.name + "/disable", - method: "POST", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Plugin.prototype.push = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/plugins/" + this.name + "/push", - method: "POST", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: "plugin not installed", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Plugin.prototype.configure = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/plugins/" + this.name + "/set", - method: "POST", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: "plugin not installed", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Plugin.prototype.upgrade = function(auth2, opts, callback) { - var self2 = this; - if (!callback && typeof opts === "function") { - callback = opts; - opts = auth2; - auth2 = opts.authconfig || void 0; - } - var optsf = { - path: "/plugins/" + this.name + "/upgrade?", - method: "POST", - abortSignal: opts && opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: "plugin not installed", - 500: "server error" - }, - authconfig: auth2, - options: opts - }; - if (callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } - }; - module2.exports = Plugin; - } -}); - -// node_modules/dockerode/lib/secret.js -var require_secret = __commonJS({ - "node_modules/dockerode/lib/secret.js"(exports2, module2) { - var util = require_util9(); - var Secret = function(modem, id) { - this.modem = modem; - this.id = id; - }; - Secret.prototype[require("util").inspect.custom] = function() { - return this; - }; - Secret.prototype.inspect = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/secrets/" + this.id, - method: "GET", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: "secret not found", - 406: "node is not part of a swarm", - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Secret.prototype.update = function(opts, callback) { - var self2 = this; - if (!callback && typeof opts === "function") { - callback = opts; - } - var optsf = { - path: "/secrets/" + this.id + "/update?", - method: "POST", - abortSignal: opts && opts.abortSignal, - statusCodes: { - 200: true, - 404: "secret not found", - 500: "server error" - }, - options: opts - }; - if (callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } - }; - Secret.prototype.remove = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/secrets/" + this.id, - method: "DELETE", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: "secret not found", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - module2.exports = Secret; - } -}); - -// node_modules/dockerode/lib/config.js -var require_config = __commonJS({ - "node_modules/dockerode/lib/config.js"(exports2, module2) { - var util = require_util9(); - var Config = function(modem, id) { - this.modem = modem; - this.id = id; - }; - Config.prototype[require("util").inspect.custom] = function() { - return this; - }; - Config.prototype.inspect = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/configs/" + this.id, - method: "GET", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: "config not found", - 500: "server error", - 503: "node is not part of a swarm" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Config.prototype.update = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/configs/" + this.id + "/update?", - method: "POST", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: "config not found", - 500: "server error", - 503: "node is not part of a swarm" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Config.prototype.remove = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/configs/" + this.id, - method: "DELETE", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: "config not found", - 500: "server error", - 503: "node is not part of a swarm" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - module2.exports = Config; - } -}); - -// node_modules/dockerode/lib/task.js -var require_task = __commonJS({ - "node_modules/dockerode/lib/task.js"(exports2, module2) { - var util = require_util9(); - var Task = function(modem, id) { - this.modem = modem; - this.id = id; - this.defaultOptions = { - log: {} - }; - }; - Task.prototype[require("util").inspect.custom] = function() { - return this; - }; - Task.prototype.inspect = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/tasks/" + this.id, - method: "GET", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: "unknown task", - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Task.prototype.logs = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback, this.defaultOptions.log); - var optsf = { - path: "/tasks/" + this.id + "/logs?", - method: "GET", - abortSignal: args.opts.abortSignal, - isStream: args.opts.follow || false, - statusCodes: { - 101: true, - 200: true, - 404: "no such container", - 500: "server error", - 503: "node is not part of a swarm" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - module2.exports = Task; - } -}); - -// node_modules/dockerode/lib/node.js -var require_node3 = __commonJS({ - "node_modules/dockerode/lib/node.js"(exports2, module2) { - var util = require_util9(); - var Node = function(modem, id) { - this.modem = modem; - this.id = id; - }; - Node.prototype[require("util").inspect.custom] = function() { - return this; - }; - Node.prototype.inspect = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/nodes/" + this.id, - method: "GET", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: "no such node", - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Node.prototype.update = function(opts, callback) { - var self2 = this; - if (!callback && typeof opts === "function") { - callback = opts; - } - var optsf = { - path: "/nodes/" + this.id + "/update?", - method: "POST", - abortSignal: opts && opts.abortSignal, - statusCodes: { - 200: true, - 404: "no such node", - 406: "node is not part of a swarm", - 500: "server error" - }, - options: opts - }; - if (callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } - }; - Node.prototype.remove = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/nodes/" + this.id + "?", - method: "DELETE", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: "no such node", - 500: "server error" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - module2.exports = Node; - } -}); - -// node_modules/@grpc/grpc-js/build/src/constants.js -var require_constants7 = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/constants.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH = exports2.DEFAULT_MAX_SEND_MESSAGE_LENGTH = exports2.Propagate = exports2.LogVerbosity = exports2.Status = void 0; - var Status; - (function(Status2) { - Status2[Status2["OK"] = 0] = "OK"; - Status2[Status2["CANCELLED"] = 1] = "CANCELLED"; - Status2[Status2["UNKNOWN"] = 2] = "UNKNOWN"; - Status2[Status2["INVALID_ARGUMENT"] = 3] = "INVALID_ARGUMENT"; - Status2[Status2["DEADLINE_EXCEEDED"] = 4] = "DEADLINE_EXCEEDED"; - Status2[Status2["NOT_FOUND"] = 5] = "NOT_FOUND"; - Status2[Status2["ALREADY_EXISTS"] = 6] = "ALREADY_EXISTS"; - Status2[Status2["PERMISSION_DENIED"] = 7] = "PERMISSION_DENIED"; - Status2[Status2["RESOURCE_EXHAUSTED"] = 8] = "RESOURCE_EXHAUSTED"; - Status2[Status2["FAILED_PRECONDITION"] = 9] = "FAILED_PRECONDITION"; - Status2[Status2["ABORTED"] = 10] = "ABORTED"; - Status2[Status2["OUT_OF_RANGE"] = 11] = "OUT_OF_RANGE"; - Status2[Status2["UNIMPLEMENTED"] = 12] = "UNIMPLEMENTED"; - Status2[Status2["INTERNAL"] = 13] = "INTERNAL"; - Status2[Status2["UNAVAILABLE"] = 14] = "UNAVAILABLE"; - Status2[Status2["DATA_LOSS"] = 15] = "DATA_LOSS"; - Status2[Status2["UNAUTHENTICATED"] = 16] = "UNAUTHENTICATED"; - })(Status || (exports2.Status = Status = {})); - var LogVerbosity; - (function(LogVerbosity2) { - LogVerbosity2[LogVerbosity2["DEBUG"] = 0] = "DEBUG"; - LogVerbosity2[LogVerbosity2["INFO"] = 1] = "INFO"; - LogVerbosity2[LogVerbosity2["ERROR"] = 2] = "ERROR"; - LogVerbosity2[LogVerbosity2["NONE"] = 3] = "NONE"; - })(LogVerbosity || (exports2.LogVerbosity = LogVerbosity = {})); - var Propagate; - (function(Propagate2) { - Propagate2[Propagate2["DEADLINE"] = 1] = "DEADLINE"; - Propagate2[Propagate2["CENSUS_STATS_CONTEXT"] = 2] = "CENSUS_STATS_CONTEXT"; - Propagate2[Propagate2["CENSUS_TRACING_CONTEXT"] = 4] = "CENSUS_TRACING_CONTEXT"; - Propagate2[Propagate2["CANCELLATION"] = 8] = "CANCELLATION"; - Propagate2[Propagate2["DEFAULTS"] = 65535] = "DEFAULTS"; - })(Propagate || (exports2.Propagate = Propagate = {})); - exports2.DEFAULT_MAX_SEND_MESSAGE_LENGTH = -1; - exports2.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH = 4 * 1024 * 1024; - } -}); - -// node_modules/@grpc/grpc-js/package.json -var require_package2 = __commonJS({ - "node_modules/@grpc/grpc-js/package.json"(exports2, module2) { - module2.exports = { - name: "@grpc/grpc-js", - version: "1.14.4", - description: "gRPC Library for Node - pure JS implementation", - homepage: "https://grpc.io/", - repository: "https://github.com/grpc/grpc-node/tree/master/packages/grpc-js", - main: "build/src/index.js", - engines: { - node: ">=12.10.0" - }, - keywords: [], - author: { - name: "Google Inc." - }, - types: "build/src/index.d.ts", - license: "Apache-2.0", - devDependencies: { - "@grpc/proto-loader": "file:../proto-loader", - "@types/gulp": "^4.0.17", - "@types/gulp-mocha": "0.0.37", - "@types/lodash": "^4.14.202", - "@types/mocha": "^10.0.6", - "@types/ncp": "^2.0.8", - "@types/node": ">=20.11.20", - "@types/pify": "^5.0.4", - "@types/semver": "^7.5.8", - "@typescript-eslint/eslint-plugin": "^7.1.0", - "@typescript-eslint/parser": "^7.1.0", - "@typescript-eslint/typescript-estree": "^7.1.0", - "clang-format": "^1.8.0", - eslint: "^8.42.0", - "eslint-config-prettier": "^8.8.0", - "eslint-plugin-node": "^11.1.0", - "eslint-plugin-prettier": "^4.2.1", - execa: "^2.0.3", - gulp: "^4.0.2", - "gulp-mocha": "^6.0.0", - lodash: "^4.17.21", - madge: "^5.0.1", - "mocha-jenkins-reporter": "^0.4.1", - ncp: "^2.0.0", - pify: "^4.0.1", - prettier: "^2.8.8", - rimraf: "^3.0.2", - semver: "^7.6.0", - "ts-node": "^10.9.2", - typescript: "^5.3.3" - }, - contributors: [ - { - name: "Google Inc." - } - ], - scripts: { - build: "npm run compile", - clean: "rimraf ./build", - compile: "tsc -p .", - format: 'clang-format -i -style="{Language: JavaScript, BasedOnStyle: Google, ColumnLimit: 80}" src/*.ts test/*.ts', - lint: "eslint src/*.ts test/*.ts", - prepare: "npm run copy-protos && npm run generate-types && npm run generate-test-types && npm run compile", - test: "gulp test", - check: "npm run lint", - fix: "eslint --fix src/*.ts test/*.ts", - pretest: "npm run generate-types && npm run generate-test-types && npm run compile", - posttest: "npm run check && madge -c ./build/src", - "generate-types": "proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --includeDirs proto/ --include-dirs proto/ proto/xds/ proto/protoc-gen-validate/ -O src/generated/ --grpcLib ../index channelz.proto xds/service/orca/v3/orca.proto", - "generate-test-types": "proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --include-dirs test/fixtures/ -O test/generated/ --grpcLib ../../src/index test_service.proto echo_service.proto", - "copy-protos": "node ./copy-protos" - }, - dependencies: { - "@grpc/proto-loader": "^0.8.0", - "@js-sdsl/ordered-map": "^4.4.2" - }, - files: [ - "src/**/*.ts", - "build/src/**/*.{js,d.ts,js.map}", - "proto/**/*.proto", - "proto/**/LICENSE", - "LICENSE", - "deps/envoy-api/envoy/api/v2/**/*.proto", - "deps/envoy-api/envoy/config/**/*.proto", - "deps/envoy-api/envoy/service/**/*.proto", - "deps/envoy-api/envoy/type/**/*.proto", - "deps/udpa/udpa/**/*.proto", - "deps/googleapis/google/api/*.proto", - "deps/googleapis/google/rpc/*.proto", - "deps/protoc-gen-validate/validate/**/*.proto" - ] - }; - } -}); - -// node_modules/@grpc/grpc-js/build/src/logging.js -var require_logging = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/logging.js"(exports2) { - "use strict"; - var _a; - var _b; - var _c; - var _d; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.log = exports2.setLoggerVerbosity = exports2.setLogger = exports2.getLogger = void 0; - exports2.trace = trace; - exports2.isTracerEnabled = isTracerEnabled; - var constants_1 = require_constants7(); - var process_1 = require("process"); - var clientVersion = require_package2().version; - var DEFAULT_LOGGER = { - error: (message, ...optionalParams) => { - console.error("E " + message, ...optionalParams); - }, - info: (message, ...optionalParams) => { - console.error("I " + message, ...optionalParams); - }, - debug: (message, ...optionalParams) => { - console.error("D " + message, ...optionalParams); - } - }; - var _logger = DEFAULT_LOGGER; - var _logVerbosity = constants_1.LogVerbosity.ERROR; - var verbosityString = (_b = (_a = process.env.GRPC_NODE_VERBOSITY) !== null && _a !== void 0 ? _a : process.env.GRPC_VERBOSITY) !== null && _b !== void 0 ? _b : ""; - switch (verbosityString.toUpperCase()) { - case "DEBUG": - _logVerbosity = constants_1.LogVerbosity.DEBUG; - break; - case "INFO": - _logVerbosity = constants_1.LogVerbosity.INFO; - break; - case "ERROR": - _logVerbosity = constants_1.LogVerbosity.ERROR; - break; - case "NONE": - _logVerbosity = constants_1.LogVerbosity.NONE; - break; - default: - } - var getLogger = () => { - return _logger; - }; - exports2.getLogger = getLogger; - var setLogger = (logger) => { - _logger = logger; - }; - exports2.setLogger = setLogger; - var setLoggerVerbosity = (verbosity) => { - _logVerbosity = verbosity; - }; - exports2.setLoggerVerbosity = setLoggerVerbosity; - var log = (severity, ...args) => { - let logFunction; - if (severity >= _logVerbosity) { - switch (severity) { - case constants_1.LogVerbosity.DEBUG: - logFunction = _logger.debug; - break; - case constants_1.LogVerbosity.INFO: - logFunction = _logger.info; - break; - case constants_1.LogVerbosity.ERROR: - logFunction = _logger.error; - break; - } - if (!logFunction) { - logFunction = _logger.error; - } - if (logFunction) { - logFunction.bind(_logger)(...args); - } - } - }; - exports2.log = log; - var tracersString = (_d = (_c = process.env.GRPC_NODE_TRACE) !== null && _c !== void 0 ? _c : process.env.GRPC_TRACE) !== null && _d !== void 0 ? _d : ""; - var enabledTracers = /* @__PURE__ */ new Set(); - var disabledTracers = /* @__PURE__ */ new Set(); - for (const tracerName of tracersString.split(",")) { - if (tracerName.startsWith("-")) { - disabledTracers.add(tracerName.substring(1)); - } else { - enabledTracers.add(tracerName); - } - } - var allEnabled = enabledTracers.has("all"); - function trace(severity, tracer, text) { - if (isTracerEnabled(tracer)) { - (0, exports2.log)(severity, (/* @__PURE__ */ new Date()).toISOString() + " | v" + clientVersion + " " + process_1.pid + " | " + tracer + " | " + text); - } - } - function isTracerEnabled(tracer) { - return !disabledTracers.has(tracer) && (allEnabled || enabledTracers.has(tracer)); - } - } -}); - -// node_modules/@grpc/grpc-js/build/src/error.js -var require_error = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/error.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getErrorMessage = getErrorMessage; - exports2.getErrorCode = getErrorCode; - function getErrorMessage(error3) { - if (error3 instanceof Error) { - return error3.message; - } else { - return String(error3); - } - } - function getErrorCode(error3) { - if (typeof error3 === "object" && error3 !== null && "code" in error3 && typeof error3.code === "number") { - return error3.code; - } else { - return null; - } - } - } -}); - -// node_modules/@grpc/grpc-js/build/src/metadata.js -var require_metadata = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/metadata.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Metadata = void 0; - var logging_1 = require_logging(); - var constants_1 = require_constants7(); - var error_1 = require_error(); - var LEGAL_KEY_REGEX = /^[:0-9a-z_.-]+$/; - var LEGAL_NON_BINARY_VALUE_REGEX = /^[ -~]*$/; - function isLegalKey(key) { - return LEGAL_KEY_REGEX.test(key); - } - function isLegalNonBinaryValue(value) { - return LEGAL_NON_BINARY_VALUE_REGEX.test(value); - } - function isBinaryKey(key) { - return key.endsWith("-bin"); - } - function isCustomMetadata(key) { - return !key.startsWith("grpc-"); - } - function normalizeKey(key) { - return key.toLowerCase(); - } - function validate(key, value) { - if (!isLegalKey(key)) { - throw new Error('Metadata key "' + key + '" contains illegal characters'); - } - if (value !== null && value !== void 0) { - if (isBinaryKey(key)) { - if (!Buffer.isBuffer(value)) { - throw new Error("keys that end with '-bin' must have Buffer values"); - } - } else { - if (Buffer.isBuffer(value)) { - throw new Error("keys that don't end with '-bin' must have String values"); - } - if (!isLegalNonBinaryValue(value)) { - throw new Error('Metadata string value "' + value + '" contains illegal characters'); - } - } - } - } - var Metadata = class _Metadata { - constructor(options = {}) { - this.internalRepr = /* @__PURE__ */ new Map(); - this.opaqueData = /* @__PURE__ */ new Map(); - this.options = options; - } - /** - * Sets the given value for the given key by replacing any other values - * associated with that key. Normalizes the key. - * @param key The key to whose value should be set. - * @param value The value to set. Must be a buffer if and only - * if the normalized key ends with '-bin'. - */ - set(key, value) { - key = normalizeKey(key); - validate(key, value); - this.internalRepr.set(key, [value]); - } - /** - * Adds the given value for the given key by appending to a list of previous - * values associated with that key. Normalizes the key. - * @param key The key for which a new value should be appended. - * @param value The value to add. Must be a buffer if and only - * if the normalized key ends with '-bin'. - */ - add(key, value) { - key = normalizeKey(key); - validate(key, value); - const existingValue = this.internalRepr.get(key); - if (existingValue === void 0) { - this.internalRepr.set(key, [value]); - } else { - existingValue.push(value); - } - } - /** - * Removes the given key and any associated values. Normalizes the key. - * @param key The key whose values should be removed. - */ - remove(key) { - key = normalizeKey(key); - this.internalRepr.delete(key); - } - /** - * Gets a list of all values associated with the key. Normalizes the key. - * @param key The key whose value should be retrieved. - * @return A list of values associated with the given key. - */ - get(key) { - key = normalizeKey(key); - return this.internalRepr.get(key) || []; - } - /** - * Gets a plain object mapping each key to the first value associated with it. - * This reflects the most common way that people will want to see metadata. - * @return A key/value mapping of the metadata. - */ - getMap() { - const result = {}; - for (const [key, values] of this.internalRepr) { - if (values.length > 0) { - const v = values[0]; - result[key] = Buffer.isBuffer(v) ? Buffer.from(v) : v; - } - } - return result; - } - /** - * Clones the metadata object. - * @return The newly cloned object. - */ - clone() { - const newMetadata = new _Metadata(this.options); - const newInternalRepr = newMetadata.internalRepr; - for (const [key, value] of this.internalRepr) { - const clonedValue = value.map((v) => { - if (Buffer.isBuffer(v)) { - return Buffer.from(v); - } else { - return v; - } - }); - newInternalRepr.set(key, clonedValue); - } - return newMetadata; - } - /** - * Merges all key-value pairs from a given Metadata object into this one. - * If both this object and the given object have values in the same key, - * values from the other Metadata object will be appended to this object's - * values. - * @param other A Metadata object. - */ - merge(other) { - for (const [key, values] of other.internalRepr) { - const mergedValue = (this.internalRepr.get(key) || []).concat(values); - this.internalRepr.set(key, mergedValue); - } - } - setOptions(options) { - this.options = options; - } - getOptions() { - return this.options; - } - /** - * Creates an OutgoingHttpHeaders object that can be used with the http2 API. - */ - toHttp2Headers() { - const result = {}; - for (const [key, values] of this.internalRepr) { - if (key.startsWith(":")) { - continue; - } - result[key] = values.map(bufToString); - } - return result; - } - /** - * This modifies the behavior of JSON.stringify to show an object - * representation of the metadata map. - */ - toJSON() { - const result = {}; - for (const [key, values] of this.internalRepr) { - result[key] = values; - } - return result; - } - /** - * Attach additional data of any type to the metadata object, which will not - * be included when sending headers. The data can later be retrieved with - * `getOpaque`. Keys with the prefix `grpc` are reserved for use by this - * library. - * @param key - * @param value - */ - setOpaque(key, value) { - this.opaqueData.set(key, value); - } - /** - * Retrieve data previously added with `setOpaque`. - * @param key - * @returns - */ - getOpaque(key) { - return this.opaqueData.get(key); - } - /** - * Returns a new Metadata object based fields in a given IncomingHttpHeaders - * object. - * @param headers An IncomingHttpHeaders object. - */ - static fromHttp2Headers(headers) { - const result = new _Metadata(); - for (const key of Object.keys(headers)) { - if (key.charAt(0) === ":") { - continue; - } - const values = headers[key]; - try { - if (isBinaryKey(key)) { - if (Array.isArray(values)) { - values.forEach((value) => { - result.add(key, Buffer.from(value, "base64")); - }); - } else if (values !== void 0) { - if (isCustomMetadata(key)) { - values.split(",").forEach((v) => { - result.add(key, Buffer.from(v.trim(), "base64")); - }); - } else { - result.add(key, Buffer.from(values, "base64")); - } - } - } else { - if (Array.isArray(values)) { - values.forEach((value) => { - result.add(key, value); - }); - } else if (values !== void 0) { - result.add(key, values); - } - } - } catch (error3) { - const message = `Failed to add metadata entry ${key}: ${values}. ${(0, error_1.getErrorMessage)(error3)}. For more information see https://github.com/grpc/grpc-node/issues/1173`; - (0, logging_1.log)(constants_1.LogVerbosity.ERROR, message); - } - } - return result; - } - }; - exports2.Metadata = Metadata; - var bufToString = (val) => { - return Buffer.isBuffer(val) ? val.toString("base64") : val; - }; - } -}); - -// node_modules/@grpc/grpc-js/build/src/call-credentials.js -var require_call_credentials = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/call-credentials.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CallCredentials = void 0; - var metadata_1 = require_metadata(); - function isCurrentOauth2Client(client) { - return "getRequestHeaders" in client && typeof client.getRequestHeaders === "function"; - } - var CallCredentials = class _CallCredentials { - /** - * Creates a new CallCredentials object from a given function that generates - * Metadata objects. - * @param metadataGenerator A function that accepts a set of options, and - * generates a Metadata object based on these options, which is passed back - * to the caller via a supplied (err, metadata) callback. - */ - static createFromMetadataGenerator(metadataGenerator) { - return new SingleCallCredentials(metadataGenerator); - } - /** - * Create a gRPC credential from a Google credential object. - * @param googleCredentials The authentication client to use. - * @return The resulting CallCredentials object. - */ - static createFromGoogleCredential(googleCredentials) { - return _CallCredentials.createFromMetadataGenerator((options, callback) => { - let getHeaders; - if (isCurrentOauth2Client(googleCredentials)) { - getHeaders = googleCredentials.getRequestHeaders(options.service_url); - } else { - getHeaders = new Promise((resolve, reject) => { - googleCredentials.getRequestMetadata(options.service_url, (err, headers) => { - if (err) { - reject(err); - return; - } - if (!headers) { - reject(new Error("Headers not set by metadata plugin")); - return; - } - resolve(headers); - }); - }); - } - getHeaders.then((headers) => { - const metadata = new metadata_1.Metadata(); - for (const key of Object.keys(headers)) { - metadata.add(key, headers[key]); - } - callback(null, metadata); - }, (err) => { - callback(err); - }); - }); - } - static createEmpty() { - return new EmptyCallCredentials(); - } - }; - exports2.CallCredentials = CallCredentials; - var ComposedCallCredentials = class _ComposedCallCredentials extends CallCredentials { - constructor(creds) { - super(); - this.creds = creds; - } - async generateMetadata(options) { - const base = new metadata_1.Metadata(); - const generated = await Promise.all(this.creds.map((cred) => cred.generateMetadata(options))); - for (const gen of generated) { - base.merge(gen); - } - return base; - } - compose(other) { - return new _ComposedCallCredentials(this.creds.concat([other])); - } - _equals(other) { - if (this === other) { - return true; - } - if (other instanceof _ComposedCallCredentials) { - return this.creds.every((value, index) => value._equals(other.creds[index])); - } else { - return false; - } - } - }; - var SingleCallCredentials = class _SingleCallCredentials extends CallCredentials { - constructor(metadataGenerator) { - super(); - this.metadataGenerator = metadataGenerator; - } - generateMetadata(options) { - return new Promise((resolve, reject) => { - this.metadataGenerator(options, (err, metadata) => { - if (metadata !== void 0) { - resolve(metadata); - } else { - reject(err); - } - }); - }); - } - compose(other) { - return new ComposedCallCredentials([this, other]); - } - _equals(other) { - if (this === other) { - return true; - } - if (other instanceof _SingleCallCredentials) { - return this.metadataGenerator === other.metadataGenerator; - } else { - return false; - } - } - }; - var EmptyCallCredentials = class _EmptyCallCredentials extends CallCredentials { - generateMetadata(options) { - return Promise.resolve(new metadata_1.Metadata()); - } - compose(other) { - return other; - } - _equals(other) { - return other instanceof _EmptyCallCredentials; - } - }; - } -}); - -// node_modules/@grpc/grpc-js/build/src/tls-helpers.js -var require_tls_helpers = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/tls-helpers.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CIPHER_SUITES = void 0; - exports2.getDefaultRootsData = getDefaultRootsData; - var fs3 = require("fs"); - exports2.CIPHER_SUITES = process.env.GRPC_SSL_CIPHER_SUITES; - var DEFAULT_ROOTS_FILE_PATH = process.env.GRPC_DEFAULT_SSL_ROOTS_FILE_PATH; - var defaultRootsData = null; - function getDefaultRootsData() { - if (DEFAULT_ROOTS_FILE_PATH) { - if (defaultRootsData === null) { - defaultRootsData = fs3.readFileSync(DEFAULT_ROOTS_FILE_PATH); - } - return defaultRootsData; - } - return null; - } - } -}); - -// node_modules/@grpc/grpc-js/build/src/uri-parser.js -var require_uri_parser = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/uri-parser.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.parseUri = parseUri; - exports2.splitHostPort = splitHostPort; - exports2.combineHostPort = combineHostPort; - exports2.uriToString = uriToString; - var URI_REGEX = /^(?:([A-Za-z0-9+.-]+):)?(?:\/\/([^/]*)\/)?(.+)$/; - function parseUri(uriString) { - const parsedUri = URI_REGEX.exec(uriString); - if (parsedUri === null) { - return null; - } - return { - scheme: parsedUri[1], - authority: parsedUri[2], - path: parsedUri[3] - }; - } - var NUMBER_REGEX = /^\d+$/; - function splitHostPort(path) { - if (path.startsWith("[")) { - const hostEnd = path.indexOf("]"); - if (hostEnd === -1) { - return null; - } - const host = path.substring(1, hostEnd); - if (host.indexOf(":") === -1) { - return null; - } - if (path.length > hostEnd + 1) { - if (path[hostEnd + 1] === ":") { - const portString = path.substring(hostEnd + 2); - if (NUMBER_REGEX.test(portString)) { - return { - host, - port: +portString - }; - } else { - return null; - } - } else { - return null; - } - } else { - return { - host - }; - } - } else { - const splitPath = path.split(":"); - if (splitPath.length === 2) { - if (NUMBER_REGEX.test(splitPath[1])) { - return { - host: splitPath[0], - port: +splitPath[1] - }; - } else { - return null; - } - } else { - return { - host: path - }; - } - } - } - function combineHostPort(hostPort) { - if (hostPort.port === void 0) { - return hostPort.host; - } else { - if (hostPort.host.includes(":")) { - return `[${hostPort.host}]:${hostPort.port}`; - } else { - return `${hostPort.host}:${hostPort.port}`; - } - } - } - function uriToString(uri) { - let result = ""; - if (uri.scheme !== void 0) { - result += uri.scheme + ":"; - } - if (uri.authority !== void 0) { - result += "//" + uri.authority + "/"; - } - result += uri.path; - return result; - } - } -}); - -// node_modules/@grpc/grpc-js/build/src/resolver.js -var require_resolver = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/resolver.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CHANNEL_ARGS_CONFIG_SELECTOR_KEY = void 0; - exports2.registerResolver = registerResolver; - exports2.registerDefaultScheme = registerDefaultScheme; - exports2.createResolver = createResolver; - exports2.getDefaultAuthority = getDefaultAuthority; - exports2.mapUriDefaultScheme = mapUriDefaultScheme; - var uri_parser_1 = require_uri_parser(); - exports2.CHANNEL_ARGS_CONFIG_SELECTOR_KEY = "grpc.internal.config_selector"; - var registeredResolvers = {}; - var defaultScheme = null; - function registerResolver(scheme, resolverClass) { - registeredResolvers[scheme] = resolverClass; - } - function registerDefaultScheme(scheme) { - defaultScheme = scheme; - } - function createResolver(target, listener, options) { - if (target.scheme !== void 0 && target.scheme in registeredResolvers) { - return new registeredResolvers[target.scheme](target, listener, options); - } else { - throw new Error(`No resolver could be created for target ${(0, uri_parser_1.uriToString)(target)}`); - } - } - function getDefaultAuthority(target) { - if (target.scheme !== void 0 && target.scheme in registeredResolvers) { - return registeredResolvers[target.scheme].getDefaultAuthority(target); - } else { - throw new Error(`Invalid target ${(0, uri_parser_1.uriToString)(target)}`); - } - } - function mapUriDefaultScheme(target) { - if (target.scheme === void 0 || !(target.scheme in registeredResolvers)) { - if (defaultScheme !== null) { - return { - scheme: defaultScheme, - authority: void 0, - path: (0, uri_parser_1.uriToString)(target) - }; - } else { - return null; - } - } - return target; - } - } -}); - -// node_modules/@grpc/grpc-js/build/src/channel-credentials.js -var require_channel_credentials = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/channel-credentials.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ChannelCredentials = void 0; - exports2.createCertificateProviderChannelCredentials = createCertificateProviderChannelCredentials; - var tls_1 = require("tls"); - var call_credentials_1 = require_call_credentials(); - var tls_helpers_1 = require_tls_helpers(); - var uri_parser_1 = require_uri_parser(); - var resolver_1 = require_resolver(); - var logging_1 = require_logging(); - var constants_1 = require_constants7(); - function verifyIsBufferOrNull(obj, friendlyName) { - if (obj && !(obj instanceof Buffer)) { - throw new TypeError(`${friendlyName}, if provided, must be a Buffer.`); - } - } - var ChannelCredentials = class { - /** - * Returns a copy of this object with the included set of per-call credentials - * expanded to include callCredentials. - * @param callCredentials A CallCredentials object to associate with this - * instance. - */ - compose(callCredentials) { - return new ComposedChannelCredentialsImpl(this, callCredentials); - } - /** - * Return a new ChannelCredentials instance with a given set of credentials. - * The resulting instance can be used to construct a Channel that communicates - * over TLS. - * @param rootCerts The root certificate data. - * @param privateKey The client certificate private key, if available. - * @param certChain The client certificate key chain, if available. - * @param verifyOptions Additional options to modify certificate verification - */ - static createSsl(rootCerts, privateKey, certChain, verifyOptions) { - var _a; - verifyIsBufferOrNull(rootCerts, "Root certificate"); - verifyIsBufferOrNull(privateKey, "Private key"); - verifyIsBufferOrNull(certChain, "Certificate chain"); - if (privateKey && !certChain) { - throw new Error("Private key must be given with accompanying certificate chain"); - } - if (!privateKey && certChain) { - throw new Error("Certificate chain must be given with accompanying private key"); - } - const secureContext = (0, tls_1.createSecureContext)({ - ca: (_a = rootCerts !== null && rootCerts !== void 0 ? rootCerts : (0, tls_helpers_1.getDefaultRootsData)()) !== null && _a !== void 0 ? _a : void 0, - key: privateKey !== null && privateKey !== void 0 ? privateKey : void 0, - cert: certChain !== null && certChain !== void 0 ? certChain : void 0, - ciphers: tls_helpers_1.CIPHER_SUITES - }); - return new SecureChannelCredentialsImpl(secureContext, verifyOptions !== null && verifyOptions !== void 0 ? verifyOptions : {}); - } - /** - * Return a new ChannelCredentials instance with credentials created using - * the provided secureContext. The resulting instances can be used to - * construct a Channel that communicates over TLS. gRPC will not override - * anything in the provided secureContext, so the environment variables - * GRPC_SSL_CIPHER_SUITES and GRPC_DEFAULT_SSL_ROOTS_FILE_PATH will - * not be applied. - * @param secureContext The return value of tls.createSecureContext() - * @param verifyOptions Additional options to modify certificate verification - */ - static createFromSecureContext(secureContext, verifyOptions) { - return new SecureChannelCredentialsImpl(secureContext, verifyOptions !== null && verifyOptions !== void 0 ? verifyOptions : {}); - } - /** - * Return a new ChannelCredentials instance with no credentials. - */ - static createInsecure() { - return new InsecureChannelCredentialsImpl(); - } - }; - exports2.ChannelCredentials = ChannelCredentials; - var InsecureChannelCredentialsImpl = class _InsecureChannelCredentialsImpl extends ChannelCredentials { - constructor() { - super(); - } - compose(callCredentials) { - throw new Error("Cannot compose insecure credentials"); - } - _isSecure() { - return false; - } - _equals(other) { - return other instanceof _InsecureChannelCredentialsImpl; - } - _createSecureConnector(channelTarget, options, callCredentials) { - return { - connect(socket) { - return Promise.resolve({ - socket, - secure: false - }); - }, - waitForReady: () => { - return Promise.resolve(); - }, - getCallCredentials: () => { - return callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty(); - }, - destroy() { - } - }; - } - }; - function getConnectionOptions(secureContext, verifyOptions, channelTarget, options) { - var _a, _b; - const connectionOptions = { - secureContext - }; - let realTarget = channelTarget; - if ("grpc.http_connect_target" in options) { - const parsedTarget = (0, uri_parser_1.parseUri)(options["grpc.http_connect_target"]); - if (parsedTarget) { - realTarget = parsedTarget; - } - } - const targetPath = (0, resolver_1.getDefaultAuthority)(realTarget); - const hostPort = (0, uri_parser_1.splitHostPort)(targetPath); - const remoteHost = (_a = hostPort === null || hostPort === void 0 ? void 0 : hostPort.host) !== null && _a !== void 0 ? _a : targetPath; - connectionOptions.host = remoteHost; - if (verifyOptions.checkServerIdentity) { - connectionOptions.checkServerIdentity = verifyOptions.checkServerIdentity; - } - if (verifyOptions.rejectUnauthorized !== void 0) { - connectionOptions.rejectUnauthorized = verifyOptions.rejectUnauthorized; - } - connectionOptions.ALPNProtocols = ["h2"]; - if (options["grpc.ssl_target_name_override"]) { - const sslTargetNameOverride = options["grpc.ssl_target_name_override"]; - const originalCheckServerIdentity = (_b = connectionOptions.checkServerIdentity) !== null && _b !== void 0 ? _b : tls_1.checkServerIdentity; - connectionOptions.checkServerIdentity = (host, cert) => { - return originalCheckServerIdentity(sslTargetNameOverride, cert); - }; - connectionOptions.servername = sslTargetNameOverride; - } else { - connectionOptions.servername = remoteHost; - } - if (options["grpc-node.tls_enable_trace"]) { - connectionOptions.enableTrace = true; - } - return connectionOptions; - } - var SecureConnectorImpl = class { - constructor(connectionOptions, callCredentials) { - this.connectionOptions = connectionOptions; - this.callCredentials = callCredentials; - } - connect(socket) { - const tlsConnectOptions = Object.assign({ socket }, this.connectionOptions); - return new Promise((resolve, reject) => { - const tlsSocket = (0, tls_1.connect)(tlsConnectOptions, () => { - var _a; - if (((_a = this.connectionOptions.rejectUnauthorized) !== null && _a !== void 0 ? _a : true) && !tlsSocket.authorized) { - reject(tlsSocket.authorizationError); - return; - } - resolve({ - socket: tlsSocket, - secure: true - }); - }); - tlsSocket.on("error", (error3) => { - reject(error3); - }); - }); - } - waitForReady() { - return Promise.resolve(); - } - getCallCredentials() { - return this.callCredentials; - } - destroy() { - } - }; - var SecureChannelCredentialsImpl = class _SecureChannelCredentialsImpl extends ChannelCredentials { - constructor(secureContext, verifyOptions) { - super(); - this.secureContext = secureContext; - this.verifyOptions = verifyOptions; - } - _isSecure() { - return true; - } - _equals(other) { - if (this === other) { - return true; - } - if (other instanceof _SecureChannelCredentialsImpl) { - return this.secureContext === other.secureContext && this.verifyOptions.checkServerIdentity === other.verifyOptions.checkServerIdentity; - } else { - return false; - } - } - _createSecureConnector(channelTarget, options, callCredentials) { - const connectionOptions = getConnectionOptions(this.secureContext, this.verifyOptions, channelTarget, options); - return new SecureConnectorImpl(connectionOptions, callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty()); - } - }; - var CertificateProviderChannelCredentialsImpl = class _CertificateProviderChannelCredentialsImpl extends ChannelCredentials { - constructor(caCertificateProvider, identityCertificateProvider, verifyOptions) { - super(); - this.caCertificateProvider = caCertificateProvider; - this.identityCertificateProvider = identityCertificateProvider; - this.verifyOptions = verifyOptions; - this.refcount = 0; - this.latestCaUpdate = void 0; - this.latestIdentityUpdate = void 0; - this.caCertificateUpdateListener = this.handleCaCertificateUpdate.bind(this); - this.identityCertificateUpdateListener = this.handleIdentityCertitificateUpdate.bind(this); - this.secureContextWatchers = []; - } - _isSecure() { - return true; - } - _equals(other) { - var _a, _b; - if (this === other) { - return true; - } - if (other instanceof _CertificateProviderChannelCredentialsImpl) { - return this.caCertificateProvider === other.caCertificateProvider && this.identityCertificateProvider === other.identityCertificateProvider && ((_a = this.verifyOptions) === null || _a === void 0 ? void 0 : _a.checkServerIdentity) === ((_b = other.verifyOptions) === null || _b === void 0 ? void 0 : _b.checkServerIdentity); - } else { - return false; - } - } - ref() { - var _a; - if (this.refcount === 0) { - this.caCertificateProvider.addCaCertificateListener(this.caCertificateUpdateListener); - (_a = this.identityCertificateProvider) === null || _a === void 0 ? void 0 : _a.addIdentityCertificateListener(this.identityCertificateUpdateListener); - } - this.refcount += 1; - } - unref() { - var _a; - this.refcount -= 1; - if (this.refcount === 0) { - this.caCertificateProvider.removeCaCertificateListener(this.caCertificateUpdateListener); - (_a = this.identityCertificateProvider) === null || _a === void 0 ? void 0 : _a.removeIdentityCertificateListener(this.identityCertificateUpdateListener); - } - } - _createSecureConnector(channelTarget, options, callCredentials) { - this.ref(); - return new _CertificateProviderChannelCredentialsImpl.SecureConnectorImpl(this, channelTarget, options, callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty()); - } - maybeUpdateWatchers() { - if (this.hasReceivedUpdates()) { - for (const watcher of this.secureContextWatchers) { - watcher(this.getLatestSecureContext()); - } - this.secureContextWatchers = []; - } - } - handleCaCertificateUpdate(update) { - this.latestCaUpdate = update; - this.maybeUpdateWatchers(); - } - handleIdentityCertitificateUpdate(update) { - this.latestIdentityUpdate = update; - this.maybeUpdateWatchers(); - } - hasReceivedUpdates() { - if (this.latestCaUpdate === void 0) { - return false; - } - if (this.identityCertificateProvider && this.latestIdentityUpdate === void 0) { - return false; - } - return true; - } - getSecureContext() { - if (this.hasReceivedUpdates()) { - return Promise.resolve(this.getLatestSecureContext()); - } else { - return new Promise((resolve) => { - this.secureContextWatchers.push(resolve); - }); - } - } - getLatestSecureContext() { - var _a, _b; - if (!this.latestCaUpdate) { - return null; - } - if (this.identityCertificateProvider !== null && !this.latestIdentityUpdate) { - return null; - } - try { - return (0, tls_1.createSecureContext)({ - ca: this.latestCaUpdate.caCertificate, - key: (_a = this.latestIdentityUpdate) === null || _a === void 0 ? void 0 : _a.privateKey, - cert: (_b = this.latestIdentityUpdate) === null || _b === void 0 ? void 0 : _b.certificate, - ciphers: tls_helpers_1.CIPHER_SUITES - }); - } catch (e) { - (0, logging_1.log)(constants_1.LogVerbosity.ERROR, "Failed to createSecureContext with error " + e.message); - return null; - } - } - }; - CertificateProviderChannelCredentialsImpl.SecureConnectorImpl = class { - constructor(parent, channelTarget, options, callCredentials) { - this.parent = parent; - this.channelTarget = channelTarget; - this.options = options; - this.callCredentials = callCredentials; - } - connect(socket) { - return new Promise((resolve, reject) => { - const secureContext = this.parent.getLatestSecureContext(); - if (!secureContext) { - reject(new Error("Failed to load credentials")); - return; - } - if (socket.closed) { - reject(new Error("Socket closed while loading credentials")); - } - const connnectionOptions = getConnectionOptions(secureContext, this.parent.verifyOptions, this.channelTarget, this.options); - const tlsConnectOptions = Object.assign({ socket }, connnectionOptions); - const closeCallback = () => { - reject(new Error("Socket closed")); - }; - const errorCallback = (error3) => { - reject(error3); - }; - const tlsSocket = (0, tls_1.connect)(tlsConnectOptions, () => { - var _a; - tlsSocket.removeListener("close", closeCallback); - tlsSocket.removeListener("error", errorCallback); - if (((_a = this.parent.verifyOptions.rejectUnauthorized) !== null && _a !== void 0 ? _a : true) && !tlsSocket.authorized) { - reject(tlsSocket.authorizationError); - return; - } - resolve({ - socket: tlsSocket, - secure: true - }); - }); - tlsSocket.once("close", closeCallback); - tlsSocket.once("error", errorCallback); - }); - } - async waitForReady() { - await this.parent.getSecureContext(); - } - getCallCredentials() { - return this.callCredentials; - } - destroy() { - this.parent.unref(); - } - }; - function createCertificateProviderChannelCredentials(caCertificateProvider, identityCertificateProvider, verifyOptions) { - return new CertificateProviderChannelCredentialsImpl(caCertificateProvider, identityCertificateProvider, verifyOptions !== null && verifyOptions !== void 0 ? verifyOptions : {}); - } - var ComposedChannelCredentialsImpl = class _ComposedChannelCredentialsImpl extends ChannelCredentials { - constructor(channelCredentials, callCredentials) { - super(); - this.channelCredentials = channelCredentials; - this.callCredentials = callCredentials; - if (!channelCredentials._isSecure()) { - throw new Error("Cannot compose insecure credentials"); - } - } - compose(callCredentials) { - const combinedCallCredentials = this.callCredentials.compose(callCredentials); - return new _ComposedChannelCredentialsImpl(this.channelCredentials, combinedCallCredentials); - } - _isSecure() { - return true; - } - _equals(other) { - if (this === other) { - return true; - } - if (other instanceof _ComposedChannelCredentialsImpl) { - return this.channelCredentials._equals(other.channelCredentials) && this.callCredentials._equals(other.callCredentials); - } else { - return false; - } - } - _createSecureConnector(channelTarget, options, callCredentials) { - const combinedCallCredentials = this.callCredentials.compose(callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty()); - return this.channelCredentials._createSecureConnector(channelTarget, options, combinedCallCredentials); - } - }; - } -}); - -// node_modules/@grpc/grpc-js/build/src/load-balancer.js -var require_load_balancer = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/load-balancer.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createChildChannelControlHelper = createChildChannelControlHelper; - exports2.registerLoadBalancerType = registerLoadBalancerType; - exports2.registerDefaultLoadBalancerType = registerDefaultLoadBalancerType; - exports2.createLoadBalancer = createLoadBalancer; - exports2.isLoadBalancerNameRegistered = isLoadBalancerNameRegistered; - exports2.parseLoadBalancingConfig = parseLoadBalancingConfig; - exports2.getDefaultConfig = getDefaultConfig; - exports2.selectLbConfigFromList = selectLbConfigFromList; - var logging_1 = require_logging(); - var constants_1 = require_constants7(); - function createChildChannelControlHelper(parent, overrides) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; - return { - createSubchannel: (_b = (_a = overrides.createSubchannel) === null || _a === void 0 ? void 0 : _a.bind(overrides)) !== null && _b !== void 0 ? _b : parent.createSubchannel.bind(parent), - updateState: (_d = (_c = overrides.updateState) === null || _c === void 0 ? void 0 : _c.bind(overrides)) !== null && _d !== void 0 ? _d : parent.updateState.bind(parent), - requestReresolution: (_f = (_e = overrides.requestReresolution) === null || _e === void 0 ? void 0 : _e.bind(overrides)) !== null && _f !== void 0 ? _f : parent.requestReresolution.bind(parent), - addChannelzChild: (_h = (_g = overrides.addChannelzChild) === null || _g === void 0 ? void 0 : _g.bind(overrides)) !== null && _h !== void 0 ? _h : parent.addChannelzChild.bind(parent), - removeChannelzChild: (_k = (_j = overrides.removeChannelzChild) === null || _j === void 0 ? void 0 : _j.bind(overrides)) !== null && _k !== void 0 ? _k : parent.removeChannelzChild.bind(parent) - }; - } - var registeredLoadBalancerTypes = {}; - var defaultLoadBalancerType = null; - function registerLoadBalancerType(typeName, loadBalancerType, loadBalancingConfigType) { - registeredLoadBalancerTypes[typeName] = { - LoadBalancer: loadBalancerType, - LoadBalancingConfig: loadBalancingConfigType - }; - } - function registerDefaultLoadBalancerType(typeName) { - defaultLoadBalancerType = typeName; - } - function createLoadBalancer(config, channelControlHelper) { - const typeName = config.getLoadBalancerName(); - if (typeName in registeredLoadBalancerTypes) { - return new registeredLoadBalancerTypes[typeName].LoadBalancer(channelControlHelper); - } else { - return null; - } - } - function isLoadBalancerNameRegistered(typeName) { - return typeName in registeredLoadBalancerTypes; - } - function parseLoadBalancingConfig(rawConfig) { - const keys = Object.keys(rawConfig); - if (keys.length !== 1) { - throw new Error("Provided load balancing config has multiple conflicting entries"); - } - const typeName = keys[0]; - if (typeName in registeredLoadBalancerTypes) { - try { - return registeredLoadBalancerTypes[typeName].LoadBalancingConfig.createFromJson(rawConfig[typeName]); - } catch (e) { - throw new Error(`${typeName}: ${e.message}`); - } - } else { - throw new Error(`Unrecognized load balancing config name ${typeName}`); - } - } - function getDefaultConfig() { - if (!defaultLoadBalancerType) { - throw new Error("No default load balancer type registered"); - } - return new registeredLoadBalancerTypes[defaultLoadBalancerType].LoadBalancingConfig(); - } - function selectLbConfigFromList(configs, fallbackTodefault = false) { - for (const config of configs) { - try { - return parseLoadBalancingConfig(config); - } catch (e) { - (0, logging_1.log)(constants_1.LogVerbosity.DEBUG, "Config parsing failed with error", e.message); - continue; - } - } - if (fallbackTodefault) { - if (defaultLoadBalancerType) { - return new registeredLoadBalancerTypes[defaultLoadBalancerType].LoadBalancingConfig(); - } else { - return null; - } - } else { - return null; - } - } - } -}); - -// node_modules/@grpc/grpc-js/build/src/service-config.js -var require_service_config = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/service-config.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.validateRetryThrottling = validateRetryThrottling; - exports2.validateServiceConfig = validateServiceConfig; - exports2.extractAndSelectServiceConfig = extractAndSelectServiceConfig; - var os = require("os"); - var constants_1 = require_constants7(); - var DURATION_REGEX = /^\d+(\.\d{1,9})?s$/; - var CLIENT_LANGUAGE_STRING = "node"; - function validateName(obj) { - if ("service" in obj && obj.service !== "") { - if (typeof obj.service !== "string") { - throw new Error(`Invalid method config name: invalid service: expected type string, got ${typeof obj.service}`); - } - if ("method" in obj && obj.method !== "") { - if (typeof obj.method !== "string") { - throw new Error(`Invalid method config name: invalid method: expected type string, got ${typeof obj.service}`); - } - return { - service: obj.service, - method: obj.method - }; - } else { - return { - service: obj.service - }; - } - } else { - if ("method" in obj && obj.method !== void 0) { - throw new Error(`Invalid method config name: method set with empty or unset service`); - } - return {}; - } - } - function validateRetryPolicy(obj) { - if (!("maxAttempts" in obj) || !Number.isInteger(obj.maxAttempts) || obj.maxAttempts < 2) { - throw new Error("Invalid method config retry policy: maxAttempts must be an integer at least 2"); - } - if (!("initialBackoff" in obj) || typeof obj.initialBackoff !== "string" || !DURATION_REGEX.test(obj.initialBackoff)) { - throw new Error("Invalid method config retry policy: initialBackoff must be a string consisting of a positive integer or decimal followed by s"); - } - if (!("maxBackoff" in obj) || typeof obj.maxBackoff !== "string" || !DURATION_REGEX.test(obj.maxBackoff)) { - throw new Error("Invalid method config retry policy: maxBackoff must be a string consisting of a positive integer or decimal followed by s"); - } - if (!("backoffMultiplier" in obj) || typeof obj.backoffMultiplier !== "number" || obj.backoffMultiplier <= 0) { - throw new Error("Invalid method config retry policy: backoffMultiplier must be a number greater than 0"); - } - if (!("retryableStatusCodes" in obj && Array.isArray(obj.retryableStatusCodes))) { - throw new Error("Invalid method config retry policy: retryableStatusCodes is required"); - } - if (obj.retryableStatusCodes.length === 0) { - throw new Error("Invalid method config retry policy: retryableStatusCodes must be non-empty"); - } - for (const value of obj.retryableStatusCodes) { - if (typeof value === "number") { - if (!Object.values(constants_1.Status).includes(value)) { - throw new Error("Invalid method config retry policy: retryableStatusCodes value not in status code range"); - } - } else if (typeof value === "string") { - if (!Object.values(constants_1.Status).includes(value.toUpperCase())) { - throw new Error("Invalid method config retry policy: retryableStatusCodes value not a status code name"); - } - } else { - throw new Error("Invalid method config retry policy: retryableStatusCodes value must be a string or number"); - } - } - return { - maxAttempts: obj.maxAttempts, - initialBackoff: obj.initialBackoff, - maxBackoff: obj.maxBackoff, - backoffMultiplier: obj.backoffMultiplier, - retryableStatusCodes: obj.retryableStatusCodes - }; - } - function validateHedgingPolicy(obj) { - if (!("maxAttempts" in obj) || !Number.isInteger(obj.maxAttempts) || obj.maxAttempts < 2) { - throw new Error("Invalid method config hedging policy: maxAttempts must be an integer at least 2"); - } - if ("hedgingDelay" in obj && (typeof obj.hedgingDelay !== "string" || !DURATION_REGEX.test(obj.hedgingDelay))) { - throw new Error("Invalid method config hedging policy: hedgingDelay must be a string consisting of a positive integer followed by s"); - } - if ("nonFatalStatusCodes" in obj && Array.isArray(obj.nonFatalStatusCodes)) { - for (const value of obj.nonFatalStatusCodes) { - if (typeof value === "number") { - if (!Object.values(constants_1.Status).includes(value)) { - throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value not in status code range"); - } - } else if (typeof value === "string") { - if (!Object.values(constants_1.Status).includes(value.toUpperCase())) { - throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value not a status code name"); - } - } else { - throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value must be a string or number"); - } - } - } - const result = { - maxAttempts: obj.maxAttempts - }; - if (obj.hedgingDelay) { - result.hedgingDelay = obj.hedgingDelay; - } - if (obj.nonFatalStatusCodes) { - result.nonFatalStatusCodes = obj.nonFatalStatusCodes; - } - return result; - } - function validateMethodConfig(obj) { - var _a; - const result = { - name: [] - }; - if (!("name" in obj) || !Array.isArray(obj.name)) { - throw new Error("Invalid method config: invalid name array"); - } - for (const name of obj.name) { - result.name.push(validateName(name)); - } - if ("waitForReady" in obj) { - if (typeof obj.waitForReady !== "boolean") { - throw new Error("Invalid method config: invalid waitForReady"); - } - result.waitForReady = obj.waitForReady; - } - if ("timeout" in obj) { - if (typeof obj.timeout === "object") { - if (!("seconds" in obj.timeout) || !(typeof obj.timeout.seconds === "number")) { - throw new Error("Invalid method config: invalid timeout.seconds"); - } - if (!("nanos" in obj.timeout) || !(typeof obj.timeout.nanos === "number")) { - throw new Error("Invalid method config: invalid timeout.nanos"); - } - result.timeout = obj.timeout; - } else if (typeof obj.timeout === "string" && DURATION_REGEX.test(obj.timeout)) { - const timeoutParts = obj.timeout.substring(0, obj.timeout.length - 1).split("."); - result.timeout = { - seconds: timeoutParts[0] | 0, - nanos: ((_a = timeoutParts[1]) !== null && _a !== void 0 ? _a : 0) | 0 - }; - } else { - throw new Error("Invalid method config: invalid timeout"); - } - } - if ("maxRequestBytes" in obj) { - if (typeof obj.maxRequestBytes !== "number") { - throw new Error("Invalid method config: invalid maxRequestBytes"); - } - result.maxRequestBytes = obj.maxRequestBytes; - } - if ("maxResponseBytes" in obj) { - if (typeof obj.maxResponseBytes !== "number") { - throw new Error("Invalid method config: invalid maxRequestBytes"); - } - result.maxResponseBytes = obj.maxResponseBytes; - } - if ("retryPolicy" in obj) { - if ("hedgingPolicy" in obj) { - throw new Error("Invalid method config: retryPolicy and hedgingPolicy cannot both be specified"); - } else { - result.retryPolicy = validateRetryPolicy(obj.retryPolicy); - } - } else if ("hedgingPolicy" in obj) { - result.hedgingPolicy = validateHedgingPolicy(obj.hedgingPolicy); - } - return result; - } - function validateRetryThrottling(obj) { - if (!("maxTokens" in obj) || typeof obj.maxTokens !== "number" || obj.maxTokens <= 0 || obj.maxTokens > 1e3) { - throw new Error("Invalid retryThrottling: maxTokens must be a number in (0, 1000]"); - } - if (!("tokenRatio" in obj) || typeof obj.tokenRatio !== "number" || obj.tokenRatio <= 0) { - throw new Error("Invalid retryThrottling: tokenRatio must be a number greater than 0"); - } - return { - maxTokens: +obj.maxTokens.toFixed(3), - tokenRatio: +obj.tokenRatio.toFixed(3) - }; - } - function validateLoadBalancingConfig(obj) { - if (!(typeof obj === "object" && obj !== null)) { - throw new Error(`Invalid loadBalancingConfig: unexpected type ${typeof obj}`); - } - const keys = Object.keys(obj); - if (keys.length > 1) { - throw new Error(`Invalid loadBalancingConfig: unexpected multiple keys ${keys}`); - } - if (keys.length === 0) { - throw new Error("Invalid loadBalancingConfig: load balancing policy name required"); - } - return { - [keys[0]]: obj[keys[0]] - }; - } - function validateServiceConfig(obj) { - const result = { - loadBalancingConfig: [], - methodConfig: [] - }; - if ("loadBalancingPolicy" in obj) { - if (typeof obj.loadBalancingPolicy === "string") { - result.loadBalancingPolicy = obj.loadBalancingPolicy; - } else { - throw new Error("Invalid service config: invalid loadBalancingPolicy"); - } - } - if ("loadBalancingConfig" in obj) { - if (Array.isArray(obj.loadBalancingConfig)) { - for (const config of obj.loadBalancingConfig) { - result.loadBalancingConfig.push(validateLoadBalancingConfig(config)); - } - } else { - throw new Error("Invalid service config: invalid loadBalancingConfig"); - } - } - if ("methodConfig" in obj) { - if (Array.isArray(obj.methodConfig)) { - for (const methodConfig of obj.methodConfig) { - result.methodConfig.push(validateMethodConfig(methodConfig)); - } - } - } - if ("retryThrottling" in obj) { - result.retryThrottling = validateRetryThrottling(obj.retryThrottling); - } - const seenMethodNames = []; - for (const methodConfig of result.methodConfig) { - for (const name of methodConfig.name) { - for (const seenName of seenMethodNames) { - if (name.service === seenName.service && name.method === seenName.method) { - throw new Error(`Invalid service config: duplicate name ${name.service}/${name.method}`); - } - } - seenMethodNames.push(name); - } - } - return result; - } - function validateCanaryConfig(obj) { - if (!("serviceConfig" in obj)) { - throw new Error("Invalid service config choice: missing service config"); - } - const result = { - serviceConfig: validateServiceConfig(obj.serviceConfig) - }; - if ("clientLanguage" in obj) { - if (Array.isArray(obj.clientLanguage)) { - result.clientLanguage = []; - for (const lang of obj.clientLanguage) { - if (typeof lang === "string") { - result.clientLanguage.push(lang); - } else { - throw new Error("Invalid service config choice: invalid clientLanguage"); - } - } - } else { - throw new Error("Invalid service config choice: invalid clientLanguage"); - } - } - if ("clientHostname" in obj) { - if (Array.isArray(obj.clientHostname)) { - result.clientHostname = []; - for (const lang of obj.clientHostname) { - if (typeof lang === "string") { - result.clientHostname.push(lang); - } else { - throw new Error("Invalid service config choice: invalid clientHostname"); - } - } - } else { - throw new Error("Invalid service config choice: invalid clientHostname"); - } - } - if ("percentage" in obj) { - if (typeof obj.percentage === "number" && 0 <= obj.percentage && obj.percentage <= 100) { - result.percentage = obj.percentage; - } else { - throw new Error("Invalid service config choice: invalid percentage"); - } - } - const allowedFields = [ - "clientLanguage", - "percentage", - "clientHostname", - "serviceConfig" - ]; - for (const field in obj) { - if (!allowedFields.includes(field)) { - throw new Error(`Invalid service config choice: unexpected field ${field}`); - } - } - return result; - } - function validateAndSelectCanaryConfig(obj, percentage) { - if (!Array.isArray(obj)) { - throw new Error("Invalid service config list"); - } - for (const config of obj) { - const validatedConfig = validateCanaryConfig(config); - if (typeof validatedConfig.percentage === "number" && percentage > validatedConfig.percentage) { - continue; - } - if (Array.isArray(validatedConfig.clientHostname)) { - let hostnameMatched = false; - for (const hostname of validatedConfig.clientHostname) { - if (hostname === os.hostname()) { - hostnameMatched = true; - } - } - if (!hostnameMatched) { - continue; - } - } - if (Array.isArray(validatedConfig.clientLanguage)) { - let languageMatched = false; - for (const language of validatedConfig.clientLanguage) { - if (language === CLIENT_LANGUAGE_STRING) { - languageMatched = true; - } - } - if (!languageMatched) { - continue; - } - } - return validatedConfig.serviceConfig; - } - throw new Error("No matching service config found"); - } - function extractAndSelectServiceConfig(txtRecord, percentage) { - for (const record of txtRecord) { - if (record.length > 0 && record[0].startsWith("grpc_config=")) { - const recordString = record.join("").substring("grpc_config=".length); - const recordJson = JSON.parse(recordString); - return validateAndSelectCanaryConfig(recordJson, percentage); - } - } - return null; - } - } -}); - -// node_modules/@grpc/grpc-js/build/src/connectivity-state.js -var require_connectivity_state = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/connectivity-state.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ConnectivityState = void 0; - var ConnectivityState; - (function(ConnectivityState2) { - ConnectivityState2[ConnectivityState2["IDLE"] = 0] = "IDLE"; - ConnectivityState2[ConnectivityState2["CONNECTING"] = 1] = "CONNECTING"; - ConnectivityState2[ConnectivityState2["READY"] = 2] = "READY"; - ConnectivityState2[ConnectivityState2["TRANSIENT_FAILURE"] = 3] = "TRANSIENT_FAILURE"; - ConnectivityState2[ConnectivityState2["SHUTDOWN"] = 4] = "SHUTDOWN"; - })(ConnectivityState || (exports2.ConnectivityState = ConnectivityState = {})); - } -}); - -// node_modules/@grpc/grpc-js/build/src/picker.js -var require_picker = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/picker.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.QueuePicker = exports2.UnavailablePicker = exports2.PickResultType = void 0; - var metadata_1 = require_metadata(); - var constants_1 = require_constants7(); - var PickResultType; - (function(PickResultType2) { - PickResultType2[PickResultType2["COMPLETE"] = 0] = "COMPLETE"; - PickResultType2[PickResultType2["QUEUE"] = 1] = "QUEUE"; - PickResultType2[PickResultType2["TRANSIENT_FAILURE"] = 2] = "TRANSIENT_FAILURE"; - PickResultType2[PickResultType2["DROP"] = 3] = "DROP"; - })(PickResultType || (exports2.PickResultType = PickResultType = {})); - var UnavailablePicker = class { - constructor(status) { - this.status = Object.assign({ code: constants_1.Status.UNAVAILABLE, details: "No connection established", metadata: new metadata_1.Metadata() }, status); - } - pick(pickArgs) { - return { - pickResultType: PickResultType.TRANSIENT_FAILURE, - subchannel: null, - status: this.status, - onCallStarted: null, - onCallEnded: null - }; - } - }; - exports2.UnavailablePicker = UnavailablePicker; - var QueuePicker = class { - // Constructed with a load balancer. Calls exitIdle on it the first time pick is called - constructor(loadBalancer, childPicker) { - this.loadBalancer = loadBalancer; - this.childPicker = childPicker; - this.calledExitIdle = false; - } - pick(pickArgs) { - if (!this.calledExitIdle) { - process.nextTick(() => { - this.loadBalancer.exitIdle(); - }); - this.calledExitIdle = true; - } - if (this.childPicker) { - return this.childPicker.pick(pickArgs); - } else { - return { - pickResultType: PickResultType.QUEUE, - subchannel: null, - status: null, - onCallStarted: null, - onCallEnded: null - }; - } - } - }; - exports2.QueuePicker = QueuePicker; - } -}); - -// node_modules/@grpc/grpc-js/build/src/backoff-timeout.js -var require_backoff_timeout = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/backoff-timeout.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BackoffTimeout = void 0; - var constants_1 = require_constants7(); - var logging = require_logging(); - var TRACER_NAME = "backoff"; - var INITIAL_BACKOFF_MS = 1e3; - var BACKOFF_MULTIPLIER = 1.6; - var MAX_BACKOFF_MS = 12e4; - var BACKOFF_JITTER = 0.2; - function uniformRandom(min, max) { - return Math.random() * (max - min) + min; - } - var BackoffTimeout = class _BackoffTimeout { - constructor(callback, options) { - this.callback = callback; - this.initialDelay = INITIAL_BACKOFF_MS; - this.multiplier = BACKOFF_MULTIPLIER; - this.maxDelay = MAX_BACKOFF_MS; - this.jitter = BACKOFF_JITTER; - this.running = false; - this.hasRef = true; - this.startTime = /* @__PURE__ */ new Date(); - this.endTime = /* @__PURE__ */ new Date(); - this.id = _BackoffTimeout.getNextId(); - if (options) { - if (options.initialDelay) { - this.initialDelay = options.initialDelay; - } - if (options.multiplier) { - this.multiplier = options.multiplier; - } - if (options.jitter) { - this.jitter = options.jitter; - } - if (options.maxDelay) { - this.maxDelay = options.maxDelay; - } - } - this.trace("constructed initialDelay=" + this.initialDelay + " multiplier=" + this.multiplier + " jitter=" + this.jitter + " maxDelay=" + this.maxDelay); - this.nextDelay = this.initialDelay; - this.timerId = setTimeout(() => { - }, 0); - clearTimeout(this.timerId); - } - static getNextId() { - return this.nextId++; - } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "{" + this.id + "} " + text); - } - runTimer(delay) { - var _a, _b; - this.trace("runTimer(delay=" + delay + ")"); - this.endTime = this.startTime; - this.endTime.setMilliseconds(this.endTime.getMilliseconds() + delay); - clearTimeout(this.timerId); - this.timerId = setTimeout(() => { - this.trace("timer fired"); - this.running = false; - this.callback(); - }, delay); - if (!this.hasRef) { - (_b = (_a = this.timerId).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - } - } - /** - * Call the callback after the current amount of delay time - */ - runOnce() { - this.trace("runOnce()"); - this.running = true; - this.startTime = /* @__PURE__ */ new Date(); - this.runTimer(this.nextDelay); - const nextBackoff = Math.min(this.nextDelay * this.multiplier, this.maxDelay); - const jitterMagnitude = nextBackoff * this.jitter; - this.nextDelay = nextBackoff + uniformRandom(-jitterMagnitude, jitterMagnitude); - } - /** - * Stop the timer. The callback will not be called until `runOnce` is called - * again. - */ - stop() { - this.trace("stop()"); - clearTimeout(this.timerId); - this.running = false; - } - /** - * Reset the delay time to its initial value. If the timer is still running, - * retroactively apply that reset to the current timer. - */ - reset() { - this.trace("reset() running=" + this.running); - this.nextDelay = this.initialDelay; - if (this.running) { - const now = /* @__PURE__ */ new Date(); - const newEndTime = this.startTime; - newEndTime.setMilliseconds(newEndTime.getMilliseconds() + this.nextDelay); - clearTimeout(this.timerId); - if (now < newEndTime) { - this.runTimer(newEndTime.getTime() - now.getTime()); - } else { - this.running = false; - } - } - } - /** - * Check whether the timer is currently running. - */ - isRunning() { - return this.running; - } - /** - * Set that while the timer is running, it should keep the Node process - * running. - */ - ref() { - var _a, _b; - this.hasRef = true; - (_b = (_a = this.timerId).ref) === null || _b === void 0 ? void 0 : _b.call(_a); - } - /** - * Set that while the timer is running, it should not keep the Node process - * running. - */ - unref() { - var _a, _b; - this.hasRef = false; - (_b = (_a = this.timerId).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - } - /** - * Get the approximate timestamp of when the timer will fire. Only valid if - * this.isRunning() is true. - */ - getEndTime() { - return this.endTime; - } - }; - exports2.BackoffTimeout = BackoffTimeout; - BackoffTimeout.nextId = 0; - } -}); - -// node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.js -var require_load_balancer_child_handler = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ChildLoadBalancerHandler = void 0; - var load_balancer_1 = require_load_balancer(); - var connectivity_state_1 = require_connectivity_state(); - var TYPE_NAME = "child_load_balancer_helper"; - var ChildLoadBalancerHandler = class { - constructor(channelControlHelper) { - this.channelControlHelper = channelControlHelper; - this.currentChild = null; - this.pendingChild = null; - this.latestConfig = null; - this.ChildPolicyHelper = class { - constructor(parent) { - this.parent = parent; - this.child = null; - } - createSubchannel(subchannelAddress, subchannelArgs) { - return this.parent.channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs); - } - updateState(connectivityState, picker, errorMessage) { - var _a; - if (this.calledByPendingChild()) { - if (connectivityState === connectivity_state_1.ConnectivityState.CONNECTING) { - return; - } - (_a = this.parent.currentChild) === null || _a === void 0 ? void 0 : _a.destroy(); - this.parent.currentChild = this.parent.pendingChild; - this.parent.pendingChild = null; - } else if (!this.calledByCurrentChild()) { - return; - } - this.parent.channelControlHelper.updateState(connectivityState, picker, errorMessage); - } - requestReresolution() { - var _a; - const latestChild = (_a = this.parent.pendingChild) !== null && _a !== void 0 ? _a : this.parent.currentChild; - if (this.child === latestChild) { - this.parent.channelControlHelper.requestReresolution(); - } - } - setChild(newChild) { - this.child = newChild; - } - addChannelzChild(child) { - this.parent.channelControlHelper.addChannelzChild(child); - } - removeChannelzChild(child) { - this.parent.channelControlHelper.removeChannelzChild(child); - } - calledByPendingChild() { - return this.child === this.parent.pendingChild; - } - calledByCurrentChild() { - return this.child === this.parent.currentChild; - } - }; - } - configUpdateRequiresNewPolicyInstance(oldConfig, newConfig) { - return oldConfig.getLoadBalancerName() !== newConfig.getLoadBalancerName(); - } - /** - * Prerequisites: lbConfig !== null and lbConfig.name is registered - * @param endpointList - * @param lbConfig - * @param attributes - */ - updateAddressList(endpointList, lbConfig, options, resolutionNote) { - let childToUpdate; - if (this.currentChild === null || this.latestConfig === null || this.configUpdateRequiresNewPolicyInstance(this.latestConfig, lbConfig)) { - const newHelper = new this.ChildPolicyHelper(this); - const newChild = (0, load_balancer_1.createLoadBalancer)(lbConfig, newHelper); - newHelper.setChild(newChild); - if (this.currentChild === null) { - this.currentChild = newChild; - childToUpdate = this.currentChild; - } else { - if (this.pendingChild) { - this.pendingChild.destroy(); - } - this.pendingChild = newChild; - childToUpdate = this.pendingChild; - } - } else { - if (this.pendingChild === null) { - childToUpdate = this.currentChild; - } else { - childToUpdate = this.pendingChild; - } - } - this.latestConfig = lbConfig; - return childToUpdate.updateAddressList(endpointList, lbConfig, options, resolutionNote); - } - exitIdle() { - if (this.currentChild) { - this.currentChild.exitIdle(); - if (this.pendingChild) { - this.pendingChild.exitIdle(); - } - } - } - resetBackoff() { - if (this.currentChild) { - this.currentChild.resetBackoff(); - if (this.pendingChild) { - this.pendingChild.resetBackoff(); - } - } - } - destroy() { - if (this.currentChild) { - this.currentChild.destroy(); - this.currentChild = null; - } - if (this.pendingChild) { - this.pendingChild.destroy(); - this.pendingChild = null; - } - } - getTypeName() { - return TYPE_NAME; - } - }; - exports2.ChildLoadBalancerHandler = ChildLoadBalancerHandler; - } -}); - -// node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.js -var require_resolving_load_balancer = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ResolvingLoadBalancer = void 0; - var load_balancer_1 = require_load_balancer(); - var service_config_1 = require_service_config(); - var connectivity_state_1 = require_connectivity_state(); - var resolver_1 = require_resolver(); - var picker_1 = require_picker(); - var backoff_timeout_1 = require_backoff_timeout(); - var constants_1 = require_constants7(); - var metadata_1 = require_metadata(); - var logging = require_logging(); - var constants_2 = require_constants7(); - var uri_parser_1 = require_uri_parser(); - var load_balancer_child_handler_1 = require_load_balancer_child_handler(); - var TRACER_NAME = "resolving_load_balancer"; - function trace(text) { - logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, text); - } - var NAME_MATCH_LEVEL_ORDER = [ - "SERVICE_AND_METHOD", - "SERVICE", - "EMPTY" - ]; - function hasMatchingName(service, method, methodConfig, matchLevel) { - for (const name of methodConfig.name) { - switch (matchLevel) { - case "EMPTY": - if (!name.service && !name.method) { - return true; - } - break; - case "SERVICE": - if (name.service === service && !name.method) { - return true; - } - break; - case "SERVICE_AND_METHOD": - if (name.service === service && name.method === method) { - return true; - } - } - } - return false; - } - function findMatchingConfig(service, method, methodConfigs, matchLevel) { - for (const config of methodConfigs) { - if (hasMatchingName(service, method, config, matchLevel)) { - return config; - } - } - return null; - } - function getDefaultConfigSelector(serviceConfig) { - return { - invoke(methodName, metadata) { - var _a, _b; - const splitName = methodName.split("/").filter((x) => x.length > 0); - const service = (_a = splitName[0]) !== null && _a !== void 0 ? _a : ""; - const method = (_b = splitName[1]) !== null && _b !== void 0 ? _b : ""; - if (serviceConfig && serviceConfig.methodConfig) { - for (const matchLevel of NAME_MATCH_LEVEL_ORDER) { - const matchingConfig = findMatchingConfig(service, method, serviceConfig.methodConfig, matchLevel); - if (matchingConfig) { - return { - methodConfig: matchingConfig, - pickInformation: {}, - status: constants_1.Status.OK, - dynamicFilterFactories: [] - }; - } - } - } - return { - methodConfig: { name: [] }, - pickInformation: {}, - status: constants_1.Status.OK, - dynamicFilterFactories: [] - }; - }, - unref() { - } - }; - } - var ResolvingLoadBalancer = class { - /** - * Wrapper class that behaves like a `LoadBalancer` and also handles name - * resolution internally. - * @param target The address of the backend to connect to. - * @param channelControlHelper `ChannelControlHelper` instance provided by - * this load balancer's owner. - * @param defaultServiceConfig The default service configuration to be used - * if none is provided by the name resolver. A `null` value indicates - * that the default behavior should be the default unconfigured behavior. - * In practice, that means using the "pick first" load balancer - * implmentation - */ - constructor(target, channelControlHelper, channelOptions, onSuccessfulResolution, onFailedResolution) { - this.target = target; - this.channelControlHelper = channelControlHelper; - this.channelOptions = channelOptions; - this.onSuccessfulResolution = onSuccessfulResolution; - this.onFailedResolution = onFailedResolution; - this.latestChildState = connectivity_state_1.ConnectivityState.IDLE; - this.latestChildPicker = new picker_1.QueuePicker(this); - this.latestChildErrorMessage = null; - this.currentState = connectivity_state_1.ConnectivityState.IDLE; - this.previousServiceConfig = null; - this.continueResolving = false; - if (channelOptions["grpc.service_config"]) { - this.defaultServiceConfig = (0, service_config_1.validateServiceConfig)(JSON.parse(channelOptions["grpc.service_config"])); - } else { - this.defaultServiceConfig = { - loadBalancingConfig: [], - methodConfig: [] - }; - } - this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null); - this.childLoadBalancer = new load_balancer_child_handler_1.ChildLoadBalancerHandler({ - createSubchannel: channelControlHelper.createSubchannel.bind(channelControlHelper), - requestReresolution: () => { - if (this.backoffTimeout.isRunning()) { - trace("requestReresolution delayed by backoff timer until " + this.backoffTimeout.getEndTime().toISOString()); - this.continueResolving = true; - } else { - this.updateResolution(); - } - }, - updateState: (newState, picker, errorMessage) => { - this.latestChildState = newState; - this.latestChildPicker = picker; - this.latestChildErrorMessage = errorMessage; - this.updateState(newState, picker, errorMessage); - }, - addChannelzChild: channelControlHelper.addChannelzChild.bind(channelControlHelper), - removeChannelzChild: channelControlHelper.removeChannelzChild.bind(channelControlHelper) - }); - this.innerResolver = (0, resolver_1.createResolver)(target, this.handleResolverResult.bind(this), channelOptions); - const backoffOptions = { - initialDelay: channelOptions["grpc.initial_reconnect_backoff_ms"], - maxDelay: channelOptions["grpc.max_reconnect_backoff_ms"] - }; - this.backoffTimeout = new backoff_timeout_1.BackoffTimeout(() => { - if (this.continueResolving) { - this.updateResolution(); - this.continueResolving = false; - } else { - this.updateState(this.latestChildState, this.latestChildPicker, this.latestChildErrorMessage); - } - }, backoffOptions); - this.backoffTimeout.unref(); - } - handleResolverResult(endpointList, attributes, serviceConfig, resolutionNote) { - var _a, _b; - this.backoffTimeout.stop(); - this.backoffTimeout.reset(); - let resultAccepted = true; - let workingServiceConfig = null; - if (serviceConfig === null) { - workingServiceConfig = this.defaultServiceConfig; - } else if (serviceConfig.ok) { - workingServiceConfig = serviceConfig.value; - } else { - if (this.previousServiceConfig !== null) { - workingServiceConfig = this.previousServiceConfig; - } else { - resultAccepted = false; - this.handleResolutionFailure(serviceConfig.error); - } - } - if (workingServiceConfig !== null) { - const workingConfigList = (_a = workingServiceConfig === null || workingServiceConfig === void 0 ? void 0 : workingServiceConfig.loadBalancingConfig) !== null && _a !== void 0 ? _a : []; - const loadBalancingConfig = (0, load_balancer_1.selectLbConfigFromList)(workingConfigList, true); - if (loadBalancingConfig === null) { - resultAccepted = false; - this.handleResolutionFailure({ - code: constants_1.Status.UNAVAILABLE, - details: "All load balancer options in service config are not compatible", - metadata: new metadata_1.Metadata() - }); - } else { - resultAccepted = this.childLoadBalancer.updateAddressList(endpointList, loadBalancingConfig, Object.assign(Object.assign({}, this.channelOptions), attributes), resolutionNote); - } - } - if (resultAccepted) { - this.onSuccessfulResolution(workingServiceConfig, (_b = attributes[resolver_1.CHANNEL_ARGS_CONFIG_SELECTOR_KEY]) !== null && _b !== void 0 ? _b : getDefaultConfigSelector(workingServiceConfig)); - } - return resultAccepted; - } - updateResolution() { - this.innerResolver.updateResolution(); - if (this.currentState === connectivity_state_1.ConnectivityState.IDLE) { - this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, this.latestChildPicker, this.latestChildErrorMessage); - } - this.backoffTimeout.runOnce(); - } - updateState(connectivityState, picker, errorMessage) { - trace((0, uri_parser_1.uriToString)(this.target) + " " + connectivity_state_1.ConnectivityState[this.currentState] + " -> " + connectivity_state_1.ConnectivityState[connectivityState]); - if (connectivityState === connectivity_state_1.ConnectivityState.IDLE) { - picker = new picker_1.QueuePicker(this, picker); - } - this.currentState = connectivityState; - this.channelControlHelper.updateState(connectivityState, picker, errorMessage); - } - handleResolutionFailure(error3) { - if (this.latestChildState === connectivity_state_1.ConnectivityState.IDLE) { - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(error3), error3.details); - this.onFailedResolution(error3); - } - } - exitIdle() { - if (this.currentState === connectivity_state_1.ConnectivityState.IDLE || this.currentState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { - if (this.backoffTimeout.isRunning()) { - this.continueResolving = true; - } else { - this.updateResolution(); - } - } - this.childLoadBalancer.exitIdle(); - } - updateAddressList(endpointList, lbConfig) { - throw new Error("updateAddressList not supported on ResolvingLoadBalancer"); - } - resetBackoff() { - this.backoffTimeout.reset(); - this.childLoadBalancer.resetBackoff(); - } - destroy() { - this.childLoadBalancer.destroy(); - this.innerResolver.destroy(); - this.backoffTimeout.reset(); - this.backoffTimeout.stop(); - this.latestChildState = connectivity_state_1.ConnectivityState.IDLE; - this.latestChildPicker = new picker_1.QueuePicker(this); - this.currentState = connectivity_state_1.ConnectivityState.IDLE; - this.previousServiceConfig = null; - this.continueResolving = false; - } - getTypeName() { - return "resolving_load_balancer"; - } - }; - exports2.ResolvingLoadBalancer = ResolvingLoadBalancer; - } -}); - -// node_modules/@grpc/grpc-js/build/src/channel-options.js -var require_channel_options = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/channel-options.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.recognizedOptions = void 0; - exports2.channelOptionsEqual = channelOptionsEqual; - exports2.recognizedOptions = { - "grpc.ssl_target_name_override": true, - "grpc.primary_user_agent": true, - "grpc.secondary_user_agent": true, - "grpc.default_authority": true, - "grpc.keepalive_time_ms": true, - "grpc.keepalive_timeout_ms": true, - "grpc.keepalive_permit_without_calls": true, - "grpc.service_config": true, - "grpc.max_concurrent_streams": true, - "grpc.initial_reconnect_backoff_ms": true, - "grpc.max_reconnect_backoff_ms": true, - "grpc.use_local_subchannel_pool": true, - "grpc.max_send_message_length": true, - "grpc.max_receive_message_length": true, - "grpc.enable_http_proxy": true, - "grpc.enable_channelz": true, - "grpc.dns_min_time_between_resolutions_ms": true, - "grpc.enable_retries": true, - "grpc.per_rpc_retry_buffer_size": true, - "grpc.retry_buffer_size": true, - "grpc.max_connection_age_ms": true, - "grpc.max_connection_age_grace_ms": true, - "grpc-node.max_session_memory": true, - "grpc.service_config_disable_resolution": true, - "grpc.client_idle_timeout_ms": true, - "grpc-node.tls_enable_trace": true, - "grpc.lb.ring_hash.ring_size_cap": true, - "grpc-node.retry_max_attempts_limit": true, - "grpc-node.flow_control_window": true, - "grpc.server_call_metric_recording": true - }; - function channelOptionsEqual(options1, options2) { - const keys1 = Object.keys(options1).sort(); - const keys2 = Object.keys(options2).sort(); - if (keys1.length !== keys2.length) { - return false; - } - for (let i = 0; i < keys1.length; i += 1) { - if (keys1[i] !== keys2[i]) { - return false; - } - if (options1[keys1[i]] !== options2[keys2[i]]) { - return false; - } - } - return true; - } - } -}); - -// node_modules/@grpc/grpc-js/build/src/subchannel-address.js -var require_subchannel_address = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/subchannel-address.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.EndpointMap = void 0; - exports2.isTcpSubchannelAddress = isTcpSubchannelAddress; - exports2.subchannelAddressEqual = subchannelAddressEqual; - exports2.subchannelAddressToString = subchannelAddressToString; - exports2.stringToSubchannelAddress = stringToSubchannelAddress; - exports2.endpointEqual = endpointEqual; - exports2.endpointToString = endpointToString; - exports2.endpointHasAddress = endpointHasAddress; - var net_1 = require("net"); - function isTcpSubchannelAddress(address) { - return "port" in address; - } - function subchannelAddressEqual(address1, address2) { - if (!address1 && !address2) { - return true; - } - if (!address1 || !address2) { - return false; - } - if (isTcpSubchannelAddress(address1)) { - return isTcpSubchannelAddress(address2) && address1.host === address2.host && address1.port === address2.port; - } else { - return !isTcpSubchannelAddress(address2) && address1.path === address2.path; - } - } - function subchannelAddressToString(address) { - if (isTcpSubchannelAddress(address)) { - if ((0, net_1.isIPv6)(address.host)) { - return "[" + address.host + "]:" + address.port; - } else { - return address.host + ":" + address.port; - } - } else { - return address.path; - } - } - var DEFAULT_PORT = 443; - function stringToSubchannelAddress(addressString, port) { - if ((0, net_1.isIP)(addressString)) { - return { - host: addressString, - port: port !== null && port !== void 0 ? port : DEFAULT_PORT - }; - } else { - return { - path: addressString - }; - } - } - function endpointEqual(endpoint1, endpoint2) { - if (endpoint1.addresses.length !== endpoint2.addresses.length) { - return false; - } - for (let i = 0; i < endpoint1.addresses.length; i++) { - if (!subchannelAddressEqual(endpoint1.addresses[i], endpoint2.addresses[i])) { - return false; - } - } - return true; - } - function endpointToString(endpoint2) { - return "[" + endpoint2.addresses.map(subchannelAddressToString).join(", ") + "]"; - } - function endpointHasAddress(endpoint2, expectedAddress) { - for (const address of endpoint2.addresses) { - if (subchannelAddressEqual(address, expectedAddress)) { - return true; - } - } - return false; - } - function endpointEqualUnordered(endpoint1, endpoint2) { - if (endpoint1.addresses.length !== endpoint2.addresses.length) { - return false; - } - for (const address1 of endpoint1.addresses) { - let matchFound = false; - for (const address2 of endpoint2.addresses) { - if (subchannelAddressEqual(address1, address2)) { - matchFound = true; - break; - } - } - if (!matchFound) { - return false; - } - } - return true; - } - var EndpointMap = class { - constructor() { - this.map = /* @__PURE__ */ new Set(); - } - get size() { - return this.map.size; - } - getForSubchannelAddress(address) { - for (const entry of this.map) { - if (endpointHasAddress(entry.key, address)) { - return entry.value; - } - } - return void 0; - } - /** - * Delete any entries in this map with keys that are not in endpoints - * @param endpoints - */ - deleteMissing(endpoints) { - const removedValues = []; - for (const entry of this.map) { - let foundEntry = false; - for (const endpoint2 of endpoints) { - if (endpointEqualUnordered(endpoint2, entry.key)) { - foundEntry = true; - } - } - if (!foundEntry) { - removedValues.push(entry.value); - this.map.delete(entry); - } - } - return removedValues; - } - get(endpoint2) { - for (const entry of this.map) { - if (endpointEqualUnordered(endpoint2, entry.key)) { - return entry.value; - } - } - return void 0; - } - set(endpoint2, mapEntry) { - for (const entry of this.map) { - if (endpointEqualUnordered(endpoint2, entry.key)) { - entry.value = mapEntry; - return; - } - } - this.map.add({ key: endpoint2, value: mapEntry }); - } - delete(endpoint2) { - for (const entry of this.map) { - if (endpointEqualUnordered(endpoint2, entry.key)) { - this.map.delete(entry); - return; - } - } - } - has(endpoint2) { - for (const entry of this.map) { - if (endpointEqualUnordered(endpoint2, entry.key)) { - return true; - } - } - return false; - } - clear() { - this.map.clear(); - } - *keys() { - for (const entry of this.map) { - yield entry.key; - } - } - *values() { - for (const entry of this.map) { - yield entry.value; - } - } - *entries() { - for (const entry of this.map) { - yield [entry.key, entry.value]; - } - } - }; - exports2.EndpointMap = EndpointMap; - } -}); - -// node_modules/@js-sdsl/ordered-map/dist/cjs/index.js -var require_cjs = __commonJS({ - "node_modules/@js-sdsl/ordered-map/dist/cjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "t", { - value: true - }); - var TreeNode = class { - constructor(t, e, s = 1) { - this.i = void 0; - this.h = void 0; - this.o = void 0; - this.u = t; - this.l = e; - this.p = s; - } - I() { - let t = this; - const e = t.o.o === t; - if (e && t.p === 1) { - t = t.h; - } else if (t.i) { - t = t.i; - while (t.h) { - t = t.h; - } - } else { - if (e) { - return t.o; - } - let s = t.o; - while (s.i === t) { - t = s; - s = t.o; - } - t = s; - } - return t; - } - B() { - let t = this; - if (t.h) { - t = t.h; - while (t.i) { - t = t.i; - } - return t; - } else { - let e = t.o; - while (e.h === t) { - t = e; - e = t.o; - } - if (t.h !== e) { - return e; - } else return t; - } - } - _() { - const t = this.o; - const e = this.h; - const s = e.i; - if (t.o === this) t.o = e; - else if (t.i === this) t.i = e; - else t.h = e; - e.o = t; - e.i = this; - this.o = e; - this.h = s; - if (s) s.o = this; - return e; - } - g() { - const t = this.o; - const e = this.i; - const s = e.h; - if (t.o === this) t.o = e; - else if (t.i === this) t.i = e; - else t.h = e; - e.o = t; - e.h = this; - this.o = e; - this.i = s; - if (s) s.o = this; - return e; - } - }; - var TreeNodeEnableIndex = class extends TreeNode { - constructor() { - super(...arguments); - this.M = 1; - } - _() { - const t = super._(); - this.O(); - t.O(); - return t; - } - g() { - const t = super.g(); - this.O(); - t.O(); - return t; - } - O() { - this.M = 1; - if (this.i) { - this.M += this.i.M; - } - if (this.h) { - this.M += this.h.M; - } - } - }; - var ContainerIterator = class { - constructor(t = 0) { - this.iteratorType = t; - } - equals(t) { - return this.T === t.T; - } - }; - var Base = class { - constructor() { - this.m = 0; - } - get length() { - return this.m; - } - size() { - return this.m; - } - empty() { - return this.m === 0; - } - }; - var Container2 = class extends Base { - }; - function throwIteratorAccessError() { - throw new RangeError("Iterator access denied!"); - } - var TreeContainer = class extends Container2 { - constructor(t = function(t2, e2) { - if (t2 < e2) return -1; - if (t2 > e2) return 1; - return 0; - }, e = false) { - super(); - this.v = void 0; - this.A = t; - this.enableIndex = e; - this.N = e ? TreeNodeEnableIndex : TreeNode; - this.C = new this.N(); - } - R(t, e) { - let s = this.C; - while (t) { - const i = this.A(t.u, e); - if (i < 0) { - t = t.h; - } else if (i > 0) { - s = t; - t = t.i; - } else return t; - } - return s; - } - K(t, e) { - let s = this.C; - while (t) { - const i = this.A(t.u, e); - if (i <= 0) { - t = t.h; - } else { - s = t; - t = t.i; - } - } - return s; - } - L(t, e) { - let s = this.C; - while (t) { - const i = this.A(t.u, e); - if (i < 0) { - s = t; - t = t.h; - } else if (i > 0) { - t = t.i; - } else return t; - } - return s; - } - k(t, e) { - let s = this.C; - while (t) { - const i = this.A(t.u, e); - if (i < 0) { - s = t; - t = t.h; - } else { - t = t.i; - } - } - return s; - } - P(t) { - while (true) { - const e = t.o; - if (e === this.C) return; - if (t.p === 1) { - t.p = 0; - return; - } - if (t === e.i) { - const s = e.h; - if (s.p === 1) { - s.p = 0; - e.p = 1; - if (e === this.v) { - this.v = e._(); - } else e._(); - } else { - if (s.h && s.h.p === 1) { - s.p = e.p; - e.p = 0; - s.h.p = 0; - if (e === this.v) { - this.v = e._(); - } else e._(); - return; - } else if (s.i && s.i.p === 1) { - s.p = 1; - s.i.p = 0; - s.g(); - } else { - s.p = 1; - t = e; - } - } - } else { - const s = e.i; - if (s.p === 1) { - s.p = 0; - e.p = 1; - if (e === this.v) { - this.v = e.g(); - } else e.g(); - } else { - if (s.i && s.i.p === 1) { - s.p = e.p; - e.p = 0; - s.i.p = 0; - if (e === this.v) { - this.v = e.g(); - } else e.g(); - return; - } else if (s.h && s.h.p === 1) { - s.p = 1; - s.h.p = 0; - s._(); - } else { - s.p = 1; - t = e; - } - } - } - } - } - S(t) { - if (this.m === 1) { - this.clear(); - return; - } - let e = t; - while (e.i || e.h) { - if (e.h) { - e = e.h; - while (e.i) e = e.i; - } else { - e = e.i; - } - const s2 = t.u; - t.u = e.u; - e.u = s2; - const i = t.l; - t.l = e.l; - e.l = i; - t = e; - } - if (this.C.i === e) { - this.C.i = e.o; - } else if (this.C.h === e) { - this.C.h = e.o; - } - this.P(e); - let s = e.o; - if (e === s.i) { - s.i = void 0; - } else s.h = void 0; - this.m -= 1; - this.v.p = 0; - if (this.enableIndex) { - while (s !== this.C) { - s.M -= 1; - s = s.o; - } - } - } - U(t) { - const e = typeof t === "number" ? t : void 0; - const s = typeof t === "function" ? t : void 0; - const i = typeof t === "undefined" ? [] : void 0; - let r = 0; - let n = this.v; - const h = []; - while (h.length || n) { - if (n) { - h.push(n); - n = n.i; - } else { - n = h.pop(); - if (r === e) return n; - i && i.push(n); - s && s(n, r, this); - r += 1; - n = n.h; - } - } - return i; - } - j(t) { - while (true) { - const e = t.o; - if (e.p === 0) return; - const s = e.o; - if (e === s.i) { - const i = s.h; - if (i && i.p === 1) { - i.p = e.p = 0; - if (s === this.v) return; - s.p = 1; - t = s; - continue; - } else if (t === e.h) { - t.p = 0; - if (t.i) { - t.i.o = e; - } - if (t.h) { - t.h.o = s; - } - e.h = t.i; - s.i = t.h; - t.i = e; - t.h = s; - if (s === this.v) { - this.v = t; - this.C.o = t; - } else { - const e2 = s.o; - if (e2.i === s) { - e2.i = t; - } else e2.h = t; - } - t.o = s.o; - e.o = t; - s.o = t; - s.p = 1; - } else { - e.p = 0; - if (s === this.v) { - this.v = s.g(); - } else s.g(); - s.p = 1; - return; - } - } else { - const i = s.i; - if (i && i.p === 1) { - i.p = e.p = 0; - if (s === this.v) return; - s.p = 1; - t = s; - continue; - } else if (t === e.i) { - t.p = 0; - if (t.i) { - t.i.o = s; - } - if (t.h) { - t.h.o = e; - } - s.h = t.i; - e.i = t.h; - t.i = s; - t.h = e; - if (s === this.v) { - this.v = t; - this.C.o = t; - } else { - const e2 = s.o; - if (e2.i === s) { - e2.i = t; - } else e2.h = t; - } - t.o = s.o; - e.o = t; - s.o = t; - s.p = 1; - } else { - e.p = 0; - if (s === this.v) { - this.v = s._(); - } else s._(); - s.p = 1; - return; - } - } - if (this.enableIndex) { - e.O(); - s.O(); - t.O(); - } - return; - } - } - q(t, e, s) { - if (this.v === void 0) { - this.m += 1; - this.v = new this.N(t, e, 0); - this.v.o = this.C; - this.C.o = this.C.i = this.C.h = this.v; - return this.m; - } - let i; - const r = this.C.i; - const n = this.A(r.u, t); - if (n === 0) { - r.l = e; - return this.m; - } else if (n > 0) { - r.i = new this.N(t, e); - r.i.o = r; - i = r.i; - this.C.i = i; - } else { - const r2 = this.C.h; - const n2 = this.A(r2.u, t); - if (n2 === 0) { - r2.l = e; - return this.m; - } else if (n2 < 0) { - r2.h = new this.N(t, e); - r2.h.o = r2; - i = r2.h; - this.C.h = i; - } else { - if (s !== void 0) { - const r3 = s.T; - if (r3 !== this.C) { - const s2 = this.A(r3.u, t); - if (s2 === 0) { - r3.l = e; - return this.m; - } else if (s2 > 0) { - const s3 = r3.I(); - const n3 = this.A(s3.u, t); - if (n3 === 0) { - s3.l = e; - return this.m; - } else if (n3 < 0) { - i = new this.N(t, e); - if (s3.h === void 0) { - s3.h = i; - i.o = s3; - } else { - r3.i = i; - i.o = r3; - } - } - } - } - } - if (i === void 0) { - i = this.v; - while (true) { - const s2 = this.A(i.u, t); - if (s2 > 0) { - if (i.i === void 0) { - i.i = new this.N(t, e); - i.i.o = i; - i = i.i; - break; - } - i = i.i; - } else if (s2 < 0) { - if (i.h === void 0) { - i.h = new this.N(t, e); - i.h.o = i; - i = i.h; - break; - } - i = i.h; - } else { - i.l = e; - return this.m; - } - } - } - } - } - if (this.enableIndex) { - let t2 = i.o; - while (t2 !== this.C) { - t2.M += 1; - t2 = t2.o; - } - } - this.j(i); - this.m += 1; - return this.m; - } - H(t, e) { - while (t) { - const s = this.A(t.u, e); - if (s < 0) { - t = t.h; - } else if (s > 0) { - t = t.i; - } else return t; - } - return t || this.C; - } - clear() { - this.m = 0; - this.v = void 0; - this.C.o = void 0; - this.C.i = this.C.h = void 0; - } - updateKeyByIterator(t, e) { - const s = t.T; - if (s === this.C) { - throwIteratorAccessError(); - } - if (this.m === 1) { - s.u = e; - return true; - } - const i = s.B().u; - if (s === this.C.i) { - if (this.A(i, e) > 0) { - s.u = e; - return true; - } - return false; - } - const r = s.I().u; - if (s === this.C.h) { - if (this.A(r, e) < 0) { - s.u = e; - return true; - } - return false; - } - if (this.A(r, e) >= 0 || this.A(i, e) <= 0) return false; - s.u = e; - return true; - } - eraseElementByPos(t) { - if (t < 0 || t > this.m - 1) { - throw new RangeError(); - } - const e = this.U(t); - this.S(e); - return this.m; - } - eraseElementByKey(t) { - if (this.m === 0) return false; - const e = this.H(this.v, t); - if (e === this.C) return false; - this.S(e); - return true; - } - eraseElementByIterator(t) { - const e = t.T; - if (e === this.C) { - throwIteratorAccessError(); - } - const s = e.h === void 0; - const i = t.iteratorType === 0; - if (i) { - if (s) t.next(); - } else { - if (!s || e.i === void 0) t.next(); - } - this.S(e); - return t; - } - getHeight() { - if (this.m === 0) return 0; - function traversal(t) { - if (!t) return 0; - return Math.max(traversal(t.i), traversal(t.h)) + 1; - } - return traversal(this.v); - } - }; - var TreeIterator = class extends ContainerIterator { - constructor(t, e, s) { - super(s); - this.T = t; - this.C = e; - if (this.iteratorType === 0) { - this.pre = function() { - if (this.T === this.C.i) { - throwIteratorAccessError(); - } - this.T = this.T.I(); - return this; - }; - this.next = function() { - if (this.T === this.C) { - throwIteratorAccessError(); - } - this.T = this.T.B(); - return this; - }; - } else { - this.pre = function() { - if (this.T === this.C.h) { - throwIteratorAccessError(); - } - this.T = this.T.B(); - return this; - }; - this.next = function() { - if (this.T === this.C) { - throwIteratorAccessError(); - } - this.T = this.T.I(); - return this; - }; - } - } - get index() { - let t = this.T; - const e = this.C.o; - if (t === this.C) { - if (e) { - return e.M - 1; - } - return 0; - } - let s = 0; - if (t.i) { - s += t.i.M; - } - while (t !== e) { - const e2 = t.o; - if (t === e2.h) { - s += 1; - if (e2.i) { - s += e2.i.M; - } - } - t = e2; - } - return s; - } - isAccessible() { - return this.T !== this.C; - } - }; - var OrderedMapIterator = class _OrderedMapIterator extends TreeIterator { - constructor(t, e, s, i) { - super(t, e, i); - this.container = s; - } - get pointer() { - if (this.T === this.C) { - throwIteratorAccessError(); - } - const t = this; - return new Proxy([], { - get(e, s) { - if (s === "0") return t.T.u; - else if (s === "1") return t.T.l; - e[0] = t.T.u; - e[1] = t.T.l; - return e[s]; - }, - set(e, s, i) { - if (s !== "1") { - throw new TypeError("prop must be 1"); - } - t.T.l = i; - return true; - } - }); - } - copy() { - return new _OrderedMapIterator(this.T, this.C, this.container, this.iteratorType); - } - }; - var OrderedMap = class extends TreeContainer { - constructor(t = [], e, s) { - super(e, s); - const i = this; - t.forEach((function(t2) { - i.setElement(t2[0], t2[1]); - })); - } - begin() { - return new OrderedMapIterator(this.C.i || this.C, this.C, this); - } - end() { - return new OrderedMapIterator(this.C, this.C, this); - } - rBegin() { - return new OrderedMapIterator(this.C.h || this.C, this.C, this, 1); - } - rEnd() { - return new OrderedMapIterator(this.C, this.C, this, 1); - } - front() { - if (this.m === 0) return; - const t = this.C.i; - return [t.u, t.l]; - } - back() { - if (this.m === 0) return; - const t = this.C.h; - return [t.u, t.l]; - } - lowerBound(t) { - const e = this.R(this.v, t); - return new OrderedMapIterator(e, this.C, this); - } - upperBound(t) { - const e = this.K(this.v, t); - return new OrderedMapIterator(e, this.C, this); - } - reverseLowerBound(t) { - const e = this.L(this.v, t); - return new OrderedMapIterator(e, this.C, this); - } - reverseUpperBound(t) { - const e = this.k(this.v, t); - return new OrderedMapIterator(e, this.C, this); - } - forEach(t) { - this.U((function(e, s, i) { - t([e.u, e.l], s, i); - })); - } - setElement(t, e, s) { - return this.q(t, e, s); - } - getElementByPos(t) { - if (t < 0 || t > this.m - 1) { - throw new RangeError(); - } - const e = this.U(t); - return [e.u, e.l]; - } - find(t) { - const e = this.H(this.v, t); - return new OrderedMapIterator(e, this.C, this); - } - getElementByKey(t) { - const e = this.H(this.v, t); - return e.l; - } - union(t) { - const e = this; - t.forEach((function(t2) { - e.setElement(t2[0], t2[1]); - })); - return this.m; - } - *[Symbol.iterator]() { - const t = this.m; - const e = this.U(); - for (let s = 0; s < t; ++s) { - const t2 = e[s]; - yield [t2.u, t2.l]; - } - } - }; - exports2.OrderedMap = OrderedMap; - } -}); - -// node_modules/@grpc/grpc-js/build/src/admin.js -var require_admin = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/admin.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.registerAdminService = registerAdminService; - exports2.addAdminServicesToServer = addAdminServicesToServer; - var registeredAdminServices = []; - function registerAdminService(getServiceDefinition, getHandlers) { - registeredAdminServices.push({ getServiceDefinition, getHandlers }); - } - function addAdminServicesToServer(server) { - for (const { getServiceDefinition, getHandlers } of registeredAdminServices) { - server.addService(getServiceDefinition(), getHandlers()); - } - } - } -}); - -// node_modules/@grpc/grpc-js/build/src/call.js -var require_call = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/call.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ClientDuplexStreamImpl = exports2.ClientWritableStreamImpl = exports2.ClientReadableStreamImpl = exports2.ClientUnaryCallImpl = void 0; - exports2.callErrorFromStatus = callErrorFromStatus; - var events_1 = require("events"); - var stream_1 = require("stream"); - var constants_1 = require_constants7(); - function callErrorFromStatus(status, callerStack) { - const message = `${status.code} ${constants_1.Status[status.code]}: ${status.details}`; - const error3 = new Error(message); - const stack = `${error3.stack} -for call at -${callerStack}`; - return Object.assign(new Error(message), status, { stack }); - } - var ClientUnaryCallImpl = class extends events_1.EventEmitter { - constructor() { - super(); - } - cancel() { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, "Cancelled on client"); - } - getPeer() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : "unknown"; - } - getAuthContext() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getAuthContext()) !== null && _b !== void 0 ? _b : null; - } - }; - exports2.ClientUnaryCallImpl = ClientUnaryCallImpl; - var ClientReadableStreamImpl = class extends stream_1.Readable { - constructor(deserialize) { - super({ objectMode: true }); - this.deserialize = deserialize; - } - cancel() { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, "Cancelled on client"); - } - getPeer() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : "unknown"; - } - getAuthContext() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getAuthContext()) !== null && _b !== void 0 ? _b : null; - } - _read(_size) { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.startRead(); - } - }; - exports2.ClientReadableStreamImpl = ClientReadableStreamImpl; - var ClientWritableStreamImpl = class extends stream_1.Writable { - constructor(serialize) { - super({ objectMode: true }); - this.serialize = serialize; - } - cancel() { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, "Cancelled on client"); - } - getPeer() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : "unknown"; - } - getAuthContext() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getAuthContext()) !== null && _b !== void 0 ? _b : null; - } - _write(chunk, encoding, cb) { - var _a; - const context3 = { - callback: cb - }; - const flags = Number(encoding); - if (!Number.isNaN(flags)) { - context3.flags = flags; - } - (_a = this.call) === null || _a === void 0 ? void 0 : _a.sendMessageWithContext(context3, chunk); - } - _final(cb) { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.halfClose(); - cb(); - } - }; - exports2.ClientWritableStreamImpl = ClientWritableStreamImpl; - var ClientDuplexStreamImpl = class extends stream_1.Duplex { - constructor(serialize, deserialize) { - super({ objectMode: true }); - this.serialize = serialize; - this.deserialize = deserialize; - } - cancel() { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, "Cancelled on client"); - } - getPeer() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : "unknown"; - } - getAuthContext() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getAuthContext()) !== null && _b !== void 0 ? _b : null; - } - _read(_size) { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.startRead(); - } - _write(chunk, encoding, cb) { - var _a; - const context3 = { - callback: cb - }; - const flags = Number(encoding); - if (!Number.isNaN(flags)) { - context3.flags = flags; - } - (_a = this.call) === null || _a === void 0 ? void 0 : _a.sendMessageWithContext(context3, chunk); - } - _final(cb) { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.halfClose(); - cb(); - } - }; - exports2.ClientDuplexStreamImpl = ClientDuplexStreamImpl; - } -}); - -// node_modules/@grpc/grpc-js/build/src/call-interface.js -var require_call_interface = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/call-interface.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.InterceptingListenerImpl = void 0; - exports2.statusOrFromValue = statusOrFromValue; - exports2.statusOrFromError = statusOrFromError; - exports2.isInterceptingListener = isInterceptingListener; - var metadata_1 = require_metadata(); - function statusOrFromValue(value) { - return { - ok: true, - value - }; - } - function statusOrFromError(error3) { - var _a; - return { - ok: false, - error: Object.assign(Object.assign({}, error3), { metadata: (_a = error3.metadata) !== null && _a !== void 0 ? _a : new metadata_1.Metadata() }) - }; - } - function isInterceptingListener(listener) { - return listener.onReceiveMetadata !== void 0 && listener.onReceiveMetadata.length === 1; - } - var InterceptingListenerImpl = class { - constructor(listener, nextListener) { - this.listener = listener; - this.nextListener = nextListener; - this.processingMetadata = false; - this.hasPendingMessage = false; - this.processingMessage = false; - this.pendingStatus = null; - } - processPendingMessage() { - if (this.hasPendingMessage) { - this.nextListener.onReceiveMessage(this.pendingMessage); - this.pendingMessage = null; - this.hasPendingMessage = false; - } - } - processPendingStatus() { - if (this.pendingStatus) { - this.nextListener.onReceiveStatus(this.pendingStatus); - } - } - onReceiveMetadata(metadata) { - this.processingMetadata = true; - this.listener.onReceiveMetadata(metadata, (metadata2) => { - this.processingMetadata = false; - this.nextListener.onReceiveMetadata(metadata2); - this.processPendingMessage(); - this.processPendingStatus(); - }); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - onReceiveMessage(message) { - this.processingMessage = true; - this.listener.onReceiveMessage(message, (msg) => { - this.processingMessage = false; - if (this.processingMetadata) { - this.pendingMessage = msg; - this.hasPendingMessage = true; - } else { - this.nextListener.onReceiveMessage(msg); - this.processPendingStatus(); - } - }); - } - onReceiveStatus(status) { - this.listener.onReceiveStatus(status, (processedStatus) => { - if (this.processingMetadata || this.processingMessage) { - this.pendingStatus = processedStatus; - } else { - this.nextListener.onReceiveStatus(processedStatus); - } - }); - } - }; - exports2.InterceptingListenerImpl = InterceptingListenerImpl; - } -}); - -// node_modules/@grpc/grpc-js/build/src/client-interceptors.js -var require_client_interceptors = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/client-interceptors.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.InterceptingCall = exports2.RequesterBuilder = exports2.ListenerBuilder = exports2.InterceptorConfigurationError = void 0; - exports2.getInterceptingCall = getInterceptingCall; - var metadata_1 = require_metadata(); - var call_interface_1 = require_call_interface(); - var constants_1 = require_constants7(); - var error_1 = require_error(); - var InterceptorConfigurationError = class _InterceptorConfigurationError extends Error { - constructor(message) { - super(message); - this.name = "InterceptorConfigurationError"; - Error.captureStackTrace(this, _InterceptorConfigurationError); - } - }; - exports2.InterceptorConfigurationError = InterceptorConfigurationError; - var ListenerBuilder = class { - constructor() { - this.metadata = void 0; - this.message = void 0; - this.status = void 0; - } - withOnReceiveMetadata(onReceiveMetadata) { - this.metadata = onReceiveMetadata; - return this; - } - withOnReceiveMessage(onReceiveMessage) { - this.message = onReceiveMessage; - return this; - } - withOnReceiveStatus(onReceiveStatus) { - this.status = onReceiveStatus; - return this; - } - build() { - return { - onReceiveMetadata: this.metadata, - onReceiveMessage: this.message, - onReceiveStatus: this.status - }; - } - }; - exports2.ListenerBuilder = ListenerBuilder; - var RequesterBuilder = class { - constructor() { - this.start = void 0; - this.message = void 0; - this.halfClose = void 0; - this.cancel = void 0; - } - withStart(start) { - this.start = start; - return this; - } - withSendMessage(sendMessage) { - this.message = sendMessage; - return this; - } - withHalfClose(halfClose) { - this.halfClose = halfClose; - return this; - } - withCancel(cancel) { - this.cancel = cancel; - return this; - } - build() { - return { - start: this.start, - sendMessage: this.message, - halfClose: this.halfClose, - cancel: this.cancel - }; - } - }; - exports2.RequesterBuilder = RequesterBuilder; - var defaultListener = { - onReceiveMetadata: (metadata, next) => { - next(metadata); - }, - onReceiveMessage: (message, next) => { - next(message); - }, - onReceiveStatus: (status, next) => { - next(status); - } - }; - var defaultRequester = { - start: (metadata, listener, next) => { - next(metadata, listener); - }, - sendMessage: (message, next) => { - next(message); - }, - halfClose: (next) => { - next(); - }, - cancel: (next) => { - next(); - } - }; - var InterceptingCall = class { - constructor(nextCall, requester) { - var _a, _b, _c, _d; - this.nextCall = nextCall; - this.processingMetadata = false; - this.pendingMessageContext = null; - this.processingMessage = false; - this.pendingHalfClose = false; - if (requester) { - this.requester = { - start: (_a = requester.start) !== null && _a !== void 0 ? _a : defaultRequester.start, - sendMessage: (_b = requester.sendMessage) !== null && _b !== void 0 ? _b : defaultRequester.sendMessage, - halfClose: (_c = requester.halfClose) !== null && _c !== void 0 ? _c : defaultRequester.halfClose, - cancel: (_d = requester.cancel) !== null && _d !== void 0 ? _d : defaultRequester.cancel - }; - } else { - this.requester = defaultRequester; - } - } - cancelWithStatus(status, details) { - this.requester.cancel(() => { - this.nextCall.cancelWithStatus(status, details); - }); - } - getPeer() { - return this.nextCall.getPeer(); - } - processPendingMessage() { - if (this.pendingMessageContext) { - this.nextCall.sendMessageWithContext(this.pendingMessageContext, this.pendingMessage); - this.pendingMessageContext = null; - this.pendingMessage = null; - } - } - processPendingHalfClose() { - if (this.pendingHalfClose) { - this.nextCall.halfClose(); - } - } - start(metadata, interceptingListener) { - var _a, _b, _c, _d, _e, _f; - const fullInterceptingListener = { - onReceiveMetadata: (_b = (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMetadata) === null || _a === void 0 ? void 0 : _a.bind(interceptingListener)) !== null && _b !== void 0 ? _b : ((metadata2) => { - }), - onReceiveMessage: (_d = (_c = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMessage) === null || _c === void 0 ? void 0 : _c.bind(interceptingListener)) !== null && _d !== void 0 ? _d : ((message) => { - }), - onReceiveStatus: (_f = (_e = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _e === void 0 ? void 0 : _e.bind(interceptingListener)) !== null && _f !== void 0 ? _f : ((status) => { - }) - }; - this.processingMetadata = true; - this.requester.start(metadata, fullInterceptingListener, (md2, listener) => { - var _a2, _b2, _c2; - this.processingMetadata = false; - let finalInterceptingListener; - if ((0, call_interface_1.isInterceptingListener)(listener)) { - finalInterceptingListener = listener; - } else { - const fullListener = { - onReceiveMetadata: (_a2 = listener.onReceiveMetadata) !== null && _a2 !== void 0 ? _a2 : defaultListener.onReceiveMetadata, - onReceiveMessage: (_b2 = listener.onReceiveMessage) !== null && _b2 !== void 0 ? _b2 : defaultListener.onReceiveMessage, - onReceiveStatus: (_c2 = listener.onReceiveStatus) !== null && _c2 !== void 0 ? _c2 : defaultListener.onReceiveStatus - }; - finalInterceptingListener = new call_interface_1.InterceptingListenerImpl(fullListener, fullInterceptingListener); - } - this.nextCall.start(md2, finalInterceptingListener); - this.processPendingMessage(); - this.processPendingHalfClose(); - }); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sendMessageWithContext(context3, message) { - this.processingMessage = true; - this.requester.sendMessage(message, (finalMessage) => { - this.processingMessage = false; - if (this.processingMetadata) { - this.pendingMessageContext = context3; - this.pendingMessage = message; - } else { - this.nextCall.sendMessageWithContext(context3, finalMessage); - this.processPendingHalfClose(); - } - }); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sendMessage(message) { - this.sendMessageWithContext({}, message); - } - startRead() { - this.nextCall.startRead(); - } - halfClose() { - this.requester.halfClose(() => { - if (this.processingMetadata || this.processingMessage) { - this.pendingHalfClose = true; - } else { - this.nextCall.halfClose(); - } - }); - } - getAuthContext() { - return this.nextCall.getAuthContext(); - } - }; - exports2.InterceptingCall = InterceptingCall; - function getCall(channel, path, options) { - var _a, _b; - const deadline = (_a = options.deadline) !== null && _a !== void 0 ? _a : Infinity; - const host = options.host; - const parent = (_b = options.parent) !== null && _b !== void 0 ? _b : null; - const propagateFlags = options.propagate_flags; - const credentials = options.credentials; - const call = channel.createCall(path, deadline, host, parent, propagateFlags); - if (credentials) { - call.setCredentials(credentials); - } - return call; - } - var BaseInterceptingCall = class { - constructor(call, methodDefinition) { - this.call = call; - this.methodDefinition = methodDefinition; - } - cancelWithStatus(status, details) { - this.call.cancelWithStatus(status, details); - } - getPeer() { - return this.call.getPeer(); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sendMessageWithContext(context3, message) { - let serialized; - try { - serialized = this.methodDefinition.requestSerialize(message); - } catch (e) { - this.call.cancelWithStatus(constants_1.Status.INTERNAL, `Request message serialization failure: ${(0, error_1.getErrorMessage)(e)}`); - return; - } - this.call.sendMessageWithContext(context3, serialized); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sendMessage(message) { - this.sendMessageWithContext({}, message); - } - start(metadata, interceptingListener) { - let readError = null; - this.call.start(metadata, { - onReceiveMetadata: (metadata2) => { - var _a; - (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMetadata) === null || _a === void 0 ? void 0 : _a.call(interceptingListener, metadata2); - }, - onReceiveMessage: (message) => { - var _a; - let deserialized; - try { - deserialized = this.methodDefinition.responseDeserialize(message); - } catch (e) { - readError = { - code: constants_1.Status.INTERNAL, - details: `Response message parsing error: ${(0, error_1.getErrorMessage)(e)}`, - metadata: new metadata_1.Metadata() - }; - this.call.cancelWithStatus(readError.code, readError.details); - return; - } - (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMessage) === null || _a === void 0 ? void 0 : _a.call(interceptingListener, deserialized); - }, - onReceiveStatus: (status) => { - var _a, _b; - if (readError) { - (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _a === void 0 ? void 0 : _a.call(interceptingListener, readError); - } else { - (_b = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _b === void 0 ? void 0 : _b.call(interceptingListener, status); - } - } - }); - } - startRead() { - this.call.startRead(); - } - halfClose() { - this.call.halfClose(); - } - getAuthContext() { - return this.call.getAuthContext(); - } - }; - var BaseUnaryInterceptingCall = class extends BaseInterceptingCall { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - constructor(call, methodDefinition) { - super(call, methodDefinition); - } - start(metadata, listener) { - var _a, _b; - let receivedMessage = false; - const wrapperListener = { - onReceiveMetadata: (_b = (_a = listener === null || listener === void 0 ? void 0 : listener.onReceiveMetadata) === null || _a === void 0 ? void 0 : _a.bind(listener)) !== null && _b !== void 0 ? _b : ((metadata2) => { - }), - // eslint-disable-next-line @typescript-eslint/no-explicit-any - onReceiveMessage: (message) => { - var _a2; - receivedMessage = true; - (_a2 = listener === null || listener === void 0 ? void 0 : listener.onReceiveMessage) === null || _a2 === void 0 ? void 0 : _a2.call(listener, message); - }, - onReceiveStatus: (status) => { - var _a2, _b2; - if (!receivedMessage) { - (_a2 = listener === null || listener === void 0 ? void 0 : listener.onReceiveMessage) === null || _a2 === void 0 ? void 0 : _a2.call(listener, null); - } - (_b2 = listener === null || listener === void 0 ? void 0 : listener.onReceiveStatus) === null || _b2 === void 0 ? void 0 : _b2.call(listener, status); - } - }; - super.start(metadata, wrapperListener); - this.call.startRead(); - } - }; - var BaseStreamingInterceptingCall = class extends BaseInterceptingCall { - }; - function getBottomInterceptingCall(channel, options, methodDefinition) { - const call = getCall(channel, methodDefinition.path, options); - if (methodDefinition.responseStream) { - return new BaseStreamingInterceptingCall(call, methodDefinition); - } else { - return new BaseUnaryInterceptingCall(call, methodDefinition); - } - } - function getInterceptingCall(interceptorArgs, methodDefinition, options, channel) { - if (interceptorArgs.clientInterceptors.length > 0 && interceptorArgs.clientInterceptorProviders.length > 0) { - throw new InterceptorConfigurationError("Both interceptors and interceptor_providers were passed as options to the client constructor. Only one of these is allowed."); - } - if (interceptorArgs.callInterceptors.length > 0 && interceptorArgs.callInterceptorProviders.length > 0) { - throw new InterceptorConfigurationError("Both interceptors and interceptor_providers were passed as call options. Only one of these is allowed."); - } - let interceptors = []; - if (interceptorArgs.callInterceptors.length > 0 || interceptorArgs.callInterceptorProviders.length > 0) { - interceptors = [].concat(interceptorArgs.callInterceptors, interceptorArgs.callInterceptorProviders.map((provider) => provider(methodDefinition))).filter((interceptor) => interceptor); - } else { - interceptors = [].concat(interceptorArgs.clientInterceptors, interceptorArgs.clientInterceptorProviders.map((provider) => provider(methodDefinition))).filter((interceptor) => interceptor); - } - const interceptorOptions = Object.assign({}, options, { - method_definition: methodDefinition - }); - const getCall2 = interceptors.reduceRight((nextCall, nextInterceptor) => { - return (currentOptions) => nextInterceptor(currentOptions, nextCall); - }, (finalOptions) => getBottomInterceptingCall(channel, finalOptions, methodDefinition)); - return getCall2(interceptorOptions); - } - } -}); - -// node_modules/@grpc/grpc-js/build/src/client.js -var require_client3 = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/client.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Client = void 0; - var call_1 = require_call(); - var channel_1 = require_channel(); - var connectivity_state_1 = require_connectivity_state(); - var constants_1 = require_constants7(); - var metadata_1 = require_metadata(); - var client_interceptors_1 = require_client_interceptors(); - var CHANNEL_SYMBOL = /* @__PURE__ */ Symbol(); - var INTERCEPTOR_SYMBOL = /* @__PURE__ */ Symbol(); - var INTERCEPTOR_PROVIDER_SYMBOL = /* @__PURE__ */ Symbol(); - var CALL_INVOCATION_TRANSFORMER_SYMBOL = /* @__PURE__ */ Symbol(); - function isFunction(arg) { - return typeof arg === "function"; - } - function getErrorStackString(error3) { - var _a; - return ((_a = error3.stack) === null || _a === void 0 ? void 0 : _a.split("\n").slice(1).join("\n")) || "no stack trace available"; - } - var Client = class { - constructor(address, credentials, options = {}) { - var _a, _b; - options = Object.assign({}, options); - this[INTERCEPTOR_SYMBOL] = (_a = options.interceptors) !== null && _a !== void 0 ? _a : []; - delete options.interceptors; - this[INTERCEPTOR_PROVIDER_SYMBOL] = (_b = options.interceptor_providers) !== null && _b !== void 0 ? _b : []; - delete options.interceptor_providers; - if (this[INTERCEPTOR_SYMBOL].length > 0 && this[INTERCEPTOR_PROVIDER_SYMBOL].length > 0) { - throw new Error("Both interceptors and interceptor_providers were passed as options to the client constructor. Only one of these is allowed."); - } - this[CALL_INVOCATION_TRANSFORMER_SYMBOL] = options.callInvocationTransformer; - delete options.callInvocationTransformer; - if (options.channelOverride) { - this[CHANNEL_SYMBOL] = options.channelOverride; - } else if (options.channelFactoryOverride) { - const channelFactoryOverride = options.channelFactoryOverride; - delete options.channelFactoryOverride; - this[CHANNEL_SYMBOL] = channelFactoryOverride(address, credentials, options); - } else { - this[CHANNEL_SYMBOL] = new channel_1.ChannelImplementation(address, credentials, options); - } - } - close() { - this[CHANNEL_SYMBOL].close(); - } - getChannel() { - return this[CHANNEL_SYMBOL]; - } - waitForReady(deadline, callback) { - const checkState = (err) => { - if (err) { - callback(new Error("Failed to connect before the deadline")); - return; - } - let newState; - try { - newState = this[CHANNEL_SYMBOL].getConnectivityState(true); - } catch (e) { - callback(new Error("The channel has been closed")); - return; - } - if (newState === connectivity_state_1.ConnectivityState.READY) { - callback(); - } else { - try { - this[CHANNEL_SYMBOL].watchConnectivityState(newState, deadline, checkState); - } catch (e) { - callback(new Error("The channel has been closed")); - } - } - }; - setImmediate(checkState); - } - checkOptionalUnaryResponseArguments(arg1, arg2, arg3) { - if (isFunction(arg1)) { - return { metadata: new metadata_1.Metadata(), options: {}, callback: arg1 }; - } else if (isFunction(arg2)) { - if (arg1 instanceof metadata_1.Metadata) { - return { metadata: arg1, options: {}, callback: arg2 }; - } else { - return { metadata: new metadata_1.Metadata(), options: arg1, callback: arg2 }; - } - } else { - if (!(arg1 instanceof metadata_1.Metadata && arg2 instanceof Object && isFunction(arg3))) { - throw new Error("Incorrect arguments passed"); - } - return { metadata: arg1, options: arg2, callback: arg3 }; - } - } - makeUnaryRequest(method, serialize, deserialize, argument, metadata, options, callback) { - var _a, _b; - const checkedArguments = this.checkOptionalUnaryResponseArguments(metadata, options, callback); - const methodDefinition = { - path: method, - requestStream: false, - responseStream: false, - requestSerialize: serialize, - responseDeserialize: deserialize - }; - let callProperties = { - argument, - metadata: checkedArguments.metadata, - call: new call_1.ClientUnaryCallImpl(), - channel: this[CHANNEL_SYMBOL], - methodDefinition, - callOptions: checkedArguments.options, - callback: checkedArguments.callback - }; - if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { - callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); - } - const emitter = callProperties.call; - const interceptorArgs = { - clientInterceptors: this[INTERCEPTOR_SYMBOL], - clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], - callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [], - callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [] - }; - const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); - emitter.call = call; - let responseMessage = null; - let receivedStatus = false; - let callerStackError = new Error(); - call.start(callProperties.metadata, { - onReceiveMetadata: (metadata2) => { - emitter.emit("metadata", metadata2); - }, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - onReceiveMessage(message) { - if (responseMessage !== null) { - call.cancelWithStatus(constants_1.Status.UNIMPLEMENTED, "Too many responses received"); - } - responseMessage = message; - }, - onReceiveStatus(status) { - if (receivedStatus) { - return; - } - receivedStatus = true; - if (status.code === constants_1.Status.OK) { - if (responseMessage === null) { - const callerStack = getErrorStackString(callerStackError); - callProperties.callback((0, call_1.callErrorFromStatus)({ - code: constants_1.Status.UNIMPLEMENTED, - details: "No message received", - metadata: status.metadata - }, callerStack)); - } else { - callProperties.callback(null, responseMessage); - } - } else { - const callerStack = getErrorStackString(callerStackError); - callProperties.callback((0, call_1.callErrorFromStatus)(status, callerStack)); - } - callerStackError = null; - emitter.emit("status", status); - } - }); - call.sendMessage(argument); - call.halfClose(); - return emitter; - } - makeClientStreamRequest(method, serialize, deserialize, metadata, options, callback) { - var _a, _b; - const checkedArguments = this.checkOptionalUnaryResponseArguments(metadata, options, callback); - const methodDefinition = { - path: method, - requestStream: true, - responseStream: false, - requestSerialize: serialize, - responseDeserialize: deserialize - }; - let callProperties = { - metadata: checkedArguments.metadata, - call: new call_1.ClientWritableStreamImpl(serialize), - channel: this[CHANNEL_SYMBOL], - methodDefinition, - callOptions: checkedArguments.options, - callback: checkedArguments.callback - }; - if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { - callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); - } - const emitter = callProperties.call; - const interceptorArgs = { - clientInterceptors: this[INTERCEPTOR_SYMBOL], - clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], - callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [], - callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [] - }; - const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); - emitter.call = call; - let responseMessage = null; - let receivedStatus = false; - let callerStackError = new Error(); - call.start(callProperties.metadata, { - onReceiveMetadata: (metadata2) => { - emitter.emit("metadata", metadata2); - }, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - onReceiveMessage(message) { - if (responseMessage !== null) { - call.cancelWithStatus(constants_1.Status.UNIMPLEMENTED, "Too many responses received"); - } - responseMessage = message; - call.startRead(); - }, - onReceiveStatus(status) { - if (receivedStatus) { - return; - } - receivedStatus = true; - if (status.code === constants_1.Status.OK) { - if (responseMessage === null) { - const callerStack = getErrorStackString(callerStackError); - callProperties.callback((0, call_1.callErrorFromStatus)({ - code: constants_1.Status.UNIMPLEMENTED, - details: "No message received", - metadata: status.metadata - }, callerStack)); - } else { - callProperties.callback(null, responseMessage); - } - } else { - const callerStack = getErrorStackString(callerStackError); - callProperties.callback((0, call_1.callErrorFromStatus)(status, callerStack)); - } - callerStackError = null; - emitter.emit("status", status); - } - }); - return emitter; - } - checkMetadataAndOptions(arg1, arg2) { - let metadata; - let options; - if (arg1 instanceof metadata_1.Metadata) { - metadata = arg1; - if (arg2) { - options = arg2; - } else { - options = {}; - } - } else { - if (arg1) { - options = arg1; - } else { - options = {}; - } - metadata = new metadata_1.Metadata(); - } - return { metadata, options }; - } - makeServerStreamRequest(method, serialize, deserialize, argument, metadata, options) { - var _a, _b; - const checkedArguments = this.checkMetadataAndOptions(metadata, options); - const methodDefinition = { - path: method, - requestStream: false, - responseStream: true, - requestSerialize: serialize, - responseDeserialize: deserialize - }; - let callProperties = { - argument, - metadata: checkedArguments.metadata, - call: new call_1.ClientReadableStreamImpl(deserialize), - channel: this[CHANNEL_SYMBOL], - methodDefinition, - callOptions: checkedArguments.options - }; - if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { - callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); - } - const stream2 = callProperties.call; - const interceptorArgs = { - clientInterceptors: this[INTERCEPTOR_SYMBOL], - clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], - callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [], - callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [] - }; - const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); - stream2.call = call; - let receivedStatus = false; - let callerStackError = new Error(); - call.start(callProperties.metadata, { - onReceiveMetadata(metadata2) { - stream2.emit("metadata", metadata2); - }, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - onReceiveMessage(message) { - stream2.push(message); - }, - onReceiveStatus(status) { - if (receivedStatus) { - return; - } - receivedStatus = true; - stream2.push(null); - if (status.code !== constants_1.Status.OK) { - const callerStack = getErrorStackString(callerStackError); - stream2.emit("error", (0, call_1.callErrorFromStatus)(status, callerStack)); - } - callerStackError = null; - stream2.emit("status", status); - } - }); - call.sendMessage(argument); - call.halfClose(); - return stream2; - } - makeBidiStreamRequest(method, serialize, deserialize, metadata, options) { - var _a, _b; - const checkedArguments = this.checkMetadataAndOptions(metadata, options); - const methodDefinition = { - path: method, - requestStream: true, - responseStream: true, - requestSerialize: serialize, - responseDeserialize: deserialize - }; - let callProperties = { - metadata: checkedArguments.metadata, - call: new call_1.ClientDuplexStreamImpl(serialize, deserialize), - channel: this[CHANNEL_SYMBOL], - methodDefinition, - callOptions: checkedArguments.options - }; - if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { - callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); - } - const stream2 = callProperties.call; - const interceptorArgs = { - clientInterceptors: this[INTERCEPTOR_SYMBOL], - clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], - callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [], - callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [] - }; - const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); - stream2.call = call; - let receivedStatus = false; - let callerStackError = new Error(); - call.start(callProperties.metadata, { - onReceiveMetadata(metadata2) { - stream2.emit("metadata", metadata2); - }, - onReceiveMessage(message) { - stream2.push(message); - }, - onReceiveStatus(status) { - if (receivedStatus) { - return; - } - receivedStatus = true; - stream2.push(null); - if (status.code !== constants_1.Status.OK) { - const callerStack = getErrorStackString(callerStackError); - stream2.emit("error", (0, call_1.callErrorFromStatus)(status, callerStack)); - } - callerStackError = null; - stream2.emit("status", status); - } - }); - return stream2; - } - }; - exports2.Client = Client; - } -}); - -// node_modules/@grpc/grpc-js/build/src/make-client.js -var require_make_client = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/make-client.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.makeClientConstructor = makeClientConstructor; - exports2.loadPackageDefinition = loadPackageDefinition; - var client_1 = require_client3(); - var requesterFuncs = { - unary: client_1.Client.prototype.makeUnaryRequest, - server_stream: client_1.Client.prototype.makeServerStreamRequest, - client_stream: client_1.Client.prototype.makeClientStreamRequest, - bidi: client_1.Client.prototype.makeBidiStreamRequest - }; - function isPrototypePolluted(key) { - return ["__proto__", "prototype", "constructor"].includes(key); - } - function makeClientConstructor(methods, serviceName, classOptions) { - if (!classOptions) { - classOptions = {}; - } - class ServiceClientImpl extends client_1.Client { - } - Object.keys(methods).forEach((name) => { - if (isPrototypePolluted(name)) { - return; - } - const attrs = methods[name]; - let methodType; - if (typeof name === "string" && name.charAt(0) === "$") { - throw new Error("Method names cannot start with $"); - } - if (attrs.requestStream) { - if (attrs.responseStream) { - methodType = "bidi"; - } else { - methodType = "client_stream"; - } - } else { - if (attrs.responseStream) { - methodType = "server_stream"; - } else { - methodType = "unary"; - } - } - const serialize = attrs.requestSerialize; - const deserialize = attrs.responseDeserialize; - const methodFunc = partial(requesterFuncs[methodType], attrs.path, serialize, deserialize); - ServiceClientImpl.prototype[name] = methodFunc; - Object.assign(ServiceClientImpl.prototype[name], attrs); - if (attrs.originalName && !isPrototypePolluted(attrs.originalName)) { - ServiceClientImpl.prototype[attrs.originalName] = ServiceClientImpl.prototype[name]; - } - }); - ServiceClientImpl.service = methods; - ServiceClientImpl.serviceName = serviceName; - return ServiceClientImpl; - } - function partial(fn, path, serialize, deserialize) { - return function(...args) { - return fn.call(this, path, serialize, deserialize, ...args); - }; - } - function isProtobufTypeDefinition(obj) { - return "format" in obj; - } - function loadPackageDefinition(packageDef) { - const result = {}; - for (const serviceFqn in packageDef) { - if (Object.prototype.hasOwnProperty.call(packageDef, serviceFqn)) { - const service = packageDef[serviceFqn]; - const nameComponents = serviceFqn.split("."); - if (nameComponents.some((comp) => isPrototypePolluted(comp))) { - continue; - } - const serviceName = nameComponents[nameComponents.length - 1]; - let current = result; - for (const packageName of nameComponents.slice(0, -1)) { - if (!current[packageName]) { - current[packageName] = {}; - } - current = current[packageName]; - } - if (isProtobufTypeDefinition(service)) { - current[serviceName] = service; - } else { - current[serviceName] = makeClientConstructor(service, serviceName, {}); - } - } - } - return result; - } - } -}); - -// node_modules/lodash.camelcase/index.js -var require_lodash = __commonJS({ - "node_modules/lodash.camelcase/index.js"(exports2, module2) { - var INFINITY = 1 / 0; - var symbolTag = "[object Symbol]"; - var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; - var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; - var rsAstralRange = "\\ud800-\\udfff"; - var rsComboMarksRange = "\\u0300-\\u036f\\ufe20-\\ufe23"; - var rsComboSymbolsRange = "\\u20d0-\\u20f0"; - var rsDingbatRange = "\\u2700-\\u27bf"; - var rsLowerRange = "a-z\\xdf-\\xf6\\xf8-\\xff"; - var rsMathOpRange = "\\xac\\xb1\\xd7\\xf7"; - var rsNonCharRange = "\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf"; - var rsPunctuationRange = "\\u2000-\\u206f"; - var rsSpaceRange = " \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000"; - var rsUpperRange = "A-Z\\xc0-\\xd6\\xd8-\\xde"; - var rsVarRange = "\\ufe0e\\ufe0f"; - var rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; - var rsApos = "['\u2019]"; - var rsAstral = "[" + rsAstralRange + "]"; - var rsBreak = "[" + rsBreakRange + "]"; - var rsCombo = "[" + rsComboMarksRange + rsComboSymbolsRange + "]"; - var rsDigits = "\\d+"; - var rsDingbat = "[" + rsDingbatRange + "]"; - var rsLower = "[" + rsLowerRange + "]"; - var rsMisc = "[^" + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + "]"; - var rsFitz = "\\ud83c[\\udffb-\\udfff]"; - var rsModifier = "(?:" + rsCombo + "|" + rsFitz + ")"; - var rsNonAstral = "[^" + rsAstralRange + "]"; - var rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}"; - var rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]"; - var rsUpper = "[" + rsUpperRange + "]"; - var rsZWJ = "\\u200d"; - var rsLowerMisc = "(?:" + rsLower + "|" + rsMisc + ")"; - var rsUpperMisc = "(?:" + rsUpper + "|" + rsMisc + ")"; - var rsOptLowerContr = "(?:" + rsApos + "(?:d|ll|m|re|s|t|ve))?"; - var rsOptUpperContr = "(?:" + rsApos + "(?:D|LL|M|RE|S|T|VE))?"; - var reOptMod = rsModifier + "?"; - var rsOptVar = "[" + rsVarRange + "]?"; - var rsOptJoin = "(?:" + rsZWJ + "(?:" + [rsNonAstral, rsRegional, rsSurrPair].join("|") + ")" + rsOptVar + reOptMod + ")*"; - var rsSeq = rsOptVar + reOptMod + rsOptJoin; - var rsEmoji = "(?:" + [rsDingbat, rsRegional, rsSurrPair].join("|") + ")" + rsSeq; - var rsSymbol = "(?:" + [rsNonAstral + rsCombo + "?", rsCombo, rsRegional, rsSurrPair, rsAstral].join("|") + ")"; - var reApos = RegExp(rsApos, "g"); - var reComboMark = RegExp(rsCombo, "g"); - var reUnicode = RegExp(rsFitz + "(?=" + rsFitz + ")|" + rsSymbol + rsSeq, "g"); - var reUnicodeWord = RegExp([ - rsUpper + "?" + rsLower + "+" + rsOptLowerContr + "(?=" + [rsBreak, rsUpper, "$"].join("|") + ")", - rsUpperMisc + "+" + rsOptUpperContr + "(?=" + [rsBreak, rsUpper + rsLowerMisc, "$"].join("|") + ")", - rsUpper + "?" + rsLowerMisc + "+" + rsOptLowerContr, - rsUpper + "+" + rsOptUpperContr, - rsDigits, - rsEmoji - ].join("|"), "g"); - var reHasUnicode = RegExp("[" + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + "]"); - var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; - var deburredLetters = { - // Latin-1 Supplement block. - "\xC0": "A", - "\xC1": "A", - "\xC2": "A", - "\xC3": "A", - "\xC4": "A", - "\xC5": "A", - "\xE0": "a", - "\xE1": "a", - "\xE2": "a", - "\xE3": "a", - "\xE4": "a", - "\xE5": "a", - "\xC7": "C", - "\xE7": "c", - "\xD0": "D", - "\xF0": "d", - "\xC8": "E", - "\xC9": "E", - "\xCA": "E", - "\xCB": "E", - "\xE8": "e", - "\xE9": "e", - "\xEA": "e", - "\xEB": "e", - "\xCC": "I", - "\xCD": "I", - "\xCE": "I", - "\xCF": "I", - "\xEC": "i", - "\xED": "i", - "\xEE": "i", - "\xEF": "i", - "\xD1": "N", - "\xF1": "n", - "\xD2": "O", - "\xD3": "O", - "\xD4": "O", - "\xD5": "O", - "\xD6": "O", - "\xD8": "O", - "\xF2": "o", - "\xF3": "o", - "\xF4": "o", - "\xF5": "o", - "\xF6": "o", - "\xF8": "o", - "\xD9": "U", - "\xDA": "U", - "\xDB": "U", - "\xDC": "U", - "\xF9": "u", - "\xFA": "u", - "\xFB": "u", - "\xFC": "u", - "\xDD": "Y", - "\xFD": "y", - "\xFF": "y", - "\xC6": "Ae", - "\xE6": "ae", - "\xDE": "Th", - "\xFE": "th", - "\xDF": "ss", - // Latin Extended-A block. - "\u0100": "A", - "\u0102": "A", - "\u0104": "A", - "\u0101": "a", - "\u0103": "a", - "\u0105": "a", - "\u0106": "C", - "\u0108": "C", - "\u010A": "C", - "\u010C": "C", - "\u0107": "c", - "\u0109": "c", - "\u010B": "c", - "\u010D": "c", - "\u010E": "D", - "\u0110": "D", - "\u010F": "d", - "\u0111": "d", - "\u0112": "E", - "\u0114": "E", - "\u0116": "E", - "\u0118": "E", - "\u011A": "E", - "\u0113": "e", - "\u0115": "e", - "\u0117": "e", - "\u0119": "e", - "\u011B": "e", - "\u011C": "G", - "\u011E": "G", - "\u0120": "G", - "\u0122": "G", - "\u011D": "g", - "\u011F": "g", - "\u0121": "g", - "\u0123": "g", - "\u0124": "H", - "\u0126": "H", - "\u0125": "h", - "\u0127": "h", - "\u0128": "I", - "\u012A": "I", - "\u012C": "I", - "\u012E": "I", - "\u0130": "I", - "\u0129": "i", - "\u012B": "i", - "\u012D": "i", - "\u012F": "i", - "\u0131": "i", - "\u0134": "J", - "\u0135": "j", - "\u0136": "K", - "\u0137": "k", - "\u0138": "k", - "\u0139": "L", - "\u013B": "L", - "\u013D": "L", - "\u013F": "L", - "\u0141": "L", - "\u013A": "l", - "\u013C": "l", - "\u013E": "l", - "\u0140": "l", - "\u0142": "l", - "\u0143": "N", - "\u0145": "N", - "\u0147": "N", - "\u014A": "N", - "\u0144": "n", - "\u0146": "n", - "\u0148": "n", - "\u014B": "n", - "\u014C": "O", - "\u014E": "O", - "\u0150": "O", - "\u014D": "o", - "\u014F": "o", - "\u0151": "o", - "\u0154": "R", - "\u0156": "R", - "\u0158": "R", - "\u0155": "r", - "\u0157": "r", - "\u0159": "r", - "\u015A": "S", - "\u015C": "S", - "\u015E": "S", - "\u0160": "S", - "\u015B": "s", - "\u015D": "s", - "\u015F": "s", - "\u0161": "s", - "\u0162": "T", - "\u0164": "T", - "\u0166": "T", - "\u0163": "t", - "\u0165": "t", - "\u0167": "t", - "\u0168": "U", - "\u016A": "U", - "\u016C": "U", - "\u016E": "U", - "\u0170": "U", - "\u0172": "U", - "\u0169": "u", - "\u016B": "u", - "\u016D": "u", - "\u016F": "u", - "\u0171": "u", - "\u0173": "u", - "\u0174": "W", - "\u0175": "w", - "\u0176": "Y", - "\u0177": "y", - "\u0178": "Y", - "\u0179": "Z", - "\u017B": "Z", - "\u017D": "Z", - "\u017A": "z", - "\u017C": "z", - "\u017E": "z", - "\u0132": "IJ", - "\u0133": "ij", - "\u0152": "Oe", - "\u0153": "oe", - "\u0149": "'n", - "\u017F": "ss" - }; - var freeGlobal = typeof global == "object" && global && global.Object === Object && global; - var freeSelf = typeof self == "object" && self && self.Object === Object && self; - var root = freeGlobal || freeSelf || Function("return this")(); - function arrayReduce(array, iteratee, accumulator, initAccum) { - var index = -1, length = array ? array.length : 0; - if (initAccum && length) { - accumulator = array[++index]; - } - while (++index < length) { - accumulator = iteratee(accumulator, array[index], index, array); - } - return accumulator; - } - function asciiToArray(string) { - return string.split(""); - } - function asciiWords(string) { - return string.match(reAsciiWord) || []; - } - function basePropertyOf(object) { - return function(key) { - return object == null ? void 0 : object[key]; - }; - } - var deburrLetter = basePropertyOf(deburredLetters); - function hasUnicode(string) { - return reHasUnicode.test(string); - } - function hasUnicodeWord(string) { - return reHasUnicodeWord.test(string); - } - function stringToArray(string) { - return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string); - } - function unicodeToArray(string) { - return string.match(reUnicode) || []; - } - function unicodeWords(string) { - return string.match(reUnicodeWord) || []; - } - var objectProto = Object.prototype; - var objectToString = objectProto.toString; - var Symbol2 = root.Symbol; - var symbolProto = Symbol2 ? Symbol2.prototype : void 0; - var symbolToString = symbolProto ? symbolProto.toString : void 0; - function baseSlice(array, start, end) { - var index = -1, length = array.length; - if (start < 0) { - start = -start > length ? 0 : length + start; - } - end = end > length ? length : end; - if (end < 0) { - end += length; - } - length = start > end ? 0 : end - start >>> 0; - start >>>= 0; - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; - } - return result; - } - function baseToString(value) { - if (typeof value == "string") { - return value; - } - if (isSymbol(value)) { - return symbolToString ? symbolToString.call(value) : ""; - } - var result = value + ""; - return result == "0" && 1 / value == -INFINITY ? "-0" : result; - } - function castSlice(array, start, end) { - var length = array.length; - end = end === void 0 ? length : end; - return !start && end >= length ? array : baseSlice(array, start, end); - } - function createCaseFirst(methodName) { - return function(string) { - string = toString(string); - var strSymbols = hasUnicode(string) ? stringToArray(string) : void 0; - var chr = strSymbols ? strSymbols[0] : string.charAt(0); - var trailing = strSymbols ? castSlice(strSymbols, 1).join("") : string.slice(1); - return chr[methodName]() + trailing; - }; - } - function createCompounder(callback) { - return function(string) { - return arrayReduce(words(deburr(string).replace(reApos, "")), callback, ""); - }; - } - function isObjectLike(value) { - return !!value && typeof value == "object"; - } - function isSymbol(value) { - return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag; - } - function toString(value) { - return value == null ? "" : baseToString(value); - } - var camelCase = createCompounder(function(result, word, index) { - word = word.toLowerCase(); - return result + (index ? capitalize(word) : word); - }); - function capitalize(string) { - return upperFirst(toString(string).toLowerCase()); - } - function deburr(string) { - string = toString(string); - return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ""); - } - var upperFirst = createCaseFirst("toUpperCase"); - function words(string, pattern, guard) { - string = toString(string); - pattern = guard ? void 0 : pattern; - if (pattern === void 0) { - return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string); - } - return string.match(pattern) || []; - } - module2.exports = camelCase; - } -}); - -// node_modules/@protobufjs/aspromise/index.js -var require_aspromise = __commonJS({ - "node_modules/@protobufjs/aspromise/index.js"(exports2, module2) { - "use strict"; - module2.exports = asPromise; - function asPromise(fn, ctx) { - var params = new Array(arguments.length - 1), offset = 0, index = 2, pending = true; - while (index < arguments.length) - params[offset++] = arguments[index++]; - return new Promise(function executor(resolve, reject) { - params[offset] = function callback(err) { - if (pending) { - pending = false; - if (err) - reject(err); - else { - var params2 = new Array(arguments.length - 1), offset2 = 0; - while (offset2 < params2.length) - params2[offset2++] = arguments[offset2]; - resolve.apply(null, params2); - } - } - }; - try { - fn.apply(ctx || null, params); - } catch (err) { - if (pending) { - pending = false; - reject(err); - } - } - }); - } - } -}); - -// node_modules/@protobufjs/base64/index.js -var require_base64 = __commonJS({ - "node_modules/@protobufjs/base64/index.js"(exports2) { - "use strict"; - var base64 = exports2; - base64.length = function length(string) { - var p = string.length; - if (!p) - return 0; - var n = 0; - while (--p % 4 > 1 && string.charAt(p) === "=") - ++n; - return Math.ceil(string.length * 3) / 4 - n; - }; - var b64 = new Array(64); - var s64 = new Array(123); - for (i = 0; i < 64; ) - s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++; - var i; - base64.encode = function encode(buffer, start, end) { - var parts = null, chunk = []; - var i2 = 0, j = 0, t; - while (start < end) { - var b = buffer[start++]; - switch (j) { - case 0: - chunk[i2++] = b64[b >> 2]; - t = (b & 3) << 4; - j = 1; - break; - case 1: - chunk[i2++] = b64[t | b >> 4]; - t = (b & 15) << 2; - j = 2; - break; - case 2: - chunk[i2++] = b64[t | b >> 6]; - chunk[i2++] = b64[b & 63]; - j = 0; - break; - } - if (i2 > 8191) { - (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); - i2 = 0; - } - } - if (j) { - chunk[i2++] = b64[t]; - chunk[i2++] = 61; - if (j === 1) - chunk[i2++] = 61; - } - if (parts) { - if (i2) - parts.push(String.fromCharCode.apply(String, chunk.slice(0, i2))); - return parts.join(""); - } - return String.fromCharCode.apply(String, chunk.slice(0, i2)); - }; - var invalidEncoding = "invalid encoding"; - base64.decode = function decode(string, buffer, offset) { - var start = offset; - var j = 0, t; - for (var i2 = 0; i2 < string.length; ) { - var c = string.charCodeAt(i2++); - if (c === 61 && j > 1) - break; - if ((c = s64[c]) === void 0) - throw Error(invalidEncoding); - switch (j) { - case 0: - t = c; - j = 1; - break; - case 1: - buffer[offset++] = t << 2 | (c & 48) >> 4; - t = c; - j = 2; - break; - case 2: - buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2; - t = c; - j = 3; - break; - case 3: - buffer[offset++] = (t & 3) << 6 | c; - j = 0; - break; - } - } - if (j === 1) - throw Error(invalidEncoding); - return offset - start; - }; - base64.test = function test(string) { - return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string); - }; - } -}); - -// node_modules/@protobufjs/eventemitter/index.js -var require_eventemitter = __commonJS({ - "node_modules/@protobufjs/eventemitter/index.js"(exports2, module2) { - "use strict"; - module2.exports = EventEmitter; - function EventEmitter() { - this._listeners = {}; - } - EventEmitter.prototype.on = function on(evt, fn, ctx) { - (this._listeners[evt] || (this._listeners[evt] = [])).push({ - fn, - ctx: ctx || this - }); - return this; - }; - EventEmitter.prototype.off = function off(evt, fn) { - if (evt === void 0) - this._listeners = {}; - else { - if (fn === void 0) - this._listeners[evt] = []; - else { - var listeners = this._listeners[evt]; - for (var i = 0; i < listeners.length; ) - if (listeners[i].fn === fn) - listeners.splice(i, 1); - else - ++i; - } - } - return this; - }; - EventEmitter.prototype.emit = function emit(evt) { - var listeners = this._listeners[evt]; - if (listeners) { - var args = [], i = 1; - for (; i < arguments.length; ) - args.push(arguments[i++]); - for (i = 0; i < listeners.length; ) - listeners[i].fn.apply(listeners[i++].ctx, args); - } - return this; - }; - } -}); - -// node_modules/@protobufjs/float/index.js -var require_float = __commonJS({ - "node_modules/@protobufjs/float/index.js"(exports2, module2) { - "use strict"; - module2.exports = factory(factory); - function factory(exports3) { - if (typeof Float32Array !== "undefined") (function() { - var f32 = new Float32Array([-0]), f8b = new Uint8Array(f32.buffer), le = f8b[3] === 128; - function writeFloat_f32_cpy(val, buf, pos) { - f32[0] = val; - buf[pos] = f8b[0]; - buf[pos + 1] = f8b[1]; - buf[pos + 2] = f8b[2]; - buf[pos + 3] = f8b[3]; - } - function writeFloat_f32_rev(val, buf, pos) { - f32[0] = val; - buf[pos] = f8b[3]; - buf[pos + 1] = f8b[2]; - buf[pos + 2] = f8b[1]; - buf[pos + 3] = f8b[0]; - } - exports3.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev; - exports3.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy; - function readFloat_f32_cpy(buf, pos) { - f8b[0] = buf[pos]; - f8b[1] = buf[pos + 1]; - f8b[2] = buf[pos + 2]; - f8b[3] = buf[pos + 3]; - return f32[0]; - } - function readFloat_f32_rev(buf, pos) { - f8b[3] = buf[pos]; - f8b[2] = buf[pos + 1]; - f8b[1] = buf[pos + 2]; - f8b[0] = buf[pos + 3]; - return f32[0]; - } - exports3.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev; - exports3.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy; - })(); - else (function() { - function writeFloat_ieee754(writeUint, val, buf, pos) { - var sign = val < 0 ? 1 : 0; - if (sign) - val = -val; - if (val === 0) - writeUint(1 / val > 0 ? ( - /* positive */ - 0 - ) : ( - /* negative 0 */ - 2147483648 - ), buf, pos); - else if (isNaN(val)) - writeUint(2143289344, buf, pos); - else if (val > 34028234663852886e22) - writeUint((sign << 31 | 2139095040) >>> 0, buf, pos); - else if (val < 11754943508222875e-54) - writeUint((sign << 31 | Math.round(val / 1401298464324817e-60)) >>> 0, buf, pos); - else { - var exponent = Math.floor(Math.log(val) / Math.LN2), mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607; - writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos); - } - } - exports3.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE); - exports3.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE); - function readFloat_ieee754(readUint, buf, pos) { - var uint = readUint(buf, pos), sign = (uint >> 31) * 2 + 1, exponent = uint >>> 23 & 255, mantissa = uint & 8388607; - return exponent === 255 ? mantissa ? NaN : sign * Infinity : exponent === 0 ? sign * 1401298464324817e-60 * mantissa : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608); - } - exports3.readFloatLE = readFloat_ieee754.bind(null, readUintLE); - exports3.readFloatBE = readFloat_ieee754.bind(null, readUintBE); - })(); - if (typeof Float64Array !== "undefined") (function() { - var f64 = new Float64Array([-0]), f8b = new Uint8Array(f64.buffer), le = f8b[7] === 128; - function writeDouble_f64_cpy(val, buf, pos) { - f64[0] = val; - buf[pos] = f8b[0]; - buf[pos + 1] = f8b[1]; - buf[pos + 2] = f8b[2]; - buf[pos + 3] = f8b[3]; - buf[pos + 4] = f8b[4]; - buf[pos + 5] = f8b[5]; - buf[pos + 6] = f8b[6]; - buf[pos + 7] = f8b[7]; - } - function writeDouble_f64_rev(val, buf, pos) { - f64[0] = val; - buf[pos] = f8b[7]; - buf[pos + 1] = f8b[6]; - buf[pos + 2] = f8b[5]; - buf[pos + 3] = f8b[4]; - buf[pos + 4] = f8b[3]; - buf[pos + 5] = f8b[2]; - buf[pos + 6] = f8b[1]; - buf[pos + 7] = f8b[0]; - } - exports3.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev; - exports3.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy; - function readDouble_f64_cpy(buf, pos) { - f8b[0] = buf[pos]; - f8b[1] = buf[pos + 1]; - f8b[2] = buf[pos + 2]; - f8b[3] = buf[pos + 3]; - f8b[4] = buf[pos + 4]; - f8b[5] = buf[pos + 5]; - f8b[6] = buf[pos + 6]; - f8b[7] = buf[pos + 7]; - return f64[0]; - } - function readDouble_f64_rev(buf, pos) { - f8b[7] = buf[pos]; - f8b[6] = buf[pos + 1]; - f8b[5] = buf[pos + 2]; - f8b[4] = buf[pos + 3]; - f8b[3] = buf[pos + 4]; - f8b[2] = buf[pos + 5]; - f8b[1] = buf[pos + 6]; - f8b[0] = buf[pos + 7]; - return f64[0]; - } - exports3.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev; - exports3.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy; - })(); - else (function() { - function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) { - var sign = val < 0 ? 1 : 0; - if (sign) - val = -val; - if (val === 0) { - writeUint(0, buf, pos + off0); - writeUint(1 / val > 0 ? ( - /* positive */ - 0 - ) : ( - /* negative 0 */ - 2147483648 - ), buf, pos + off1); - } else if (isNaN(val)) { - writeUint(0, buf, pos + off0); - writeUint(2146959360, buf, pos + off1); - } else if (val > 17976931348623157e292) { - writeUint(0, buf, pos + off0); - writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1); - } else { - var mantissa; - if (val < 22250738585072014e-324) { - mantissa = val / 5e-324; - writeUint(mantissa >>> 0, buf, pos + off0); - writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1); - } else { - var exponent = Math.floor(Math.log(val) / Math.LN2); - if (exponent === 1024) - exponent = 1023; - mantissa = val * Math.pow(2, -exponent); - writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0); - writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1); - } - } - } - exports3.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4); - exports3.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0); - function readDouble_ieee754(readUint, off0, off1, buf, pos) { - var lo = readUint(buf, pos + off0), hi = readUint(buf, pos + off1); - var sign = (hi >> 31) * 2 + 1, exponent = hi >>> 20 & 2047, mantissa = 4294967296 * (hi & 1048575) + lo; - return exponent === 2047 ? mantissa ? NaN : sign * Infinity : exponent === 0 ? sign * 5e-324 * mantissa : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496); - } - exports3.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4); - exports3.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0); - })(); - return exports3; - } - function writeUintLE(val, buf, pos) { - buf[pos] = val & 255; - buf[pos + 1] = val >>> 8 & 255; - buf[pos + 2] = val >>> 16 & 255; - buf[pos + 3] = val >>> 24; - } - function writeUintBE(val, buf, pos) { - buf[pos] = val >>> 24; - buf[pos + 1] = val >>> 16 & 255; - buf[pos + 2] = val >>> 8 & 255; - buf[pos + 3] = val & 255; - } - function readUintLE(buf, pos) { - return (buf[pos] | buf[pos + 1] << 8 | buf[pos + 2] << 16 | buf[pos + 3] << 24) >>> 0; - } - function readUintBE(buf, pos) { - return (buf[pos] << 24 | buf[pos + 1] << 16 | buf[pos + 2] << 8 | buf[pos + 3]) >>> 0; - } - } -}); - -// node_modules/@protobufjs/inquire/index.js -var require_inquire = __commonJS({ - "node_modules/@protobufjs/inquire/index.js"(exports2, module2) { - "use strict"; - module2.exports = inquire; - function inquire(moduleName) { - try { - if (typeof require !== "function") { - return null; - } - var mod = require(moduleName); - if (mod && (mod.length || Object.keys(mod).length)) return mod; - return null; - } catch (err) { - return null; - } - } - } -}); - -// node_modules/@protobufjs/utf8/index.js -var require_utf8 = __commonJS({ - "node_modules/@protobufjs/utf8/index.js"(exports2) { - "use strict"; - var utf8 = exports2; - var replacementChar = "\uFFFD"; - utf8.length = function utf8_length(string) { - var len = 0, c = 0; - for (var i = 0; i < string.length; ++i) { - c = string.charCodeAt(i); - if (c < 128) - len += 1; - else if (c < 2048) - len += 2; - else if ((c & 64512) === 55296 && (string.charCodeAt(i + 1) & 64512) === 56320) { - ++i; - len += 4; - } else - len += 3; - } - return len; - }; - utf8.read = function utf8_read(buffer, start, end) { - if (end - start < 1) { - return ""; - } - var str = ""; - for (var i = start; i < end; ) { - var t = buffer[i++]; - if (t <= 127) { - str += String.fromCharCode(t); - } else if (t >= 192 && t < 224) { - var c2 = (t & 31) << 6 | buffer[i++] & 63; - str += c2 >= 128 ? String.fromCharCode(c2) : replacementChar; - } else if (t >= 224 && t < 240) { - var c3 = (t & 15) << 12 | (buffer[i++] & 63) << 6 | buffer[i++] & 63; - str += c3 >= 2048 ? String.fromCharCode(c3) : replacementChar; - } else if (t >= 240) { - var t2 = (t & 7) << 18 | (buffer[i++] & 63) << 12 | (buffer[i++] & 63) << 6 | buffer[i++] & 63; - if (t2 < 65536 || t2 > 1114111) - str += replacementChar; - else { - t2 -= 65536; - str += String.fromCharCode(55296 + (t2 >> 10)); - str += String.fromCharCode(56320 + (t2 & 1023)); - } - } - } - return str; - }; - utf8.write = function utf8_write(string, buffer, offset) { - var start = offset, c1, c2; - for (var i = 0; i < string.length; ++i) { - c1 = string.charCodeAt(i); - if (c1 < 128) { - buffer[offset++] = c1; - } else if (c1 < 2048) { - buffer[offset++] = c1 >> 6 | 192; - buffer[offset++] = c1 & 63 | 128; - } else if ((c1 & 64512) === 55296 && ((c2 = string.charCodeAt(i + 1)) & 64512) === 56320) { - c1 = 65536 + ((c1 & 1023) << 10) + (c2 & 1023); - ++i; - buffer[offset++] = c1 >> 18 | 240; - buffer[offset++] = c1 >> 12 & 63 | 128; - buffer[offset++] = c1 >> 6 & 63 | 128; - buffer[offset++] = c1 & 63 | 128; - } else { - buffer[offset++] = c1 >> 12 | 224; - buffer[offset++] = c1 >> 6 & 63 | 128; - buffer[offset++] = c1 & 63 | 128; - } - } - return offset - start; - }; - } -}); - -// node_modules/@protobufjs/pool/index.js -var require_pool2 = __commonJS({ - "node_modules/@protobufjs/pool/index.js"(exports2, module2) { - "use strict"; - module2.exports = pool; - function pool(alloc, slice, size) { - var SIZE = size || 8192; - var MAX = SIZE >>> 1; - var slab = null; - var offset = SIZE; - return function pool_alloc(size2) { - if (size2 < 1 || size2 > MAX) - return alloc(size2); - if (offset + size2 > SIZE) { - slab = alloc(SIZE); - offset = 0; - } - var buf = slice.call(slab, offset, offset += size2); - if (offset & 7) - offset = (offset | 7) + 1; - return buf; - }; - } - } -}); - -// node_modules/protobufjs/src/util/longbits.js -var require_longbits = __commonJS({ - "node_modules/protobufjs/src/util/longbits.js"(exports2, module2) { - "use strict"; - module2.exports = LongBits; - var util = require_minimal(); - function LongBits(lo, hi) { - this.lo = lo >>> 0; - this.hi = hi >>> 0; - } - var zero = LongBits.zero = new LongBits(0, 0); - zero.toNumber = function() { - return 0; - }; - zero.zzEncode = zero.zzDecode = function() { - return this; - }; - zero.length = function() { - return 1; - }; - var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0"; - LongBits.fromNumber = function fromNumber(value) { - if (value === 0) - return zero; - var sign = value < 0; - if (sign) - value = -value; - var lo = value >>> 0, hi = (value - lo) / 4294967296 >>> 0; - if (sign) { - hi = ~hi >>> 0; - lo = ~lo >>> 0; - if (++lo > 4294967295) { - lo = 0; - if (++hi > 4294967295) - hi = 0; - } - } - return new LongBits(lo, hi); - }; - LongBits.from = function from(value) { - if (typeof value === "number") - return LongBits.fromNumber(value); - if (util.isString(value)) { - if (util.Long) - value = util.Long.fromString(value); - else - return LongBits.fromNumber(parseInt(value, 10)); - } - return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero; - }; - LongBits.prototype.toNumber = function toNumber(unsigned) { - if (!unsigned && this.hi >>> 31) { - var lo = ~this.lo + 1 >>> 0, hi = ~this.hi >>> 0; - if (!lo) - hi = hi + 1 >>> 0; - return -(lo + hi * 4294967296); - } - return this.lo + this.hi * 4294967296; - }; - LongBits.prototype.toLong = function toLong(unsigned) { - return util.Long ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned)) : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) }; - }; - var charCodeAt = String.prototype.charCodeAt; - LongBits.fromHash = function fromHash(hash) { - if (hash === zeroHash) - return zero; - return new LongBits( - (charCodeAt.call(hash, 0) | charCodeAt.call(hash, 1) << 8 | charCodeAt.call(hash, 2) << 16 | charCodeAt.call(hash, 3) << 24) >>> 0, - (charCodeAt.call(hash, 4) | charCodeAt.call(hash, 5) << 8 | charCodeAt.call(hash, 6) << 16 | charCodeAt.call(hash, 7) << 24) >>> 0 - ); - }; - LongBits.prototype.toHash = function toHash() { - return String.fromCharCode( - this.lo & 255, - this.lo >>> 8 & 255, - this.lo >>> 16 & 255, - this.lo >>> 24, - this.hi & 255, - this.hi >>> 8 & 255, - this.hi >>> 16 & 255, - this.hi >>> 24 - ); - }; - LongBits.prototype.zzEncode = function zzEncode() { - var mask = this.hi >> 31; - this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0; - this.lo = (this.lo << 1 ^ mask) >>> 0; - return this; - }; - LongBits.prototype.zzDecode = function zzDecode() { - var mask = -(this.lo & 1); - this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0; - this.hi = (this.hi >>> 1 ^ mask) >>> 0; - return this; - }; - LongBits.prototype.length = function length() { - var part0 = this.lo, part1 = (this.lo >>> 28 | this.hi << 4) >>> 0, part2 = this.hi >>> 24; - return part2 === 0 ? part1 === 0 ? part0 < 16384 ? part0 < 128 ? 1 : 2 : part0 < 2097152 ? 3 : 4 : part1 < 16384 ? part1 < 128 ? 5 : 6 : part1 < 2097152 ? 7 : 8 : part2 < 128 ? 9 : 10; - }; - } -}); - -// node_modules/protobufjs/src/util/minimal.js -var require_minimal = __commonJS({ - "node_modules/protobufjs/src/util/minimal.js"(exports2) { - "use strict"; - var util = exports2; - util.asPromise = require_aspromise(); - util.base64 = require_base64(); - util.EventEmitter = require_eventemitter(); - util.float = require_float(); - util.inquire = require_inquire(); - util.utf8 = require_utf8(); - util.pool = require_pool2(); - util.LongBits = require_longbits(); - util.isNode = Boolean(typeof global !== "undefined" && global && global.process && global.process.versions && global.process.versions.node); - util.global = util.isNode && global || typeof window !== "undefined" && window || typeof self !== "undefined" && self || exports2; - util.emptyArray = Object.freeze ? Object.freeze([]) : ( - /* istanbul ignore next */ - [] - ); - util.emptyObject = Object.freeze ? Object.freeze({}) : ( - /* istanbul ignore next */ - {} - ); - util.isInteger = Number.isInteger || /* istanbul ignore next */ - function isInteger(value) { - return typeof value === "number" && isFinite(value) && Math.floor(value) === value; - }; - util.isString = function isString(value) { - return typeof value === "string" || value instanceof String; - }; - util.isObject = function isObject(value) { - return value && typeof value === "object"; - }; - util.isset = /** - * Checks if a property on a message is considered to be present. - * @param {Object} obj Plain object or message instance - * @param {string} prop Property name - * @returns {boolean} `true` if considered to be present, otherwise `false` - */ - util.isSet = function isSet(obj, prop) { - var value = obj[prop]; - if (value != null && obj.hasOwnProperty(prop)) - return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0; - return false; - }; - util.Buffer = (function() { - try { - var Buffer2 = util.inquire("buffer").Buffer; - return Buffer2.prototype.utf8Write ? Buffer2 : ( - /* istanbul ignore next */ - null - ); - } catch (e) { - return null; - } - })(); - util._Buffer_from = null; - util._Buffer_allocUnsafe = null; - util.newBuffer = function newBuffer(sizeOrArray) { - return typeof sizeOrArray === "number" ? util.Buffer ? util._Buffer_allocUnsafe(sizeOrArray) : new util.Array(sizeOrArray) : util.Buffer ? util._Buffer_from(sizeOrArray) : typeof Uint8Array === "undefined" ? sizeOrArray : new Uint8Array(sizeOrArray); - }; - util.Array = typeof Uint8Array !== "undefined" ? Uint8Array : Array; - util.Long = /* istanbul ignore next */ - util.global.dcodeIO && /* istanbul ignore next */ - util.global.dcodeIO.Long || /* istanbul ignore next */ - util.global.Long || util.inquire("long"); - util.key2Re = /^true|false|0|1$/; - util.key32Re = /^-?(?:0|[1-9][0-9]*)$/; - util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/; - util.longToHash = function longToHash(value) { - return value ? util.LongBits.from(value).toHash() : util.LongBits.zeroHash; - }; - util.longFromHash = function longFromHash(hash, unsigned) { - var bits = util.LongBits.fromHash(hash); - if (util.Long) - return util.Long.fromBits(bits.lo, bits.hi, unsigned); - return bits.toNumber(Boolean(unsigned)); - }; - function merge2(dst, src, ifNotSet) { - for (var keys = Object.keys(src), i = 0; i < keys.length; ++i) - if (dst[keys[i]] === void 0 || !ifNotSet) { - if (keys[i] !== "__proto__") - dst[keys[i]] = src[keys[i]]; - } - return dst; - } - util.merge = merge2; - util.recursionLimit = 100; - util.makeProp = function makeProp(obj, key) { - Object.defineProperty(obj, key, { - enumerable: true, - configurable: true, - writable: true - }); - }; - util.lcFirst = function lcFirst(str) { - return str.charAt(0).toLowerCase() + str.substring(1); - }; - function newError(name) { - function CustomError(message, properties) { - if (!(this instanceof CustomError)) - return new CustomError(message, properties); - Object.defineProperty(this, "message", { get: function() { - return message; - } }); - if (Error.captureStackTrace) - Error.captureStackTrace(this, CustomError); - else - Object.defineProperty(this, "stack", { value: new Error().stack || "" }); - if (properties) - merge2(this, properties); - } - CustomError.prototype = Object.create(Error.prototype, { - constructor: { - value: CustomError, - writable: true, - enumerable: false, - configurable: true - }, - name: { - get: function get() { - return name; - }, - set: void 0, - enumerable: false, - // configurable: false would accurately preserve the behavior of - // the original, but I'm guessing that was not intentional. - // For an actual error subclass, this property would - // be configurable. - configurable: true - }, - toString: { - value: function value() { - return this.name + ": " + this.message; - }, - writable: true, - enumerable: false, - configurable: true - } - }); - return CustomError; - } - util.newError = newError; - util.ProtocolError = newError("ProtocolError"); - util.oneOfGetter = function getOneOf(fieldNames) { - var fieldMap = {}; - for (var i = 0; i < fieldNames.length; ++i) - fieldMap[fieldNames[i]] = 1; - return function() { - for (var keys = Object.keys(this), i2 = keys.length - 1; i2 > -1; --i2) - if (fieldMap[keys[i2]] === 1 && this[keys[i2]] !== void 0 && this[keys[i2]] !== null) - return keys[i2]; - }; - }; - util.oneOfSetter = function setOneOf(fieldNames) { - return function(name) { - for (var i = 0; i < fieldNames.length; ++i) - if (fieldNames[i] !== name) - delete this[fieldNames[i]]; - }; - }; - util.toJSONOptions = { - longs: String, - enums: String, - bytes: String, - json: true - }; - util._configure = function() { - var Buffer2 = util.Buffer; - if (!Buffer2) { - util._Buffer_from = util._Buffer_allocUnsafe = null; - return; - } - util._Buffer_from = Buffer2.from !== Uint8Array.from && Buffer2.from || /* istanbul ignore next */ - function Buffer_from(value, encoding) { - return new Buffer2(value, encoding); - }; - util._Buffer_allocUnsafe = Buffer2.allocUnsafe || /* istanbul ignore next */ - function Buffer_allocUnsafe(size) { - return new Buffer2(size); - }; - }; - } -}); - -// node_modules/protobufjs/src/writer.js -var require_writer2 = __commonJS({ - "node_modules/protobufjs/src/writer.js"(exports2, module2) { - "use strict"; - module2.exports = Writer; - var util = require_minimal(); - var BufferWriter; - var LongBits = util.LongBits; - var base64 = util.base64; - var utf8 = util.utf8; - function Op(fn, len, val) { - this.fn = fn; - this.len = len; - this.next = void 0; - this.val = val; - } - function noop3() { - } - function State(writer) { - this.head = writer.head; - this.tail = writer.tail; - this.len = writer.len; - this.next = writer.states; - } - function Writer() { - this.len = 0; - this.head = new Op(noop3, 0, 0); - this.tail = this.head; - this.states = null; - } - var create = function create2() { - return util.Buffer ? function create_buffer_setup() { - return (Writer.create = function create_buffer() { - return new BufferWriter(); - })(); - } : function create_array() { - return new Writer(); - }; - }; - Writer.create = create(); - Writer.alloc = function alloc(size) { - return new util.Array(size); - }; - if (util.Array !== Array) - Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray); - Writer.prototype._push = function push(fn, len, val) { - this.tail = this.tail.next = new Op(fn, len, val); - this.len += len; - return this; - }; - function writeByte(val, buf, pos) { - buf[pos] = val & 255; - } - function writeVarint32(val, buf, pos) { - while (val > 127) { - buf[pos++] = val & 127 | 128; - val >>>= 7; - } - buf[pos] = val; - } - function VarintOp(len, val) { - this.len = len; - this.next = void 0; - this.val = val; - } - VarintOp.prototype = Object.create(Op.prototype); - VarintOp.prototype.fn = writeVarint32; - Writer.prototype.uint32 = function write_uint32(value) { - this.len += (this.tail = this.tail.next = new VarintOp( - (value = value >>> 0) < 128 ? 1 : value < 16384 ? 2 : value < 2097152 ? 3 : value < 268435456 ? 4 : 5, - value - )).len; - return this; - }; - Writer.prototype.int32 = function write_int32(value) { - return value < 0 ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) : this.uint32(value); - }; - Writer.prototype.sint32 = function write_sint32(value) { - return this.uint32((value << 1 ^ value >> 31) >>> 0); - }; - function writeVarint64(val, buf, pos) { - while (val.hi) { - buf[pos++] = val.lo & 127 | 128; - val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0; - val.hi >>>= 7; - } - while (val.lo > 127) { - buf[pos++] = val.lo & 127 | 128; - val.lo = val.lo >>> 7; - } - buf[pos++] = val.lo; - } - Writer.prototype.uint64 = function write_uint64(value) { - var bits = LongBits.from(value); - return this._push(writeVarint64, bits.length(), bits); - }; - Writer.prototype.int64 = Writer.prototype.uint64; - Writer.prototype.sint64 = function write_sint64(value) { - var bits = LongBits.from(value).zzEncode(); - return this._push(writeVarint64, bits.length(), bits); - }; - Writer.prototype.bool = function write_bool(value) { - return this._push(writeByte, 1, value ? 1 : 0); - }; - function writeFixed32(val, buf, pos) { - buf[pos] = val & 255; - buf[pos + 1] = val >>> 8 & 255; - buf[pos + 2] = val >>> 16 & 255; - buf[pos + 3] = val >>> 24; - } - Writer.prototype.fixed32 = function write_fixed32(value) { - return this._push(writeFixed32, 4, value >>> 0); - }; - Writer.prototype.sfixed32 = Writer.prototype.fixed32; - Writer.prototype.fixed64 = function write_fixed64(value) { - var bits = LongBits.from(value); - return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi); - }; - Writer.prototype.sfixed64 = Writer.prototype.fixed64; - Writer.prototype.float = function write_float(value) { - return this._push(util.float.writeFloatLE, 4, value); - }; - Writer.prototype.double = function write_double(value) { - return this._push(util.float.writeDoubleLE, 8, value); - }; - var writeBytes = util.Array.prototype.set ? function writeBytes_set(val, buf, pos) { - buf.set(val, pos); - } : function writeBytes_for(val, buf, pos) { - for (var i = 0; i < val.length; ++i) - buf[pos + i] = val[i]; - }; - Writer.prototype.bytes = function write_bytes(value) { - var len = value.length >>> 0; - if (!len) - return this._push(writeByte, 1, 0); - if (util.isString(value)) { - var buf = Writer.alloc(len = base64.length(value)); - base64.decode(value, buf, 0); - value = buf; - } - return this.uint32(len)._push(writeBytes, len, value); - }; - Writer.prototype.string = function write_string(value) { - var len = utf8.length(value); - return len ? this.uint32(len)._push(utf8.write, len, value) : this._push(writeByte, 1, 0); - }; - Writer.prototype.fork = function fork() { - this.states = new State(this); - this.head = this.tail = new Op(noop3, 0, 0); - this.len = 0; - return this; - }; - Writer.prototype.reset = function reset() { - if (this.states) { - this.head = this.states.head; - this.tail = this.states.tail; - this.len = this.states.len; - this.states = this.states.next; - } else { - this.head = this.tail = new Op(noop3, 0, 0); - this.len = 0; - } - return this; - }; - Writer.prototype.ldelim = function ldelim() { - var head = this.head, tail = this.tail, len = this.len; - this.reset().uint32(len); - if (len) { - this.tail.next = head.next; - this.tail = tail; - this.len += len; - } - return this; - }; - Writer.prototype.finish = function finish() { - var head = this.head.next, buf = this.constructor.alloc(this.len), pos = 0; - while (head) { - head.fn(head.val, buf, pos); - pos += head.len; - head = head.next; - } - return buf; - }; - Writer._configure = function(BufferWriter_) { - BufferWriter = BufferWriter_; - Writer.create = create(); - BufferWriter._configure(); - }; - } -}); - -// node_modules/protobufjs/src/writer_buffer.js -var require_writer_buffer = __commonJS({ - "node_modules/protobufjs/src/writer_buffer.js"(exports2, module2) { - "use strict"; - module2.exports = BufferWriter; - var Writer = require_writer2(); - (BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter; - var util = require_minimal(); - function BufferWriter() { - Writer.call(this); - } - BufferWriter._configure = function() { - BufferWriter.alloc = util._Buffer_allocUnsafe; - BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === "set" ? function writeBytesBuffer_set(val, buf, pos) { - buf.set(val, pos); - } : function writeBytesBuffer_copy(val, buf, pos) { - if (val.copy) - val.copy(buf, pos, 0, val.length); - else for (var i = 0; i < val.length; ) - buf[pos++] = val[i++]; - }; - }; - BufferWriter.prototype.bytes = function write_bytes_buffer(value) { - if (util.isString(value)) - value = util._Buffer_from(value, "base64"); - var len = value.length >>> 0; - this.uint32(len); - if (len) - this._push(BufferWriter.writeBytesBuffer, len, value); - return this; - }; - function writeStringBuffer(val, buf, pos) { - if (val.length < 40) - util.utf8.write(val, buf, pos); - else if (buf.utf8Write) - buf.utf8Write(val, pos); - else - buf.write(val, pos); - } - BufferWriter.prototype.string = function write_string_buffer(value) { - var len = util.Buffer.byteLength(value); - this.uint32(len); - if (len) - this._push(writeStringBuffer, len, value); - return this; - }; - BufferWriter._configure(); - } -}); - -// node_modules/protobufjs/src/reader.js -var require_reader2 = __commonJS({ - "node_modules/protobufjs/src/reader.js"(exports2, module2) { - "use strict"; - module2.exports = Reader; - var util = require_minimal(); - var BufferReader; - var LongBits = util.LongBits; - var utf8 = util.utf8; - function indexOutOfRange(reader, writeLength) { - return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len); - } - function Reader(buffer) { - this.buf = buffer; - this.pos = 0; - this.len = buffer.length; - } - var create_array = typeof Uint8Array !== "undefined" ? function create_typed_array(buffer) { - if (buffer instanceof Uint8Array || Array.isArray(buffer)) - return new Reader(buffer); - throw Error("illegal buffer"); - } : function create_array2(buffer) { - if (Array.isArray(buffer)) - return new Reader(buffer); - throw Error("illegal buffer"); - }; - var create = function create2() { - return util.Buffer ? function create_buffer_setup(buffer) { - return (Reader.create = function create_buffer(buffer2) { - return util.Buffer.isBuffer(buffer2) ? new BufferReader(buffer2) : create_array(buffer2); - })(buffer); - } : create_array; - }; - Reader.create = create(); - Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ - util.Array.prototype.slice; - Reader.prototype.uint32 = /* @__PURE__ */ (function read_uint32_setup() { - var value = 4294967295; - return function read_uint32() { - value = (this.buf[this.pos] & 127) >>> 0; - if (this.buf[this.pos++] < 128) return value; - value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; - if (this.buf[this.pos++] < 128) return value; - value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; - if (this.buf[this.pos++] < 128) return value; - value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; - if (this.buf[this.pos++] < 128) return value; - value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; - if (this.buf[this.pos++] < 128) return value; - if ((this.pos += 5) > this.len) { - this.pos = this.len; - throw indexOutOfRange(this, 10); - } - return value; - }; - })(); - Reader.prototype.int32 = function read_int32() { - return this.uint32() | 0; - }; - Reader.prototype.sint32 = function read_sint32() { - var value = this.uint32(); - return value >>> 1 ^ -(value & 1) | 0; - }; - function readLongVarint() { - var bits = new LongBits(0, 0); - var i = 0; - if (this.len - this.pos > 4) { - for (; i < 4; ++i) { - bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - } - bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0; - bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - i = 0; - } else { - for (; i < 3; ++i) { - if (this.pos >= this.len) - throw indexOutOfRange(this); - bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - } - bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0; - return bits; - } - if (this.len - this.pos > 4) { - for (; i < 5; ++i) { - bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - } - } else { - for (; i < 5; ++i) { - if (this.pos >= this.len) - throw indexOutOfRange(this); - bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - } - } - throw Error("invalid varint encoding"); - } - Reader.prototype.bool = function read_bool() { - return this.uint32() !== 0; - }; - function readFixed32_end(buf, end) { - return (buf[end - 4] | buf[end - 3] << 8 | buf[end - 2] << 16 | buf[end - 1] << 24) >>> 0; - } - Reader.prototype.fixed32 = function read_fixed32() { - if (this.pos + 4 > this.len) - throw indexOutOfRange(this, 4); - return readFixed32_end(this.buf, this.pos += 4); - }; - Reader.prototype.sfixed32 = function read_sfixed32() { - if (this.pos + 4 > this.len) - throw indexOutOfRange(this, 4); - return readFixed32_end(this.buf, this.pos += 4) | 0; - }; - function readFixed64() { - if (this.pos + 8 > this.len) - throw indexOutOfRange(this, 8); - return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4)); - } - Reader.prototype.float = function read_float() { - if (this.pos + 4 > this.len) - throw indexOutOfRange(this, 4); - var value = util.float.readFloatLE(this.buf, this.pos); - this.pos += 4; - return value; - }; - Reader.prototype.double = function read_double() { - if (this.pos + 8 > this.len) - throw indexOutOfRange(this, 4); - var value = util.float.readDoubleLE(this.buf, this.pos); - this.pos += 8; - return value; - }; - Reader.prototype.bytes = function read_bytes() { - var length = this.uint32(), start = this.pos, end = this.pos + length; - if (end > this.len) - throw indexOutOfRange(this, length); - this.pos += length; - if (Array.isArray(this.buf)) - return this.buf.slice(start, end); - if (start === end) { - var nativeBuffer = util.Buffer; - return nativeBuffer ? nativeBuffer.alloc(0) : new this.buf.constructor(0); - } - return this._slice.call(this.buf, start, end); - }; - Reader.prototype.string = function read_string() { - var bytes = this.bytes(); - return utf8.read(bytes, 0, bytes.length); - }; - Reader.prototype.skip = function skip(length) { - if (typeof length === "number") { - if (this.pos + length > this.len) - throw indexOutOfRange(this, length); - this.pos += length; - } else { - do { - if (this.pos >= this.len) - throw indexOutOfRange(this); - } while (this.buf[this.pos++] & 128); - } - return this; - }; - Reader.recursionLimit = util.recursionLimit; - Reader.prototype.skipType = function(wireType, depth) { - if (depth === void 0) depth = 0; - if (depth > Reader.recursionLimit) - throw Error("maximum nesting depth exceeded"); - switch (wireType) { - case 0: - this.skip(); - break; - case 1: - this.skip(8); - break; - case 2: - this.skip(this.uint32()); - break; - case 3: - while ((wireType = this.uint32() & 7) !== 4) { - this.skipType(wireType, depth + 1); - } - break; - case 5: - this.skip(4); - break; - /* istanbul ignore next */ - default: - throw Error("invalid wire type " + wireType + " at offset " + this.pos); - } - return this; - }; - Reader._configure = function(BufferReader_) { - BufferReader = BufferReader_; - Reader.create = create(); - BufferReader._configure(); - var fn = util.Long ? "toLong" : ( - /* istanbul ignore next */ - "toNumber" - ); - util.merge(Reader.prototype, { - int64: function read_int64() { - return readLongVarint.call(this)[fn](false); - }, - uint64: function read_uint64() { - return readLongVarint.call(this)[fn](true); - }, - sint64: function read_sint64() { - return readLongVarint.call(this).zzDecode()[fn](false); - }, - fixed64: function read_fixed64() { - return readFixed64.call(this)[fn](true); - }, - sfixed64: function read_sfixed64() { - return readFixed64.call(this)[fn](false); - } - }); - }; - } -}); - -// node_modules/protobufjs/src/reader_buffer.js -var require_reader_buffer = __commonJS({ - "node_modules/protobufjs/src/reader_buffer.js"(exports2, module2) { - "use strict"; - module2.exports = BufferReader; - var Reader = require_reader2(); - (BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader; - var util = require_minimal(); - function BufferReader(buffer) { - Reader.call(this, buffer); - } - BufferReader._configure = function() { - if (util.Buffer) - BufferReader.prototype._slice = util.Buffer.prototype.slice; - }; - BufferReader.prototype.string = function read_string_buffer() { - var len = this.uint32(); - return this.buf.utf8Slice ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len)) : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + len, this.len)); - }; - BufferReader._configure(); - } -}); - -// node_modules/protobufjs/src/rpc/service.js -var require_service2 = __commonJS({ - "node_modules/protobufjs/src/rpc/service.js"(exports2, module2) { - "use strict"; - module2.exports = Service; - var util = require_minimal(); - (Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service; - function Service(rpcImpl, requestDelimited, responseDelimited) { - if (typeof rpcImpl !== "function") - throw TypeError("rpcImpl must be a function"); - util.EventEmitter.call(this); - this.rpcImpl = rpcImpl; - this.requestDelimited = Boolean(requestDelimited); - this.responseDelimited = Boolean(responseDelimited); - } - Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request2, callback) { - if (!request2) - throw TypeError("request must be specified"); - var self2 = this; - if (!callback) - return util.asPromise(rpcCall, self2, method, requestCtor, responseCtor, request2); - if (!self2.rpcImpl) { - setTimeout(function() { - callback(Error("already ended")); - }, 0); - return void 0; - } - try { - return self2.rpcImpl( - method, - requestCtor[self2.requestDelimited ? "encodeDelimited" : "encode"](request2).finish(), - function rpcCallback(err, response) { - if (err) { - self2.emit("error", err, method); - return callback(err); - } - if (response === null) { - self2.end( - /* endedByRPC */ - true - ); - return void 0; - } - if (!(response instanceof responseCtor)) { - try { - response = responseCtor[self2.responseDelimited ? "decodeDelimited" : "decode"](response); - } catch (err2) { - self2.emit("error", err2, method); - return callback(err2); - } - } - self2.emit("data", response, method); - return callback(null, response); - } - ); - } catch (err) { - self2.emit("error", err, method); - setTimeout(function() { - callback(err); - }, 0); - return void 0; - } - }; - Service.prototype.end = function end(endedByRPC) { - if (this.rpcImpl) { - if (!endedByRPC) - this.rpcImpl(null, null, null); - this.rpcImpl = null; - this.emit("end").off(); - } - return this; - }; - } -}); - -// node_modules/protobufjs/src/rpc.js -var require_rpc = __commonJS({ - "node_modules/protobufjs/src/rpc.js"(exports2) { - "use strict"; - var rpc = exports2; - rpc.Service = require_service2(); - } -}); - -// node_modules/protobufjs/src/roots.js -var require_roots = __commonJS({ - "node_modules/protobufjs/src/roots.js"(exports2, module2) { - "use strict"; - module2.exports = {}; - } -}); - -// node_modules/protobufjs/src/index-minimal.js -var require_index_minimal = __commonJS({ - "node_modules/protobufjs/src/index-minimal.js"(exports2) { - "use strict"; - var protobuf = exports2; - protobuf.build = "minimal"; - protobuf.Writer = require_writer2(); - protobuf.BufferWriter = require_writer_buffer(); - protobuf.Reader = require_reader2(); - protobuf.BufferReader = require_reader_buffer(); - protobuf.util = require_minimal(); - protobuf.rpc = require_rpc(); - protobuf.roots = require_roots(); - protobuf.configure = configure; - function configure() { - protobuf.util._configure(); - protobuf.Writer._configure(protobuf.BufferWriter); - protobuf.Reader._configure(protobuf.BufferReader); - } - configure(); - } -}); - -// node_modules/@protobufjs/codegen/index.js -var require_codegen = __commonJS({ - "node_modules/@protobufjs/codegen/index.js"(exports2, module2) { - "use strict"; - module2.exports = codegen; - var reservedRe = /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/; - function codegen(functionParams, functionName) { - if (typeof functionParams === "string") { - functionName = functionParams; - functionParams = void 0; - } - var body = []; - function Codegen(formatStringOrScope) { - if (typeof formatStringOrScope !== "string") { - var source = toString(); - if (codegen.verbose) - console.log("codegen: " + source); - source = "return " + source; - if (formatStringOrScope) { - var scopeKeys = Object.keys(formatStringOrScope), scopeParams = new Array(scopeKeys.length + 1), scopeValues = new Array(scopeKeys.length), scopeOffset = 0; - while (scopeOffset < scopeKeys.length) { - scopeParams[scopeOffset] = scopeKeys[scopeOffset]; - scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]]; - } - scopeParams[scopeOffset] = source; - return Function.apply(null, scopeParams).apply(null, scopeValues); - } - return Function(source)(); - } - var formatParams = new Array(arguments.length - 1), formatOffset = 0; - while (formatOffset < formatParams.length) - formatParams[formatOffset] = arguments[++formatOffset]; - formatOffset = 0; - formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, function replace($0, $1) { - var value = formatParams[formatOffset++]; - switch ($1) { - case "d": - case "f": - return String(Number(value)); - case "i": - return String(Math.floor(value)); - case "j": - return JSON.stringify(value); - case "s": - return String(value); - } - return "%"; - }); - if (formatOffset !== formatParams.length) - throw Error("parameter count mismatch"); - body.push(formatStringOrScope); - return Codegen; - } - function toString(functionNameOverride) { - return "function " + safeFunctionName(functionNameOverride || functionName) + "(" + (functionParams && functionParams.join(",") || "") + "){\n " + body.join("\n ") + "\n}"; - } - Codegen.toString = toString; - return Codegen; - } - codegen.verbose = false; - function safeFunctionName(name) { - if (!name) - return ""; - name = String(name).replace(/[^\w$]/g, ""); - if (!name) - return ""; - if (/^\d/.test(name)) - name = "_" + name; - return reservedRe.test(name) ? name + "_" : name; - } - } -}); - -// node_modules/@protobufjs/fetch/index.js -var require_fetch2 = __commonJS({ - "node_modules/@protobufjs/fetch/index.js"(exports2, module2) { - "use strict"; - module2.exports = fetch3; - var asPromise = require_aspromise(); - var inquire = require_inquire(); - var fs3 = inquire("fs"); - function fetch3(filename, options, callback) { - if (typeof options === "function") { - callback = options; - options = {}; - } else if (!options) - options = {}; - if (!callback) - return asPromise(fetch3, this, filename, options); - if (!options.xhr && fs3 && fs3.readFile) - return fs3.readFile(filename, function fetchReadFileCallback(err, contents) { - return err && typeof XMLHttpRequest !== "undefined" ? fetch3.xhr(filename, options, callback) : err ? callback(err) : callback(null, options.binary ? contents : contents.toString("utf8")); - }); - return fetch3.xhr(filename, options, callback); - } - fetch3.xhr = function fetch_xhr(filename, options, callback) { - var xhr = new XMLHttpRequest(); - xhr.onreadystatechange = function fetchOnReadyStateChange() { - if (xhr.readyState !== 4) - return void 0; - if (xhr.status !== 0 && xhr.status !== 200) - return callback(Error("status " + xhr.status)); - if (options.binary) { - var buffer = xhr.response; - if (!buffer) { - buffer = []; - for (var i = 0; i < xhr.responseText.length; ++i) - buffer.push(xhr.responseText.charCodeAt(i) & 255); - } - return callback(null, typeof Uint8Array !== "undefined" ? new Uint8Array(buffer) : buffer); - } - return callback(null, xhr.responseText); - }; - if (options.binary) { - if ("overrideMimeType" in xhr) - xhr.overrideMimeType("text/plain; charset=x-user-defined"); - xhr.responseType = "arraybuffer"; - } - xhr.open("GET", filename); - xhr.send(); - }; - } -}); - -// node_modules/@protobufjs/path/index.js -var require_path = __commonJS({ - "node_modules/@protobufjs/path/index.js"(exports2) { - "use strict"; - var path = exports2; - var isAbsolute = ( - /** - * Tests if the specified path is absolute. - * @param {string} path Path to test - * @returns {boolean} `true` if path is absolute - */ - path.isAbsolute = function isAbsolute2(path2) { - return /^(?:\/|\w+:)/.test(path2); - } - ); - var normalize = ( - /** - * Normalizes the specified path. - * @param {string} path Path to normalize - * @returns {string} Normalized path - */ - path.normalize = function normalize2(path2) { - path2 = path2.replace(/\\/g, "/").replace(/\/{2,}/g, "/"); - var parts = path2.split("/"), absolute = isAbsolute(path2), prefix = ""; - if (absolute) - prefix = parts.shift() + "/"; - for (var i = 0; i < parts.length; ) { - if (parts[i] === "..") { - if (i > 0 && parts[i - 1] !== "..") - parts.splice(--i, 2); - else if (absolute) - parts.splice(i, 1); - else - ++i; - } else if (parts[i] === ".") - parts.splice(i, 1); - else - ++i; - } - return prefix + parts.join("/"); - } - ); - path.resolve = function resolve(originPath, includePath, alreadyNormalized) { - if (!alreadyNormalized) - includePath = normalize(includePath); - if (isAbsolute(includePath)) - return includePath; - if (!alreadyNormalized) - originPath = normalize(originPath); - return (originPath = originPath.replace(/(?:\/|^)[^/]+$/, "")).length ? normalize(originPath + "/" + includePath) : includePath; - }; - } -}); - -// node_modules/protobufjs/src/util/patterns.js -var require_patterns = __commonJS({ - "node_modules/protobufjs/src/util/patterns.js"(exports2) { - "use strict"; - var patterns = exports2; - patterns.numberRe = /^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/; - patterns.typeRefRe = /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/; - patterns.reservedRe = /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/; - patterns.unsafePropertyRe = /^(?:__proto__|prototype|constructor)$/; - } -}); - -// node_modules/protobufjs/src/namespace.js -var require_namespace = __commonJS({ - "node_modules/protobufjs/src/namespace.js"(exports2, module2) { - "use strict"; - module2.exports = Namespace; - var ReflectionObject = require_object(); - ((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = "Namespace"; - var Field = require_field(); - var util = require_util10(); - var OneOf = require_oneof(); - var Type; - var Service; - var Enum; - Namespace.fromJSON = function fromJSON(name, json) { - return new Namespace(name, json.options).addJSON(json.nested); - }; - function arrayToJSON(array, toJSONOptions) { - if (!(array && array.length)) - return void 0; - var obj = {}; - for (var i = 0; i < array.length; ++i) - obj[array[i].name] = array[i].toJSON(toJSONOptions); - return obj; - } - Namespace.arrayToJSON = arrayToJSON; - Namespace.isReservedId = function isReservedId(reserved, id) { - if (reserved) { - for (var i = 0; i < reserved.length; ++i) - if (typeof reserved[i] !== "string" && reserved[i][0] <= id && reserved[i][1] > id) - return true; - } - return false; - }; - Namespace.isReservedName = function isReservedName(reserved, name) { - if (reserved) { - for (var i = 0; i < reserved.length; ++i) - if (reserved[i] === name) - return true; - } - return false; - }; - function Namespace(name, options) { - ReflectionObject.call(this, name, options); - this.nested = void 0; - this._nestedArray = null; - this._lookupCache = /* @__PURE__ */ Object.create(null); - this._needsRecursiveFeatureResolution = true; - this._needsRecursiveResolve = true; - } - function clearCache(namespace) { - namespace._nestedArray = null; - namespace._lookupCache = /* @__PURE__ */ Object.create(null); - var parent = namespace; - while (parent = parent.parent) { - parent._lookupCache = /* @__PURE__ */ Object.create(null); - } - return namespace; - } - Object.defineProperty(Namespace.prototype, "nestedArray", { - get: function() { - return this._nestedArray || (this._nestedArray = util.toArray(this.nested)); - } - }); - Namespace.prototype.toJSON = function toJSON(toJSONOptions) { - return util.toObject([ - "options", - this.options, - "nested", - arrayToJSON(this.nestedArray, toJSONOptions) - ]); - }; - Namespace.prototype.addJSON = function addJSON(nestedJson) { - var ns = this; - if (nestedJson) { - for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) { - nested = nestedJson[names[i]]; - ns.add( - // most to least likely - (nested.fields !== void 0 ? Type.fromJSON : nested.values !== void 0 ? Enum.fromJSON : nested.methods !== void 0 ? Service.fromJSON : nested.id !== void 0 ? Field.fromJSON : Namespace.fromJSON)(names[i], nested) - ); - } - } - return this; - }; - Namespace.prototype.get = function get(name) { - return this.nested && Object.prototype.hasOwnProperty.call(this.nested, name) ? this.nested[name] : null; - }; - Namespace.prototype.getEnum = function getEnum(name) { - if (this.nested && Object.prototype.hasOwnProperty.call(this.nested, name) && this.nested[name] instanceof Enum) - return this.nested[name].values; - throw Error("no such enum: " + name); - }; - Namespace.prototype.add = function add(object) { - if (!(object instanceof Field && object.extend !== void 0 || object instanceof Type || object instanceof OneOf || object instanceof Enum || object instanceof Service || object instanceof Namespace)) - throw TypeError("object must be a valid nested object"); - if (object.name === "__proto__") - return this; - if (!this.nested) - this.nested = {}; - else { - var prev = this.get(object.name); - if (prev) { - if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) { - var nested = prev.nestedArray; - for (var i = 0; i < nested.length; ++i) - object.add(nested[i]); - this.remove(prev); - if (!this.nested) - this.nested = {}; - object.setOptions(prev.options, true); - } else - throw Error("duplicate name '" + object.name + "' in " + this); - } - } - this.nested[object.name] = object; - if (!(this instanceof Type || this instanceof Service || this instanceof Enum || this instanceof Field)) { - if (!object._edition) { - object._edition = object._defaultEdition; - } - } - this._needsRecursiveFeatureResolution = true; - this._needsRecursiveResolve = true; - var parent = this; - while (parent = parent.parent) { - parent._needsRecursiveFeatureResolution = true; - parent._needsRecursiveResolve = true; - } - object.onAdd(this); - return clearCache(this); - }; - Namespace.prototype.remove = function remove(object) { - if (!(object instanceof ReflectionObject)) - throw TypeError("object must be a ReflectionObject"); - if (object.parent !== this) - throw Error(object + " is not a member of " + this); - delete this.nested[object.name]; - if (!Object.keys(this.nested).length) - this.nested = void 0; - object.onRemove(this); - return clearCache(this); - }; - Namespace.prototype.define = function define2(path, json) { - if (util.isString(path)) - path = path.split("."); - else if (!Array.isArray(path)) - throw TypeError("illegal path"); - if (path && path.length && path[0] === "") - throw Error("path must be relative"); - var ptr = this; - while (path.length > 0) { - var part = path.shift(); - if (ptr.nested && ptr.nested[part]) { - ptr = ptr.nested[part]; - if (!(ptr instanceof Namespace)) - throw Error("path conflicts with non-namespace objects"); - } else - ptr.add(ptr = new Namespace(part)); - } - if (json) - ptr.addJSON(json); - return ptr; - }; - Namespace.prototype.resolveAll = function resolveAll() { - if (!this._needsRecursiveResolve) return this; - this._resolveFeaturesRecursive(this._edition); - var nested = this.nestedArray, i = 0; - this.resolve(); - while (i < nested.length) - if (nested[i] instanceof Namespace) - nested[i++].resolveAll(); - else - nested[i++].resolve(); - this._needsRecursiveResolve = false; - return this; - }; - Namespace.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) { - if (!this._needsRecursiveFeatureResolution) return this; - this._needsRecursiveFeatureResolution = false; - edition = this._edition || edition; - ReflectionObject.prototype._resolveFeaturesRecursive.call(this, edition); - this.nestedArray.forEach((nested) => { - nested._resolveFeaturesRecursive(edition); - }); - return this; - }; - Namespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChecked) { - if (typeof filterTypes === "boolean") { - parentAlreadyChecked = filterTypes; - filterTypes = void 0; - } else if (filterTypes && !Array.isArray(filterTypes)) - filterTypes = [filterTypes]; - if (util.isString(path) && path.length) { - if (path === ".") - return this.root; - path = path.split("."); - } else if (!path.length) - return this; - var flatPath = path.join("."); - if (path[0] === "") - return this.root.lookup(path.slice(1), filterTypes); - var found = this.root._fullyQualifiedObjects && this.root._fullyQualifiedObjects["." + flatPath]; - if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) { - return found; - } - found = this._lookupImpl(path, flatPath); - if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) { - return found; - } - if (parentAlreadyChecked) - return null; - var current = this; - while (current.parent) { - found = current.parent._lookupImpl(path, flatPath); - if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) { - return found; - } - current = current.parent; - } - return null; - }; - Namespace.prototype._lookupImpl = function lookup(path, flatPath) { - if (Object.prototype.hasOwnProperty.call(this._lookupCache, flatPath)) { - return this._lookupCache[flatPath]; - } - var found = this.get(path[0]); - var exact = null; - if (found) { - if (path.length === 1) { - exact = found; - } else if (found instanceof Namespace) { - path = path.slice(1); - exact = found._lookupImpl(path, path.join(".")); - } - } else { - for (var i = 0; i < this.nestedArray.length; ++i) - if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i]._lookupImpl(path, flatPath))) - exact = found; - } - this._lookupCache[flatPath] = exact; - return exact; - }; - Namespace.prototype.lookupType = function lookupType(path) { - var found = this.lookup(path, [Type]); - if (!found) - throw Error("no such type: " + path); - return found; - }; - Namespace.prototype.lookupEnum = function lookupEnum(path) { - var found = this.lookup(path, [Enum]); - if (!found) - throw Error("no such Enum '" + path + "' in " + this); - return found; - }; - Namespace.prototype.lookupTypeOrEnum = function lookupTypeOrEnum(path) { - var found = this.lookup(path, [Type, Enum]); - if (!found) - throw Error("no such Type or Enum '" + path + "' in " + this); - return found; - }; - Namespace.prototype.lookupService = function lookupService(path) { - var found = this.lookup(path, [Service]); - if (!found) - throw Error("no such Service '" + path + "' in " + this); - return found; - }; - Namespace._configure = function(Type_, Service_, Enum_) { - Type = Type_; - Service = Service_; - Enum = Enum_; - }; - } -}); - -// node_modules/protobufjs/src/mapfield.js -var require_mapfield = __commonJS({ - "node_modules/protobufjs/src/mapfield.js"(exports2, module2) { - "use strict"; - module2.exports = MapField; - var Field = require_field(); - ((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = "MapField"; - var types = require_types2(); - var util = require_util10(); - function MapField(name, id, keyType, type, options, comment) { - Field.call(this, name, id, type, void 0, void 0, options, comment); - if (!util.isString(keyType)) - throw TypeError("keyType must be a string"); - this.keyType = keyType; - this.resolvedKeyType = null; - this.map = true; - } - MapField.fromJSON = function fromJSON(name, json) { - return new MapField(name, json.id, json.keyType, json.type, json.options, json.comment); - }; - MapField.prototype.toJSON = function toJSON(toJSONOptions) { - var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; - return util.toObject([ - "keyType", - this.keyType, - "type", - this.type, - "id", - this.id, - "extend", - this.extend, - "options", - this.options, - "comment", - keepComments ? this.comment : void 0 - ]); - }; - MapField.prototype.resolve = function resolve() { - if (this.resolved) - return this; - if (types.mapKey[this.keyType] === void 0) - throw Error("invalid key type: " + this.keyType); - return Field.prototype.resolve.call(this); - }; - MapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) { - if (typeof fieldValueType === "function") - fieldValueType = util.decorateType(fieldValueType).name; - else if (fieldValueType && typeof fieldValueType === "object") - fieldValueType = util.decorateEnum(fieldValueType).name; - return function mapFieldDecorator(prototype, fieldName) { - util.decorateType(prototype.constructor).add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType)); - }; - }; - } -}); - -// node_modules/protobufjs/src/method.js -var require_method = __commonJS({ - "node_modules/protobufjs/src/method.js"(exports2, module2) { - "use strict"; - module2.exports = Method; - var ReflectionObject = require_object(); - ((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = "Method"; - var util = require_util10(); - function Method(name, type, requestType, responseType, requestStream, responseStream, options, comment, parsedOptions) { - if (util.isObject(requestStream)) { - options = requestStream; - requestStream = responseStream = void 0; - } else if (util.isObject(responseStream)) { - options = responseStream; - responseStream = void 0; - } - if (!(type === void 0 || util.isString(type))) - throw TypeError("type must be a string"); - if (!util.isString(requestType)) - throw TypeError("requestType must be a string"); - if (!util.isString(responseType)) - throw TypeError("responseType must be a string"); - ReflectionObject.call(this, name, options); - this.type = type || "rpc"; - this.requestType = requestType; - this.requestStream = requestStream ? true : void 0; - this.responseType = responseType; - this.responseStream = responseStream ? true : void 0; - this.resolvedRequestType = null; - this.resolvedResponseType = null; - this.comment = comment; - this.parsedOptions = parsedOptions; - } - Method.fromJSON = function fromJSON(name, json) { - return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options, json.comment, json.parsedOptions); - }; - Method.prototype.toJSON = function toJSON(toJSONOptions) { - var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; - return util.toObject([ - "type", - this.type !== "rpc" && /* istanbul ignore next */ - this.type || void 0, - "requestType", - this.requestType, - "requestStream", - this.requestStream, - "responseType", - this.responseType, - "responseStream", - this.responseStream, - "options", - this.options, - "comment", - keepComments ? this.comment : void 0, - "parsedOptions", - this.parsedOptions - ]); - }; - Method.prototype.resolve = function resolve() { - if (this.resolved) - return this; - this.resolvedRequestType = this.parent.lookupType(this.requestType); - this.resolvedResponseType = this.parent.lookupType(this.responseType); - return ReflectionObject.prototype.resolve.call(this); - }; - } -}); - -// node_modules/protobufjs/src/service.js -var require_service3 = __commonJS({ - "node_modules/protobufjs/src/service.js"(exports2, module2) { - "use strict"; - module2.exports = Service; - var Namespace = require_namespace(); - ((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = "Service"; - var Method = require_method(); - var util = require_util10(); - var rpc = require_rpc(); - var reservedRe = util.patterns.reservedRe; - function Service(name, options) { - Namespace.call(this, name, options); - this.methods = {}; - this._methodsArray = null; - } - Service.fromJSON = function fromJSON(name, json) { - var service = new Service(name, json.options); - if (json.methods) - for (var names = Object.keys(json.methods), i = 0; i < names.length; ++i) - service.add(Method.fromJSON(names[i], json.methods[names[i]])); - if (json.nested) - service.addJSON(json.nested); - if (json.edition) - service._edition = json.edition; - service.comment = json.comment; - service._defaultEdition = "proto3"; - return service; - }; - Service.prototype.toJSON = function toJSON(toJSONOptions) { - var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions); - var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; - return util.toObject([ - "edition", - this._editionToJSON(), - "options", - inherited && inherited.options || void 0, - "methods", - Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || /* istanbul ignore next */ - {}, - "nested", - inherited && inherited.nested || void 0, - "comment", - keepComments ? this.comment : void 0 - ]); - }; - Object.defineProperty(Service.prototype, "methodsArray", { - get: function() { - return this._methodsArray || (this._methodsArray = util.toArray(this.methods)); - } - }); - function clearCache(service) { - service._methodsArray = null; - return service; - } - Service.prototype.get = function get(name) { - return Object.prototype.hasOwnProperty.call(this.methods, name) ? this.methods[name] : Namespace.prototype.get.call(this, name); - }; - Service.prototype.resolveAll = function resolveAll() { - if (!this._needsRecursiveResolve) return this; - Namespace.prototype.resolve.call(this); - var methods = this.methodsArray; - for (var i = 0; i < methods.length; ++i) - methods[i].resolve(); - return this; - }; - Service.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) { - if (!this._needsRecursiveFeatureResolution) return this; - edition = this._edition || edition; - Namespace.prototype._resolveFeaturesRecursive.call(this, edition); - this.methodsArray.forEach((method) => { - method._resolveFeaturesRecursive(edition); - }); - return this; - }; - Service.prototype.add = function add(object) { - if (this.get(object.name)) - throw Error("duplicate name '" + object.name + "' in " + this); - if (object instanceof Method) { - if (object.name === "__proto__") - return this; - this.methods[object.name] = object; - object.parent = this; - return clearCache(this); - } - return Namespace.prototype.add.call(this, object); - }; - Service.prototype.remove = function remove(object) { - if (object instanceof Method) { - if (this.methods[object.name] !== object) - throw Error(object + " is not a member of " + this); - delete this.methods[object.name]; - object.parent = null; - return clearCache(this); - } - return Namespace.prototype.remove.call(this, object); - }; - Service.prototype.create = function create(rpcImpl, requestDelimited, responseDelimited) { - var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited); - for (var i = 0, method; i < /* initializes */ - this.methodsArray.length; ++i) { - var methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\w_]/g, ""); - rpcService[methodName] = util.codegen(["r", "c"], reservedRe.test(methodName) ? methodName + "_" : methodName)("return this.rpcCall(m,q,s,r,c)")({ - m: method, - q: method.resolvedRequestType.ctor, - s: method.resolvedResponseType.ctor - }); - } - return rpcService; - }; - } -}); - -// node_modules/protobufjs/src/message.js -var require_message = __commonJS({ - "node_modules/protobufjs/src/message.js"(exports2, module2) { - "use strict"; - module2.exports = Message; - var util = require_minimal(); - function Message(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (key === "__proto__") - continue; - this[key] = properties[key]; - } - } - Message.create = function create(properties) { - return this.$type.create(properties); - }; - Message.encode = function encode(message, writer) { - return this.$type.encode(message, writer); - }; - Message.encodeDelimited = function encodeDelimited(message, writer) { - return this.$type.encodeDelimited(message, writer); - }; - Message.decode = function decode(reader) { - return this.$type.decode(reader); - }; - Message.decodeDelimited = function decodeDelimited(reader) { - return this.$type.decodeDelimited(reader); - }; - Message.verify = function verify(message) { - return this.$type.verify(message); - }; - Message.fromObject = function fromObject(object) { - return this.$type.fromObject(object); - }; - Message.toObject = function toObject(message, options) { - return this.$type.toObject(message, options); - }; - Message.prototype.toJSON = function toJSON() { - return this.$type.toObject(this, util.toJSONOptions); - }; - } -}); - -// node_modules/protobufjs/src/decoder.js -var require_decoder = __commonJS({ - "node_modules/protobufjs/src/decoder.js"(exports2, module2) { - "use strict"; - module2.exports = decoder; - var Enum = require_enum(); - var types = require_types2(); - var util = require_util10(); - function missing(field) { - return "missing required '" + field.name + "'"; - } - function decoder(mtype) { - var gen = util.codegen(["r", "l", "e", "n"], mtype.name + "$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("if(n===undefined)n=0")("if(n>Reader.recursionLimit)")('throw Error("maximum nesting depth exceeded")')("var c=l===undefined?r.len:r.pos+l,m=new this.ctor" + (mtype.fieldsArray.filter(function(field2) { - return field2.map; - }).length ? ",k,value" : ""))("while(r.pos>>3){"); - var i = 0; - for (; i < /* initializes */ - mtype.fieldsArray.length; ++i) { - var field = mtype._fieldsArray[i].resolve(), type = field.resolvedType instanceof Enum ? "int32" : field.type, ref = "m" + util.safeProp(field.name); - gen("case %i: {", field.id); - if (field.map) { - gen("if(%s===util.emptyObject)", ref)("%s={}", ref)("var c2 = r.uint32()+r.pos"); - if (types.defaults[field.keyType] !== void 0) gen("k=%j", types.defaults[field.keyType]); - else gen("k=null"); - if (types.defaults[type] !== void 0) gen("value=%j", types.defaults[type]); - else gen("value=null"); - gen("while(r.pos>>3){")("case 1: k=r.%s(); break", field.keyType)("case 2:"); - if (types.basic[type] === void 0) gen("value=types[%i].decode(r,r.uint32(),undefined,n+1)", i); - else gen("value=r.%s()", type); - gen("break")("default:")("r.skipType(tag2&7,n)")("break")("}")("}"); - if (types.long[field.keyType] !== void 0) gen('%s[typeof k==="object"?util.longToHash(k):k]=value', ref); - else { - if (field.keyType === "string") gen('if(k==="__proto__")')("util.makeProp(%s,k)", ref); - gen("%s[k]=value", ref); - } - } else if (field.repeated) { - gen("if(!(%s&&%s.length))", ref, ref)("%s=[]", ref); - if (types.packed[type] !== void 0) gen("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.posutil.recursionLimit)")("return%j", "maximum nesting depth exceeded"); - var oneofs = mtype.oneofsArray, seenFirstField = {}; - if (oneofs.length) gen("var p={}"); - for (var i = 0; i < /* initializes */ - mtype.fieldsArray.length; ++i) { - var field = mtype._fieldsArray[i].resolve(), ref = "m" + util.safeProp(field.name); - if (field.optional) gen("if(%s!=null&&m.hasOwnProperty(%j)){", ref, field.name); - if (field.map) { - gen("if(!util.isObject(%s))", ref)("return%j", invalid(field, "object"))("var k=Object.keys(%s)", ref)("for(var i=0;i>>0", prop, prop); - break; - case "int32": - case "sint32": - case "sfixed32": - gen("m%s=d%s|0", prop, prop); - break; - case "uint64": - isUnsigned = true; - // eslint-disable-next-line no-fallthrough - case "int64": - case "sint64": - case "fixed64": - case "sfixed64": - gen("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j", prop, prop, isUnsigned)('else if(typeof d%s==="string")', prop)("m%s=parseInt(d%s,10)", prop, prop)('else if(typeof d%s==="number")', prop)("m%s=d%s", prop, prop)('else if(typeof d%s==="object")', prop)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)", prop, prop, prop, isUnsigned ? "true" : ""); - break; - case "bytes": - gen('if(typeof d%s==="string")', prop)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)", prop, prop, prop)("else if(d%s.length >= 0)", prop)("m%s=d%s", prop, prop); - break; - case "string": - gen("m%s=String(d%s)", prop, prop); - break; - case "bool": - gen("m%s=Boolean(d%s)", prop, prop); - break; - } - } - return gen; - } - converter.fromObject = function fromObject(mtype) { - var fields = mtype.fieldsArray; - var gen = util.codegen(["d", "n"], mtype.name + "$fromObject")("if(d instanceof this.ctor)")("return d")("if(n===undefined)n=0")("if(n>util.recursionLimit)")('throw Error("maximum nesting depth exceeded")'); - if (!fields.length) return gen("return new this.ctor"); - gen("var m=new this.ctor"); - for (var i = 0; i < fields.length; ++i) { - var field = fields[i].resolve(), prop = util.safeProp(field.name); - if (field.map) { - gen("if(d%s){", prop)('if(typeof d%s!=="object")', prop)("throw TypeError(%j)", field.fullName + ": object expected")("m%s={}", prop)("for(var ks=Object.keys(d%s),i=0;i>>0,m%s.high>>>0).toNumber(%s):m%s", prop, prop, prop, prop, isUnsigned ? "true" : "", prop); - break; - case "bytes": - gen("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s", prop, prop, prop, prop, prop); - break; - default: - gen("d%s=m%s", prop, prop); - break; - } - } - return gen; - } - converter.toObject = function toObject(mtype) { - var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById); - if (!fields.length) - return util.codegen()("return {}"); - var gen = util.codegen(["m", "o"], mtype.name + "$toObject")("if(!o)")("o={}")("var d={}"); - var repeatedFields = [], mapFields = [], normalFields = [], i = 0; - for (; i < fields.length; ++i) - if (!fields[i].partOf) - (fields[i].resolve().repeated ? repeatedFields : fields[i].map ? mapFields : normalFields).push(fields[i]); - if (repeatedFields.length) { - gen("if(o.arrays||o.defaults){"); - for (i = 0; i < repeatedFields.length; ++i) gen("d%s=[]", util.safeProp(repeatedFields[i].name)); - gen("}"); - } - if (mapFields.length) { - gen("if(o.objects||o.defaults){"); - for (i = 0; i < mapFields.length; ++i) gen("d%s={}", util.safeProp(mapFields[i].name)); - gen("}"); - } - if (normalFields.length) { - gen("if(o.defaults){"); - for (i = 0; i < normalFields.length; ++i) { - var field = normalFields[i], prop = util.safeProp(field.name); - if (field.resolvedType instanceof Enum) gen("d%s=o.enums===String?%j:%j", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault); - else if (field.long) gen("if(util.Long){")("var n=new util.Long(%i,%i,%j)", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned)("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n", prop)("}else")("d%s=o.longs===String?%j:%i", prop, field.typeDefault.toString(), field.typeDefault.toNumber()); - else if (field.bytes) { - var arrayDefault = Array.prototype.slice.call(field.typeDefault); - gen("if(o.bytes===String)d%s=%j", prop, String.fromCharCode.apply(String, field.typeDefault))("else{")("d%s=%j", prop, arrayDefault)("if(o.bytes!==Array)d%s=util.newBuffer(d%s)", prop, prop)("}"); - } else gen("d%s=%j", prop, field.typeDefault); - } - gen("}"); - } - var hasKs2 = false; - for (i = 0; i < fields.length; ++i) { - var field = fields[i], index = mtype._fieldsArray.indexOf(field), prop = util.safeProp(field.name); - if (field.map) { - if (!hasKs2) { - hasKs2 = true; - gen("var ks2"); - } - gen("if(m%s&&(ks2=Object.keys(m%s)).length){", prop, prop)("d%s={}", prop)("for(var j=0;j} - * @readonly - */ - fieldsById: { - get: function() { - if (this._fieldsById) - return this._fieldsById; - this._fieldsById = {}; - for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) { - var field = this.fields[names[i]], id = field.id; - if (this._fieldsById[id]) - throw Error("duplicate id " + id + " in " + this); - this._fieldsById[id] = field; - } - return this._fieldsById; - } - }, - /** - * Fields of this message as an array for iteration. - * @name Type#fieldsArray - * @type {Field[]} - * @readonly - */ - fieldsArray: { - get: function() { - return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields)); - } - }, - /** - * Oneofs of this message as an array for iteration. - * @name Type#oneofsArray - * @type {OneOf[]} - * @readonly - */ - oneofsArray: { - get: function() { - return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs)); - } - }, - /** - * The registered constructor, if any registered, otherwise a generic constructor. - * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor. - * @name Type#ctor - * @type {Constructor<{}>} - */ - ctor: { - get: function() { - return this._ctor || (this.ctor = Type.generateConstructor(this)()); - }, - set: function(ctor) { - var prototype = ctor.prototype; - if (!(prototype instanceof Message)) { - (ctor.prototype = new Message()).constructor = ctor; - util.merge(ctor.prototype, prototype); - } - ctor.$type = ctor.prototype.$type = this; - util.merge(ctor, Message, true); - this._ctor = ctor; - var i = 0; - for (; i < /* initializes */ - this.fieldsArray.length; ++i) - this._fieldsArray[i].resolve(); - var ctorProperties = {}; - for (i = 0; i < /* initializes */ - this.oneofsArray.length; ++i) - ctorProperties[this._oneofsArray[i].resolve().name] = { - get: util.oneOfGetter(this._oneofsArray[i].oneof), - set: util.oneOfSetter(this._oneofsArray[i].oneof) - }; - if (i) - Object.defineProperties(ctor.prototype, ctorProperties); - } - } - }); - Type.generateConstructor = function generateConstructor(mtype) { - var gen = util.codegen(["p"], mtype.name); - for (var i = 0, field; i < mtype.fieldsArray.length; ++i) - if ((field = mtype._fieldsArray[i]).map) gen("this%s={}", util.safeProp(field.name)); - else if (field.repeated) gen("this%s=[]", util.safeProp(field.name)); - return gen('if(p)for(var ks=Object.keys(p),i=0;i { - oneof._resolveFeatures(edition); - }); - this.fieldsArray.forEach((field) => { - field._resolveFeatures(edition); - }); - return this; - }; - Type.prototype.get = function get(name) { - if (Object.prototype.hasOwnProperty.call(this.fields, name)) - return this.fields[name]; - if (this.oneofs && Object.prototype.hasOwnProperty.call(this.oneofs, name)) - return this.oneofs[name]; - if (this.nested && Object.prototype.hasOwnProperty.call(this.nested, name)) - return this.nested[name]; - return null; - }; - Type.prototype.add = function add(object) { - if (this.get(object.name)) - throw Error("duplicate name '" + object.name + "' in " + this); - if (object instanceof Field && object.extend === void 0) { - if (this._fieldsById ? ( - /* istanbul ignore next */ - this._fieldsById[object.id] - ) : this.fieldsById[object.id]) - throw Error("duplicate id " + object.id + " in " + this); - if (this.isReservedId(object.id)) - throw Error("id " + object.id + " is reserved in " + this); - if (this.isReservedName(object.name)) - throw Error("name '" + object.name + "' is reserved in " + this); - if (object.name === "__proto__") - return this; - if (object.parent) - object.parent.remove(object); - this.fields[object.name] = object; - object.message = this; - object.onAdd(this); - return clearCache(this); - } - if (object instanceof OneOf) { - if (object.name === "__proto__") - return this; - if (!this.oneofs) - this.oneofs = {}; - this.oneofs[object.name] = object; - object.onAdd(this); - return clearCache(this); - } - return Namespace.prototype.add.call(this, object); - }; - Type.prototype.remove = function remove(object) { - if (object instanceof Field && object.extend === void 0) { - if (!this.fields || this.fields[object.name] !== object) - throw Error(object + " is not a member of " + this); - delete this.fields[object.name]; - object.parent = null; - object.onRemove(this); - return clearCache(this); - } - if (object instanceof OneOf) { - if (!this.oneofs || this.oneofs[object.name] !== object) - throw Error(object + " is not a member of " + this); - delete this.oneofs[object.name]; - object.parent = null; - object.onRemove(this); - return clearCache(this); - } - return Namespace.prototype.remove.call(this, object); - }; - Type.prototype.isReservedId = function isReservedId(id) { - return Namespace.isReservedId(this.reserved, id); - }; - Type.prototype.isReservedName = function isReservedName(name) { - return Namespace.isReservedName(this.reserved, name); - }; - Type.prototype.create = function create(properties) { - return new this.ctor(properties); - }; - Type.prototype.setup = function setup() { - var fullName = this.fullName, types = []; - for (var i = 0; i < /* initializes */ - this.fieldsArray.length; ++i) - types.push(this._fieldsArray[i].resolve().resolvedType); - this.encode = encoder(this)({ - Writer, - types, - util - }); - this.decode = decoder(this)({ - Reader, - types, - util - }); - this.verify = verifier(this)({ - types, - util - }); - this.fromObject = converter.fromObject(this)({ - types, - util - }); - this.toObject = converter.toObject(this)({ - types, - util - }); - var wrapper = wrappers[fullName]; - if (wrapper) { - var originalThis = Object.create(this); - originalThis.fromObject = this.fromObject; - this.fromObject = wrapper.fromObject.bind(originalThis); - originalThis.toObject = this.toObject; - this.toObject = wrapper.toObject.bind(originalThis); - } - return this; - }; - Type.prototype.encode = function encode_setup(message, writer) { - return this.setup().encode(message, writer); - }; - Type.prototype.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim(); - }; - Type.prototype.decode = function decode_setup(reader, length, end, depth) { - return this.setup().decode(reader, length, end, depth); - }; - Type.prototype.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof Reader)) - reader = Reader.create(reader); - return this.decode(reader, reader.uint32()); - }; - Type.prototype.verify = function verify_setup(message, depth) { - return this.setup().verify(message, depth); - }; - Type.prototype.fromObject = function fromObject(object, depth) { - return this.setup().fromObject(object, depth); - }; - Type.prototype.toObject = function toObject(message, options) { - return this.setup().toObject(message, options); - }; - Type.d = function decorateType(typeName) { - return function typeDecorator(target) { - util.decorateType(target, typeName); - }; - }; - } -}); - -// node_modules/protobufjs/src/root.js -var require_root = __commonJS({ - "node_modules/protobufjs/src/root.js"(exports2, module2) { - "use strict"; - module2.exports = Root; - var Namespace = require_namespace(); - ((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = "Root"; - var Field = require_field(); - var Enum = require_enum(); - var OneOf = require_oneof(); - var util = require_util10(); - var Type; - var parse3; - var common; - function Root(options) { - Namespace.call(this, "", options); - this.deferred = []; - this.files = []; - this._edition = "proto2"; - this._fullyQualifiedObjects = {}; - } - Root.fromJSON = function fromJSON(json, root) { - if (!root) - root = new Root(); - if (json.options) - root.setOptions(json.options); - return root.addJSON(json.nested).resolveAll(); - }; - Root.prototype.resolvePath = util.path.resolve; - Root.prototype.fetch = util.fetch; - function SYNC() { - } - Root.prototype.load = function load(filename, options, callback) { - if (typeof options === "function") { - callback = options; - options = void 0; - } - var self2 = this; - if (!callback) { - return util.asPromise(load, self2, filename, options); - } - var sync = callback === SYNC; - function finish(err, root) { - if (!callback) { - return; - } - if (sync) { - throw err; - } - if (root) { - root.resolveAll(); - } - var cb = callback; - callback = null; - cb(err, root); - } - function getBundledFileName(filename2) { - var idx = filename2.lastIndexOf("google/protobuf/"); - if (idx > -1) { - var altname = filename2.substring(idx); - if (altname in common) return altname; - } - return null; - } - function process2(filename2, source) { - try { - if (util.isString(source) && source.charAt(0) === "{") - source = JSON.parse(source); - if (!util.isString(source)) - self2.setOptions(source.options).addJSON(source.nested); - else { - parse3.filename = filename2; - var parsed = parse3(source, self2, options), resolved2, i2 = 0; - if (parsed.imports) { - for (; i2 < parsed.imports.length; ++i2) - if (resolved2 = getBundledFileName(parsed.imports[i2]) || self2.resolvePath(filename2, parsed.imports[i2])) - fetch3(resolved2); - } - if (parsed.weakImports) { - for (i2 = 0; i2 < parsed.weakImports.length; ++i2) - if (resolved2 = getBundledFileName(parsed.weakImports[i2]) || self2.resolvePath(filename2, parsed.weakImports[i2])) - fetch3(resolved2, true); - } - } - } catch (err) { - finish(err); - } - if (!sync && !queued) { - finish(null, self2); - } - } - function fetch3(filename2, weak) { - filename2 = getBundledFileName(filename2) || filename2; - if (self2.files.indexOf(filename2) > -1) { - return; - } - self2.files.push(filename2); - if (filename2 in common) { - if (sync) { - process2(filename2, common[filename2]); - } else { - ++queued; - setTimeout(function() { - --queued; - process2(filename2, common[filename2]); - }); - } - return; - } - if (sync) { - var source; - try { - source = util.fs.readFileSync(filename2).toString("utf8"); - } catch (err) { - if (!weak) - finish(err); - return; - } - process2(filename2, source); - } else { - ++queued; - self2.fetch(filename2, function(err, source2) { - --queued; - if (!callback) { - return; - } - if (err) { - if (!weak) - finish(err); - else if (!queued) - finish(null, self2); - return; - } - process2(filename2, source2); - }); - } - } - var queued = 0; - if (util.isString(filename)) { - filename = [filename]; - } - for (var i = 0, resolved; i < filename.length; ++i) - if (resolved = self2.resolvePath("", filename[i])) - fetch3(resolved); - if (sync) { - self2.resolveAll(); - return self2; - } - if (!queued) { - finish(null, self2); - } - return self2; - }; - Root.prototype.loadSync = function loadSync(filename, options) { - if (!util.isNode) - throw Error("not supported"); - return this.load(filename, options, SYNC); - }; - Root.prototype.resolveAll = function resolveAll() { - if (!this._needsRecursiveResolve) return this; - if (this.deferred.length) - throw Error("unresolvable extensions: " + this.deferred.map(function(field) { - return "'extend " + field.extend + "' in " + field.parent.fullName; - }).join(", ")); - return Namespace.prototype.resolveAll.call(this); - }; - var exposeRe = /^[A-Z]/; - function tryHandleExtension(root, field) { - var extendedType = field.parent.lookup(field.extend); - if (extendedType) { - var sisterField = new Field(field.fullName, field.id, field.type, field.rule, void 0, field.options); - if (extendedType.get(sisterField.name)) { - return true; - } - sisterField.declaringField = field; - field.extensionField = sisterField; - extendedType.add(sisterField); - return true; - } - return false; - } - Root.prototype._handleAdd = function _handleAdd(object) { - if (object instanceof Field) { - if ( - /* an extension field (implies not part of a oneof) */ - object.extend !== void 0 && /* not already handled */ - !object.extensionField - ) { - if (!tryHandleExtension(this, object)) - this.deferred.push(object); - } - } else if (object instanceof Enum) { - if (exposeRe.test(object.name)) - object.parent[object.name] = object.values; - } else if (!(object instanceof OneOf)) { - if (object instanceof Type) - for (var i = 0; i < this.deferred.length; ) - if (tryHandleExtension(this, this.deferred[i])) - this.deferred.splice(i, 1); - else - ++i; - for (var j = 0; j < /* initializes */ - object.nestedArray.length; ++j) - this._handleAdd(object._nestedArray[j]); - if (exposeRe.test(object.name)) - object.parent[object.name] = object; - } - if (object instanceof Type || object instanceof Enum || object instanceof Field) { - this._fullyQualifiedObjects[object.fullName] = object; - } - }; - Root.prototype._handleRemove = function _handleRemove(object) { - if (object instanceof Field) { - if ( - /* an extension field */ - object.extend !== void 0 - ) { - if ( - /* already handled */ - object.extensionField - ) { - object.extensionField.parent.remove(object.extensionField); - object.extensionField = null; - } else { - var index = this.deferred.indexOf(object); - if (index > -1) - this.deferred.splice(index, 1); - } - } - } else if (object instanceof Enum) { - if (exposeRe.test(object.name)) - delete object.parent[object.name]; - } else if (object instanceof Namespace) { - for (var i = 0; i < /* initializes */ - object.nestedArray.length; ++i) - this._handleRemove(object._nestedArray[i]); - if (exposeRe.test(object.name)) - delete object.parent[object.name]; - } - delete this._fullyQualifiedObjects[object.fullName]; - }; - Root._configure = function(Type_, parse_, common_) { - Type = Type_; - parse3 = parse_; - common = common_; - }; - } -}); - -// node_modules/protobufjs/src/util.js -var require_util10 = __commonJS({ - "node_modules/protobufjs/src/util.js"(exports2, module2) { - "use strict"; - var util = module2.exports = require_minimal(); - var roots = require_roots(); - var Type; - var Enum; - util.codegen = require_codegen(); - util.fetch = require_fetch2(); - util.path = require_path(); - util.patterns = require_patterns(); - var reservedRe = util.patterns.reservedRe; - var unsafePropertyRe = util.patterns.unsafePropertyRe; - util.fs = util.inquire("fs"); - util.toArray = function toArray(object) { - if (object) { - var keys = Object.keys(object), array = new Array(keys.length), index = 0; - while (index < keys.length) - array[index] = object[keys[index++]]; - return array; - } - return []; - }; - util.toObject = function toObject(array) { - var object = {}, index = 0; - while (index < array.length) { - var key = array[index++], val = array[index++]; - if (val !== void 0) - object[key] = val; - } - return object; - }; - util.isReserved = function isReserved(name) { - return reservedRe.test(name); - }; - util.safeProp = function safeProp(prop) { - if (!/^[$\w_]+$/.test(prop) || reservedRe.test(prop)) - return "[" + JSON.stringify(prop) + "]"; - return "." + prop; - }; - util.ucFirst = function ucFirst(str) { - return str.charAt(0).toUpperCase() + str.substring(1); - }; - var camelCaseRe = /_([a-z])/g; - util.camelCase = function camelCase(str) { - return str.substring(0, 1) + str.substring(1).replace(camelCaseRe, function($0, $1) { - return $1.toUpperCase(); - }); - }; - util.compareFieldsById = function compareFieldsById(a, b) { - return a.id - b.id; - }; - util.decorateType = function decorateType(ctor, typeName) { - if (ctor.$type) { - if (typeName && ctor.$type.name !== typeName) { - util.decorateRoot.remove(ctor.$type); - ctor.$type.name = typeName; - util.decorateRoot.add(ctor.$type); - } - return ctor.$type; - } - if (!Type) - Type = require_type(); - var type = new Type(typeName || ctor.name); - util.decorateRoot.add(type); - type.ctor = ctor; - Object.defineProperty(ctor, "$type", { value: type, enumerable: false }); - Object.defineProperty(ctor.prototype, "$type", { value: type, enumerable: false }); - return type; - }; - var decorateEnumIndex = 0; - util.decorateEnum = function decorateEnum(object) { - if (object.$type) - return object.$type; - if (!Enum) - Enum = require_enum(); - var enm = new Enum("Enum" + decorateEnumIndex++, object); - util.decorateRoot.add(enm); - Object.defineProperty(object, "$type", { value: enm, enumerable: false }); - return enm; - }; - util.setProperty = function setProperty(dst, path, value, ifNotSet) { - function setProp(dst2, path2, value2) { - var part = path2.shift(); - if (unsafePropertyRe.test(part)) - return dst2; - if (path2.length > 0) { - dst2[part] = setProp(dst2[part] || {}, path2, value2); - } else { - var prevValue = dst2[part]; - if (prevValue && ifNotSet) - return dst2; - if (prevValue) - value2 = [].concat(prevValue).concat(value2); - dst2[part] = value2; - } - return dst2; - } - if (typeof dst !== "object") - throw TypeError("dst must be an object"); - if (!path) - throw TypeError("path must be specified"); - path = path.split("."); - return setProp(dst, path, value); - }; - Object.defineProperty(util, "decorateRoot", { - get: function() { - return roots["decorated"] || (roots["decorated"] = new (require_root())()); - } - }); - } -}); - -// node_modules/protobufjs/src/types.js -var require_types2 = __commonJS({ - "node_modules/protobufjs/src/types.js"(exports2) { - "use strict"; - var types = exports2; - var util = require_util10(); - var s = [ - "double", - // 0 - "float", - // 1 - "int32", - // 2 - "uint32", - // 3 - "sint32", - // 4 - "fixed32", - // 5 - "sfixed32", - // 6 - "int64", - // 7 - "uint64", - // 8 - "sint64", - // 9 - "fixed64", - // 10 - "sfixed64", - // 11 - "bool", - // 12 - "string", - // 13 - "bytes" - // 14 - ]; - function bake(values, offset) { - var i = 0, o = /* @__PURE__ */ Object.create(null); - offset |= 0; - while (i < values.length) o[s[i + offset]] = values[i++]; - return o; - } - types.basic = bake([ - /* double */ - 1, - /* float */ - 5, - /* int32 */ - 0, - /* uint32 */ - 0, - /* sint32 */ - 0, - /* fixed32 */ - 5, - /* sfixed32 */ - 5, - /* int64 */ - 0, - /* uint64 */ - 0, - /* sint64 */ - 0, - /* fixed64 */ - 1, - /* sfixed64 */ - 1, - /* bool */ - 0, - /* string */ - 2, - /* bytes */ - 2 - ]); - types.defaults = bake([ - /* double */ - 0, - /* float */ - 0, - /* int32 */ - 0, - /* uint32 */ - 0, - /* sint32 */ - 0, - /* fixed32 */ - 0, - /* sfixed32 */ - 0, - /* int64 */ - 0, - /* uint64 */ - 0, - /* sint64 */ - 0, - /* fixed64 */ - 0, - /* sfixed64 */ - 0, - /* bool */ - false, - /* string */ - "", - /* bytes */ - util.emptyArray, - /* message */ - null - ]); - types.long = bake([ - /* int64 */ - 0, - /* uint64 */ - 0, - /* sint64 */ - 0, - /* fixed64 */ - 1, - /* sfixed64 */ - 1 - ], 7); - types.mapKey = bake([ - /* int32 */ - 0, - /* uint32 */ - 0, - /* sint32 */ - 0, - /* fixed32 */ - 5, - /* sfixed32 */ - 5, - /* int64 */ - 0, - /* uint64 */ - 0, - /* sint64 */ - 0, - /* fixed64 */ - 1, - /* sfixed64 */ - 1, - /* bool */ - 0, - /* string */ - 2 - ], 2); - types.packed = bake([ - /* double */ - 1, - /* float */ - 5, - /* int32 */ - 0, - /* uint32 */ - 0, - /* sint32 */ - 0, - /* fixed32 */ - 5, - /* sfixed32 */ - 5, - /* int64 */ - 0, - /* uint64 */ - 0, - /* sint64 */ - 0, - /* fixed64 */ - 1, - /* sfixed64 */ - 1, - /* bool */ - 0 - ]); - } -}); - -// node_modules/protobufjs/src/field.js -var require_field = __commonJS({ - "node_modules/protobufjs/src/field.js"(exports2, module2) { - "use strict"; - module2.exports = Field; - var ReflectionObject = require_object(); - ((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = "Field"; - var Enum = require_enum(); - var types = require_types2(); - var util = require_util10(); - var Type; - var ruleRe = /^required|optional|repeated$/; - Field.fromJSON = function fromJSON(name, json) { - var field = new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment); - if (json.edition) - field._edition = json.edition; - field._defaultEdition = "proto3"; - return field; - }; - function Field(name, id, type, rule, extend, options, comment) { - if (util.isObject(rule)) { - comment = extend; - options = rule; - rule = extend = void 0; - } else if (util.isObject(extend)) { - comment = options; - options = extend; - extend = void 0; - } - ReflectionObject.call(this, name, options); - if (!util.isInteger(id) || id < 0) - throw TypeError("id must be a non-negative integer"); - if (!util.isString(type)) - throw TypeError("type must be a string"); - if (rule !== void 0 && !ruleRe.test(rule = rule.toString().toLowerCase())) - throw TypeError("rule must be a string rule"); - if (extend !== void 0 && !util.isString(extend)) - throw TypeError("extend must be a string"); - if (rule === "proto3_optional") { - rule = "optional"; - } - this.rule = rule && rule !== "optional" ? rule : void 0; - this.type = type; - this.id = id; - this.extend = extend || void 0; - this.repeated = rule === "repeated"; - this.map = false; - this.message = null; - this.partOf = null; - this.typeDefault = null; - this.defaultValue = null; - this.long = util.Long ? types.long[type] !== void 0 : ( - /* istanbul ignore next */ - false - ); - this.bytes = type === "bytes"; - this.resolvedType = null; - this.extensionField = null; - this.declaringField = null; - this.comment = comment; - } - Object.defineProperty(Field.prototype, "required", { - get: function() { - return this._features.field_presence === "LEGACY_REQUIRED"; - } - }); - Object.defineProperty(Field.prototype, "optional", { - get: function() { - return !this.required; - } - }); - Object.defineProperty(Field.prototype, "delimited", { - get: function() { - return this.resolvedType instanceof Type && this._features.message_encoding === "DELIMITED"; - } - }); - Object.defineProperty(Field.prototype, "packed", { - get: function() { - return this._features.repeated_field_encoding === "PACKED"; - } - }); - Object.defineProperty(Field.prototype, "hasPresence", { - get: function() { - if (this.repeated || this.map) { - return false; - } - return this.partOf || // oneofs - this.declaringField || this.extensionField || // extensions - this._features.field_presence !== "IMPLICIT"; - } - }); - Field.prototype.setOption = function setOption(name, value, ifNotSet) { - return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet); - }; - Field.prototype.toJSON = function toJSON(toJSONOptions) { - var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; - return util.toObject([ - "edition", - this._editionToJSON(), - "rule", - this.rule !== "optional" && this.rule || void 0, - "type", - this.type, - "id", - this.id, - "extend", - this.extend, - "options", - this.options, - "comment", - keepComments ? this.comment : void 0 - ]); - }; - Field.prototype.resolve = function resolve() { - if (this.resolved) - return this; - if ((this.typeDefault = types.defaults[this.type]) === void 0) { - this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type); - if (this.resolvedType instanceof Type) - this.typeDefault = null; - else - this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; - } else if (this.options && this.options.proto3_optional) { - this.typeDefault = null; - } - if (this.options && this.options["default"] != null) { - this.typeDefault = this.options["default"]; - if (this.resolvedType instanceof Enum && typeof this.typeDefault === "string") - this.typeDefault = this.resolvedType.values[this.typeDefault]; - } - if (this.options) { - if (this.options.packed !== void 0 && this.resolvedType && !(this.resolvedType instanceof Enum)) - delete this.options.packed; - if (!Object.keys(this.options).length) - this.options = void 0; - } - if (this.long) { - this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type.charAt(0) === "u"); - if (Object.freeze) - Object.freeze(this.typeDefault); - } else if (this.bytes && typeof this.typeDefault === "string") { - var buf; - if (util.base64.test(this.typeDefault)) - util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0); - else - util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0); - this.typeDefault = buf; - } - if (this.map) - this.defaultValue = util.emptyObject; - else if (this.repeated) - this.defaultValue = util.emptyArray; - else - this.defaultValue = this.typeDefault; - if (this.parent instanceof Type) - this.parent.ctor.prototype[this.name] = this.defaultValue; - return ReflectionObject.prototype.resolve.call(this); - }; - Field.prototype._inferLegacyProtoFeatures = function _inferLegacyProtoFeatures(edition) { - if (edition !== "proto2" && edition !== "proto3") { - return {}; - } - var features = {}; - if (this.rule === "required") { - features.field_presence = "LEGACY_REQUIRED"; - } - if (this.parent && types.defaults[this.type] === void 0) { - var type = this.parent.get(this.type.split(".").pop()); - if (type && type instanceof Type && type.group) { - features.message_encoding = "DELIMITED"; - } - } - if (this.getOption("packed") === true) { - features.repeated_field_encoding = "PACKED"; - } else if (this.getOption("packed") === false) { - features.repeated_field_encoding = "EXPANDED"; - } - return features; - }; - Field.prototype._resolveFeatures = function _resolveFeatures(edition) { - return ReflectionObject.prototype._resolveFeatures.call(this, this._edition || edition); - }; - Field.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) { - if (typeof fieldType === "function") - fieldType = util.decorateType(fieldType).name; - else if (fieldType && typeof fieldType === "object") - fieldType = util.decorateEnum(fieldType).name; - return function fieldDecorator(prototype, fieldName) { - util.decorateType(prototype.constructor).add(new Field(fieldName, fieldId, fieldType, fieldRule, { "default": defaultValue })); - }; - }; - Field._configure = function configure(Type_) { - Type = Type_; - }; - } -}); - -// node_modules/protobufjs/src/oneof.js -var require_oneof = __commonJS({ - "node_modules/protobufjs/src/oneof.js"(exports2, module2) { - "use strict"; - module2.exports = OneOf; - var ReflectionObject = require_object(); - ((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = "OneOf"; - var Field = require_field(); - var util = require_util10(); - function OneOf(name, fieldNames, options, comment) { - if (!Array.isArray(fieldNames)) { - options = fieldNames; - fieldNames = void 0; - } - ReflectionObject.call(this, name, options); - if (!(fieldNames === void 0 || Array.isArray(fieldNames))) - throw TypeError("fieldNames must be an Array"); - this.oneof = fieldNames || []; - this.fieldsArray = []; - this.comment = comment; - } - OneOf.fromJSON = function fromJSON(name, json) { - return new OneOf(name, json.oneof, json.options, json.comment); - }; - OneOf.prototype.toJSON = function toJSON(toJSONOptions) { - var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; - return util.toObject([ - "options", - this.options, - "oneof", - this.oneof, - "comment", - keepComments ? this.comment : void 0 - ]); - }; - function addFieldsToParent(oneof) { - if (oneof.parent) { - for (var i = 0; i < oneof.fieldsArray.length; ++i) - if (!oneof.fieldsArray[i].parent) - oneof.parent.add(oneof.fieldsArray[i]); - } - } - OneOf.prototype.add = function add(field) { - if (!(field instanceof Field)) - throw TypeError("field must be a Field"); - if (field.parent && field.parent !== this.parent) - field.parent.remove(field); - this.oneof.push(field.name); - this.fieldsArray.push(field); - field.partOf = this; - addFieldsToParent(this); - return this; - }; - OneOf.prototype.remove = function remove(field) { - if (!(field instanceof Field)) - throw TypeError("field must be a Field"); - var index = this.fieldsArray.indexOf(field); - if (index < 0) - throw Error(field + " is not a member of " + this); - this.fieldsArray.splice(index, 1); - index = this.oneof.indexOf(field.name); - if (index > -1) - this.oneof.splice(index, 1); - field.partOf = null; - return this; - }; - OneOf.prototype.onAdd = function onAdd(parent) { - ReflectionObject.prototype.onAdd.call(this, parent); - var self2 = this; - for (var i = 0; i < this.oneof.length; ++i) { - var field = parent.get(this.oneof[i]); - if (field && !field.partOf) { - field.partOf = self2; - self2.fieldsArray.push(field); - } - } - addFieldsToParent(this); - }; - OneOf.prototype.onRemove = function onRemove(parent) { - for (var i = 0, field; i < this.fieldsArray.length; ++i) - if ((field = this.fieldsArray[i]).parent) - field.parent.remove(field); - ReflectionObject.prototype.onRemove.call(this, parent); - }; - Object.defineProperty(OneOf.prototype, "isProto3Optional", { - get: function() { - if (this.fieldsArray == null || this.fieldsArray.length !== 1) { - return false; - } - var field = this.fieldsArray[0]; - return field.options != null && field.options["proto3_optional"] === true; - } - }); - OneOf.d = function decorateOneOf() { - var fieldNames = new Array(arguments.length), index = 0; - while (index < arguments.length) - fieldNames[index] = arguments[index++]; - return function oneOfDecorator(prototype, oneofName) { - util.decorateType(prototype.constructor).add(new OneOf(oneofName, fieldNames)); - Object.defineProperty(prototype, oneofName, { - get: util.oneOfGetter(fieldNames), - set: util.oneOfSetter(fieldNames) - }); - }; - }; - } -}); - -// node_modules/protobufjs/src/object.js -var require_object = __commonJS({ - "node_modules/protobufjs/src/object.js"(exports2, module2) { - "use strict"; - module2.exports = ReflectionObject; - ReflectionObject.className = "ReflectionObject"; - var OneOf = require_oneof(); - var util = require_util10(); - var Root; - var editions2023Defaults = { enum_type: "OPEN", field_presence: "EXPLICIT", json_format: "ALLOW", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "PACKED", utf8_validation: "VERIFY" }; - var proto2Defaults = { enum_type: "CLOSED", field_presence: "EXPLICIT", json_format: "LEGACY_BEST_EFFORT", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "EXPANDED", utf8_validation: "NONE" }; - var proto3Defaults = { enum_type: "OPEN", field_presence: "IMPLICIT", json_format: "ALLOW", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "PACKED", utf8_validation: "VERIFY" }; - function ReflectionObject(name, options) { - if (!util.isString(name)) - throw TypeError("name must be a string"); - if (options && !util.isObject(options)) - throw TypeError("options must be an object"); - this.options = options; - this.parsedOptions = null; - this.name = name; - this._edition = null; - this._defaultEdition = "proto2"; - this._features = {}; - this._featuresResolved = false; - this.parent = null; - this.resolved = false; - this.comment = null; - this.filename = null; - } - Object.defineProperties(ReflectionObject.prototype, { - /** - * Reference to the root namespace. - * @name ReflectionObject#root - * @type {Root} - * @readonly - */ - root: { - get: function() { - var ptr = this; - while (ptr.parent !== null) - ptr = ptr.parent; - return ptr; - } - }, - /** - * Full name including leading dot. - * @name ReflectionObject#fullName - * @type {string} - * @readonly - */ - fullName: { - get: function() { - var path = [this.name], ptr = this.parent; - while (ptr) { - path.unshift(ptr.name); - ptr = ptr.parent; - } - return path.join("."); - } - } - }); - ReflectionObject.prototype.toJSON = /* istanbul ignore next */ - function toJSON() { - throw Error(); - }; - ReflectionObject.prototype.onAdd = function onAdd(parent) { - if (this.parent && this.parent !== parent) - this.parent.remove(this); - this.parent = parent; - this.resolved = false; - var root = parent.root; - if (root instanceof Root) - root._handleAdd(this); - }; - ReflectionObject.prototype.onRemove = function onRemove(parent) { - var root = parent.root; - if (root instanceof Root) - root._handleRemove(this); - this.parent = null; - this.resolved = false; - }; - ReflectionObject.prototype.resolve = function resolve() { - if (this.resolved) - return this; - if (this.root instanceof Root) - this.resolved = true; - return this; - }; - ReflectionObject.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) { - return this._resolveFeatures(this._edition || edition); - }; - ReflectionObject.prototype._resolveFeatures = function _resolveFeatures(edition) { - if (this._featuresResolved) { - return; - } - var defaults2 = {}; - if (!edition) { - throw new Error("Unknown edition for " + this.fullName); - } - var protoFeatures = Object.assign( - this.options ? Object.assign({}, this.options.features) : {}, - this._inferLegacyProtoFeatures(edition) - ); - if (this._edition) { - if (edition === "proto2") { - defaults2 = Object.assign({}, proto2Defaults); - } else if (edition === "proto3") { - defaults2 = Object.assign({}, proto3Defaults); - } else if (edition === "2023") { - defaults2 = Object.assign({}, editions2023Defaults); - } else { - throw new Error("Unknown edition: " + edition); - } - this._features = Object.assign(defaults2, protoFeatures || {}); - this._featuresResolved = true; - return; - } - if (this.partOf instanceof OneOf) { - var lexicalParentFeaturesCopy = Object.assign({}, this.partOf._features); - this._features = Object.assign(lexicalParentFeaturesCopy, protoFeatures || {}); - } else if (this.declaringField) { - } else if (this.parent) { - var parentFeaturesCopy = Object.assign({}, this.parent._features); - this._features = Object.assign(parentFeaturesCopy, protoFeatures || {}); - } else { - throw new Error("Unable to find a parent for " + this.fullName); - } - if (this.extensionField) { - this.extensionField._features = this._features; - } - this._featuresResolved = true; - }; - ReflectionObject.prototype._inferLegacyProtoFeatures = function _inferLegacyProtoFeatures() { - return {}; - }; - ReflectionObject.prototype.getOption = function getOption(name) { - if (this.options) - return this.options[name]; - return void 0; - }; - ReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) { - if (name === "__proto__") - return this; - if (!this.options) - this.options = {}; - if (/^features\./.test(name)) { - util.setProperty(this.options, name, value, ifNotSet); - } else if (!ifNotSet || this.options[name] === void 0) { - if (this.getOption(name) !== value) this.resolved = false; - this.options[name] = value; - } - return this; - }; - ReflectionObject.prototype.setParsedOption = function setParsedOption(name, value, propName) { - if (name === "__proto__") - return this; - if (!this.parsedOptions) { - this.parsedOptions = []; - } - var parsedOptions = this.parsedOptions; - if (propName) { - var opt = parsedOptions.find(function(opt2) { - return Object.prototype.hasOwnProperty.call(opt2, name); - }); - if (opt) { - var newValue = opt[name]; - util.setProperty(newValue, propName, value); - } else { - opt = {}; - opt[name] = util.setProperty({}, propName, value); - parsedOptions.push(opt); - } - } else { - var newOpt = {}; - newOpt[name] = value; - parsedOptions.push(newOpt); - } - return this; - }; - ReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) { - if (options) - for (var keys = Object.keys(options), i = 0; i < keys.length; ++i) - this.setOption(keys[i], options[keys[i]], ifNotSet); - return this; - }; - ReflectionObject.prototype.toString = function toString() { - var className = this.constructor.className, fullName = this.fullName; - if (fullName.length) - return className + " " + fullName; - return className; - }; - ReflectionObject.prototype._editionToJSON = function _editionToJSON() { - if (!this._edition || this._edition === "proto3") { - return void 0; - } - return this._edition; - }; - ReflectionObject._configure = function(Root_) { - Root = Root_; - }; - } -}); - -// node_modules/protobufjs/src/enum.js -var require_enum = __commonJS({ - "node_modules/protobufjs/src/enum.js"(exports2, module2) { - "use strict"; - module2.exports = Enum; - var ReflectionObject = require_object(); - ((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = "Enum"; - var Namespace = require_namespace(); - var util = require_util10(); - function Enum(name, values, options, comment, comments, valuesOptions) { - ReflectionObject.call(this, name, options); - if (values && typeof values !== "object") - throw TypeError("values must be an object"); - this.valuesById = {}; - this.values = Object.create(this.valuesById); - this.comment = comment; - this.comments = comments || {}; - this.valuesOptions = valuesOptions; - this._valuesFeatures = {}; - this.reserved = void 0; - if (values) { - for (var keys = Object.keys(values), i = 0; i < keys.length; ++i) - if (keys[i] !== "__proto__" && typeof values[keys[i]] === "number") - this.valuesById[this.values[keys[i]] = values[keys[i]]] = keys[i]; - } - } - Enum.prototype._resolveFeatures = function _resolveFeatures(edition) { - edition = this._edition || edition; - ReflectionObject.prototype._resolveFeatures.call(this, edition); - Object.keys(this.values).forEach((key) => { - var parentFeaturesCopy = Object.assign({}, this._features); - this._valuesFeatures[key] = Object.assign(parentFeaturesCopy, this.valuesOptions && this.valuesOptions[key] && this.valuesOptions[key].features); - }); - return this; - }; - Enum.fromJSON = function fromJSON(name, json) { - var enm = new Enum(name, json.values, json.options, json.comment, json.comments); - enm.reserved = json.reserved; - if (json.edition) - enm._edition = json.edition; - enm._defaultEdition = "proto3"; - return enm; - }; - Enum.prototype.toJSON = function toJSON(toJSONOptions) { - var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; - return util.toObject([ - "edition", - this._editionToJSON(), - "options", - this.options, - "valuesOptions", - this.valuesOptions, - "values", - this.values, - "reserved", - this.reserved && this.reserved.length ? this.reserved : void 0, - "comment", - keepComments ? this.comment : void 0, - "comments", - keepComments ? this.comments : void 0 - ]); - }; - Enum.prototype.add = function add(name, id, comment, options) { - if (!util.isString(name)) - throw TypeError("name must be a string"); - if (!util.isInteger(id)) - throw TypeError("id must be an integer"); - if (name === "__proto__") - return this; - if (this.values[name] !== void 0) - throw Error("duplicate name '" + name + "' in " + this); - if (this.isReservedId(id)) - throw Error("id " + id + " is reserved in " + this); - if (this.isReservedName(name)) - throw Error("name '" + name + "' is reserved in " + this); - if (this.valuesById[id] !== void 0) { - if (!(this.options && this.options.allow_alias)) - throw Error("duplicate id " + id + " in " + this); - this.values[name] = id; - } else - this.valuesById[this.values[name] = id] = name; - if (options) { - if (this.valuesOptions === void 0) - this.valuesOptions = {}; - this.valuesOptions[name] = options || null; - } - this.comments[name] = comment || null; - return this; - }; - Enum.prototype.remove = function remove(name) { - if (!util.isString(name)) - throw TypeError("name must be a string"); - var val = this.values[name]; - if (val == null) - throw Error("name '" + name + "' does not exist in " + this); - delete this.valuesById[val]; - delete this.values[name]; - delete this.comments[name]; - if (this.valuesOptions) - delete this.valuesOptions[name]; - return this; - }; - Enum.prototype.isReservedId = function isReservedId(id) { - return Namespace.isReservedId(this.reserved, id); - }; - Enum.prototype.isReservedName = function isReservedName(name) { - return Namespace.isReservedName(this.reserved, name); - }; - } -}); - -// node_modules/protobufjs/src/encoder.js -var require_encoder = __commonJS({ - "node_modules/protobufjs/src/encoder.js"(exports2, module2) { - "use strict"; - module2.exports = encoder; - var Enum = require_enum(); - var types = require_types2(); - var util = require_util10(); - function genTypePartial(gen, field, fieldIndex, ref) { - return field.delimited ? gen("types[%i].encode(%s,w.uint32(%i)).uint32(%i)", fieldIndex, ref, (field.id << 3 | 3) >>> 0, (field.id << 3 | 4) >>> 0) : gen("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()", fieldIndex, ref, (field.id << 3 | 2) >>> 0); - } - function encoder(mtype) { - var gen = util.codegen(["m", "w"], mtype.name + "$encode")("if(!w)")("w=Writer.create()"); - var i, ref; - var fields = ( - /* initializes */ - mtype.fieldsArray.slice().sort(util.compareFieldsById) - ); - for (var i = 0; i < fields.length; ++i) { - var field = fields[i].resolve(), index = mtype._fieldsArray.indexOf(field), type = field.resolvedType instanceof Enum ? "int32" : field.type, wireType = types.basic[type]; - ref = "m" + util.safeProp(field.name); - if (field.map) { - gen("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){", ref, field.name)("for(var ks=Object.keys(%s),i=0;i>> 0, 8 | types.mapKey[field.keyType], field.keyType); - if (wireType === void 0) gen("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()", index, ref); - else gen(".uint32(%i).%s(%s[ks[i]]).ldelim()", 16 | wireType, type, ref); - gen("}")("}"); - } else if (field.repeated) { - gen("if(%s!=null&&%s.length){", ref, ref); - if (field.packed && types.packed[type] !== void 0) { - gen("w.uint32(%i).fork()", (field.id << 3 | 2) >>> 0)("for(var i=0;i<%s.length;++i)", ref)("w.%s(%s[i])", type, ref)("w.ldelim()"); - } else { - gen("for(var i=0;i<%s.length;++i)", ref); - if (wireType === void 0) - genTypePartial(gen, field, index, ref + "[i]"); - else gen("w.uint32(%i).%s(%s[i])", (field.id << 3 | wireType) >>> 0, type, ref); - } - gen("}"); - } else { - if (field.optional) gen("if(%s!=null&&Object.hasOwnProperty.call(m,%j))", ref, field.name); - if (wireType === void 0) - genTypePartial(gen, field, index, ref); - else gen("w.uint32(%i).%s(%s)", (field.id << 3 | wireType) >>> 0, type, ref); - } - } - return gen("return w"); - } - } -}); - -// node_modules/protobufjs/src/index-light.js -var require_index_light = __commonJS({ - "node_modules/protobufjs/src/index-light.js"(exports2, module2) { - "use strict"; - var protobuf = module2.exports = require_index_minimal(); - protobuf.build = "light"; - function load(filename, root, callback) { - if (typeof root === "function") { - callback = root; - root = new protobuf.Root(); - } else if (!root) - root = new protobuf.Root(); - return root.load(filename, callback); - } - protobuf.load = load; - function loadSync(filename, root) { - if (!root) - root = new protobuf.Root(); - return root.loadSync(filename); - } - protobuf.loadSync = loadSync; - protobuf.encoder = require_encoder(); - protobuf.decoder = require_decoder(); - protobuf.verifier = require_verifier(); - protobuf.converter = require_converter(); - protobuf.ReflectionObject = require_object(); - protobuf.Namespace = require_namespace(); - protobuf.Root = require_root(); - protobuf.Enum = require_enum(); - protobuf.Type = require_type(); - protobuf.Field = require_field(); - protobuf.OneOf = require_oneof(); - protobuf.MapField = require_mapfield(); - protobuf.Service = require_service3(); - protobuf.Method = require_method(); - protobuf.Message = require_message(); - protobuf.wrappers = require_wrappers(); - protobuf.types = require_types2(); - protobuf.util = require_util10(); - protobuf.ReflectionObject._configure(protobuf.Root); - protobuf.Namespace._configure(protobuf.Type, protobuf.Service, protobuf.Enum); - protobuf.Root._configure(protobuf.Type); - protobuf.Field._configure(protobuf.Type); - } -}); - -// node_modules/protobufjs/src/tokenize.js -var require_tokenize = __commonJS({ - "node_modules/protobufjs/src/tokenize.js"(exports2, module2) { - "use strict"; - module2.exports = tokenize; - var delimRe = /[\s{}=;:[\],'"()<>]/g; - var stringDoubleRe = /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g; - var stringSingleRe = /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g; - var setCommentRe = /^ *[*/]+ */; - var setCommentAltRe = /^\s*\*?\/*/; - var setCommentSplitRe = /\n/g; - var whitespaceRe = /\s/; - var unescapeRe = /\\(.?)/g; - var unescapeMap = { - "0": "\0", - "r": "\r", - "n": "\n", - "t": " " - }; - function unescape2(str) { - return str.replace(unescapeRe, function($0, $1) { - switch ($1) { - case "\\": - case "": - return $1; - default: - return unescapeMap[$1] || ""; - } - }); - } - tokenize.unescape = unescape2; - function tokenize(source, alternateCommentMode) { - source = source.toString(); - var offset = 0, length = source.length, line = 1, lastCommentLine = 0, comments = {}; - var stack = []; - var stringDelim = null; - function illegal(subject) { - return Error("illegal " + subject + " (line " + line + ")"); - } - function readString() { - var re = stringDelim === "'" ? stringSingleRe : stringDoubleRe; - re.lastIndex = offset - 1; - var match = re.exec(source); - if (!match) - throw illegal("string"); - offset = re.lastIndex; - push(stringDelim); - stringDelim = null; - return unescape2(match[1]); - } - function charAt(pos) { - return source.charAt(pos); - } - function setComment(start, end, isLeading) { - var comment = { - type: source.charAt(start++), - lineEmpty: false, - leading: isLeading - }; - var lookback; - if (alternateCommentMode) { - lookback = 2; - } else { - lookback = 3; - } - var commentOffset = start - lookback, c; - do { - if (--commentOffset < 0 || (c = source.charAt(commentOffset)) === "\n") { - comment.lineEmpty = true; - break; - } - } while (c === " " || c === " "); - var lines = source.substring(start, end).split(setCommentSplitRe); - for (var i = 0; i < lines.length; ++i) - lines[i] = lines[i].replace(alternateCommentMode ? setCommentAltRe : setCommentRe, "").trim(); - comment.text = lines.join("\n").trim(); - comments[line] = comment; - lastCommentLine = line; - } - function isDoubleSlashCommentLine(startOffset) { - var endOffset = findEndOfLine(startOffset); - var lineText = source.substring(startOffset, endOffset); - var isComment = /^\s*\/\//.test(lineText); - return isComment; - } - function findEndOfLine(cursor) { - var endOffset = cursor; - while (endOffset < length && charAt(endOffset) !== "\n") { - endOffset++; - } - return endOffset; - } - function next() { - if (stack.length > 0) - return stack.shift(); - if (stringDelim) - return readString(); - var repeat, prev, curr, start, isDoc, isLeadingComment = offset === 0; - do { - if (offset === length) - return null; - repeat = false; - while (whitespaceRe.test(curr = charAt(offset))) { - if (curr === "\n") { - isLeadingComment = true; - ++line; - } - if (++offset === length) - return null; - } - if (charAt(offset) === "/") { - if (++offset === length) { - throw illegal("comment"); - } - if (charAt(offset) === "/") { - if (!alternateCommentMode) { - isDoc = charAt(start = offset + 1) === "/"; - while (charAt(++offset) !== "\n") { - if (offset === length) { - return null; - } - } - ++offset; - if (isDoc) { - setComment(start, offset - 1, isLeadingComment); - isLeadingComment = true; - } - ++line; - repeat = true; - } else { - start = offset; - isDoc = false; - if (isDoubleSlashCommentLine(offset - 1)) { - isDoc = true; - do { - offset = findEndOfLine(offset); - if (offset === length) { - break; - } - offset++; - if (!isLeadingComment) { - break; - } - } while (isDoubleSlashCommentLine(offset)); - } else { - offset = Math.min(length, findEndOfLine(offset) + 1); - } - if (isDoc) { - setComment(start, offset, isLeadingComment); - isLeadingComment = true; - } - line++; - repeat = true; - } - } else if ((curr = charAt(offset)) === "*") { - start = offset + 1; - isDoc = alternateCommentMode || charAt(start) === "*"; - do { - if (curr === "\n") { - ++line; - } - if (++offset === length) { - throw illegal("comment"); - } - prev = curr; - curr = charAt(offset); - } while (prev !== "*" || curr !== "/"); - ++offset; - if (isDoc) { - setComment(start, offset - 2, isLeadingComment); - isLeadingComment = true; - } - repeat = true; - } else { - return "/"; - } - } - } while (repeat); - var end = offset; - delimRe.lastIndex = 0; - var delim = delimRe.test(charAt(end++)); - if (!delim) - while (end < length && !delimRe.test(charAt(end))) - ++end; - var token = source.substring(offset, offset = end); - if (token === '"' || token === "'") - stringDelim = token; - return token; - } - function push(token) { - stack.push(token); - } - function peek() { - if (!stack.length) { - var token = next(); - if (token === null) - return null; - push(token); - } - return stack[0]; - } - function skip(expected, optional) { - var actual = peek(), equals = actual === expected; - if (equals) { - next(); - return true; - } - if (!optional) - throw illegal("token '" + actual + "', '" + expected + "' expected"); - return false; - } - function cmnt(trailingLine) { - var ret = null; - var comment; - if (trailingLine === void 0) { - comment = comments[line - 1]; - delete comments[line - 1]; - if (comment && (alternateCommentMode || comment.type === "*" || comment.lineEmpty)) { - ret = comment.leading ? comment.text : null; - } - } else { - if (lastCommentLine < trailingLine) { - peek(); - } - comment = comments[trailingLine]; - delete comments[trailingLine]; - if (comment && !comment.lineEmpty && (alternateCommentMode || comment.type === "/")) { - ret = comment.leading ? null : comment.text; - } - } - return ret; - } - return Object.defineProperty({ - next, - peek, - push, - skip, - cmnt - }, "line", { - get: function() { - return line; - } - }); - } - } -}); - -// node_modules/protobufjs/src/parse.js -var require_parse2 = __commonJS({ - "node_modules/protobufjs/src/parse.js"(exports2, module2) { - "use strict"; - module2.exports = parse3; - parse3.filename = null; - parse3.defaults = { keepCase: false }; - var tokenize = require_tokenize(); - var Root = require_root(); - var Type = require_type(); - var Field = require_field(); - var MapField = require_mapfield(); - var OneOf = require_oneof(); - var Enum = require_enum(); - var Service = require_service3(); - var Method = require_method(); - var ReflectionObject = require_object(); - var types = require_types2(); - var util = require_util10(); - var base10Re = /^[1-9][0-9]*$/; - var base10NegRe = /^-?[1-9][0-9]*$/; - var base16Re = /^0[x][0-9a-fA-F]+$/; - var base16NegRe = /^-?0[x][0-9a-fA-F]+$/; - var base8Re = /^0[0-7]+$/; - var base8NegRe = /^-?0[0-7]+$/; - var numberRe = util.patterns.numberRe; - var nameRe = /^[a-zA-Z_][a-zA-Z_0-9]*$/; - var typeRefRe = util.patterns.typeRefRe; - function parse3(source, root, options) { - if (!(root instanceof Root)) { - options = root; - root = new Root(); - } - if (!options) - options = parse3.defaults; - var preferTrailingComment = options.preferTrailingComment || false; - var tn = tokenize(source, options.alternateCommentMode || false), next = tn.next, push = tn.push, peek = tn.peek, skip = tn.skip, cmnt = tn.cmnt; - var head = true, pkg, imports, weakImports, edition = "proto2"; - var ptr = root; - var topLevelObjects = []; - var topLevelOptions = {}; - var applyCase = options.keepCase ? function(name) { - return name; - } : util.camelCase; - function resolveFileFeatures() { - topLevelObjects.forEach((obj) => { - obj._edition = edition; - Object.keys(topLevelOptions).forEach((opt) => { - if (obj.getOption(opt) !== void 0) return; - obj.setOption(opt, topLevelOptions[opt], true); - }); - }); - } - function illegal(token2, name, insideTryCatch) { - var filename = parse3.filename; - if (!insideTryCatch) - parse3.filename = null; - return Error("illegal " + (name || "token") + " '" + token2 + "' (" + (filename ? filename + ", " : "") + "line " + tn.line + ")"); - } - function readString() { - var values = [], token2; - do { - if ((token2 = next()) !== '"' && token2 !== "'") - throw illegal(token2); - values.push(next()); - skip(token2); - token2 = peek(); - } while (token2 === '"' || token2 === "'"); - return values.join(""); - } - function readValue(acceptTypeRef) { - var token2 = next(); - switch (token2) { - case "'": - case '"': - push(token2); - return readString(); - case "true": - case "TRUE": - return true; - case "false": - case "FALSE": - return false; - } - try { - return parseNumber( - token2, - /* insideTryCatch */ - true - ); - } catch (e) { - if (acceptTypeRef && typeRefRe.test(token2)) - return token2; - throw illegal(token2, "value"); - } - } - function readRanges(target, acceptStrings) { - var token2, start; - do { - if (acceptStrings && ((token2 = peek()) === '"' || token2 === "'")) { - var str = readString(); - target.push(str); - if (edition >= 2023) { - throw illegal(str, "id"); - } - } else { - try { - target.push([start = parseId(next()), skip("to", true) ? parseId(next()) : start]); - } catch (err) { - if (acceptStrings && typeRefRe.test(token2) && edition >= 2023) { - target.push(token2); - } else { - throw err; - } - } - } - } while (skip(",", true)); - var dummy = { options: void 0 }; - dummy.setOption = function(name, value) { - if (this.options === void 0) this.options = {}; - this.options[name] = value; - }; - ifBlock( - dummy, - function parseRange_block(token3) { - if (token3 === "option") { - parseOption(dummy, token3); - skip(";"); - } else - throw illegal(token3); - }, - function parseRange_line() { - parseInlineOptions(dummy); - } - ); - } - function parseNumber(token2, insideTryCatch) { - var sign = 1; - if (token2.charAt(0) === "-") { - sign = -1; - token2 = token2.substring(1); - } - switch (token2) { - case "inf": - case "INF": - case "Inf": - return sign * Infinity; - case "nan": - case "NAN": - case "Nan": - case "NaN": - return NaN; - case "0": - return 0; - } - if (base10Re.test(token2)) - return sign * parseInt(token2, 10); - if (base16Re.test(token2)) - return sign * parseInt(token2, 16); - if (base8Re.test(token2)) - return sign * parseInt(token2, 8); - if (numberRe.test(token2)) - return sign * parseFloat(token2); - throw illegal(token2, "number", insideTryCatch); - } - function parseId(token2, acceptNegative) { - switch (token2) { - case "max": - case "MAX": - case "Max": - return 536870911; - case "0": - return 0; - } - if (!acceptNegative && token2.charAt(0) === "-") - throw illegal(token2, "id"); - if (base10NegRe.test(token2)) - return parseInt(token2, 10); - if (base16NegRe.test(token2)) - return parseInt(token2, 16); - if (base8NegRe.test(token2)) - return parseInt(token2, 8); - throw illegal(token2, "id"); - } - function parsePackage() { - if (pkg !== void 0) - throw illegal("package"); - pkg = next(); - if (!typeRefRe.test(pkg)) - throw illegal(pkg, "name"); - ptr = ptr.define(pkg); - skip(";"); - } - function parseImport() { - var token2 = peek(); - var whichImports; - switch (token2) { - case "weak": - whichImports = weakImports || (weakImports = []); - next(); - break; - case "public": - next(); - // eslint-disable-next-line no-fallthrough - default: - whichImports = imports || (imports = []); - break; - } - token2 = readString(); - skip(";"); - whichImports.push(token2); - } - function parseSyntax() { - skip("="); - edition = readString(); - if (edition < 2023) - throw illegal(edition, "syntax"); - skip(";"); - } - function parseEdition() { - skip("="); - edition = readString(); - const supportedEditions = ["2023"]; - if (!supportedEditions.includes(edition)) - throw illegal(edition, "edition"); - skip(";"); - } - function parseCommon(parent, token2) { - switch (token2) { - case "option": - parseOption(parent, token2); - skip(";"); - return true; - case "message": - parseType(parent, token2); - return true; - case "enum": - parseEnum(parent, token2); - return true; - case "service": - parseService(parent, token2); - return true; - case "extend": - parseExtension(parent, token2); - return true; - } - return false; - } - function ifBlock(obj, fnIf, fnElse) { - var trailingLine = tn.line; - if (obj) { - if (typeof obj.comment !== "string") { - obj.comment = cmnt(); - } - obj.filename = parse3.filename; - } - if (skip("{", true)) { - var token2; - while ((token2 = next()) !== "}") - fnIf(token2); - skip(";", true); - } else { - if (fnElse) - fnElse(); - skip(";"); - if (obj && (typeof obj.comment !== "string" || preferTrailingComment)) - obj.comment = cmnt(trailingLine) || obj.comment; - } - } - function parseType(parent, token2) { - if (!nameRe.test(token2 = next())) - throw illegal(token2, "type name"); - var type = new Type(token2); - ifBlock(type, function parseType_block(token3) { - if (parseCommon(type, token3)) - return; - switch (token3) { - case "map": - parseMapField(type, token3); - break; - case "required": - if (edition !== "proto2") - throw illegal(token3); - /* eslint-disable no-fallthrough */ - case "repeated": - parseField(type, token3); - break; - case "optional": - if (edition === "proto3") { - parseField(type, "proto3_optional"); - } else if (edition !== "proto2") { - throw illegal(token3); - } else { - parseField(type, "optional"); - } - break; - case "oneof": - parseOneOf(type, token3); - break; - case "extensions": - readRanges(type.extensions || (type.extensions = [])); - break; - case "reserved": - readRanges(type.reserved || (type.reserved = []), true); - break; - default: - if (edition === "proto2" || !typeRefRe.test(token3)) { - throw illegal(token3); - } - push(token3); - parseField(type, "optional"); - break; - } - }); - parent.add(type); - if (parent === ptr) { - topLevelObjects.push(type); - } - } - function parseField(parent, rule, extend) { - var type = next(); - if (type === "group") { - parseGroup(parent, rule); - return; - } - while (type.endsWith(".") || peek().startsWith(".")) { - type += next(); - } - if (!typeRefRe.test(type)) - throw illegal(type, "type"); - var name = next(); - if (!nameRe.test(name)) - throw illegal(name, "name"); - name = applyCase(name); - skip("="); - var field = new Field(name, parseId(next()), type, rule, extend); - ifBlock(field, function parseField_block(token2) { - if (token2 === "option") { - parseOption(field, token2); - skip(";"); - } else - throw illegal(token2); - }, function parseField_line() { - parseInlineOptions(field); - }); - if (rule === "proto3_optional") { - var oneof = new OneOf("_" + name); - field.setOption("proto3_optional", true); - oneof.add(field); - parent.add(oneof); - } else { - parent.add(field); - } - if (parent === ptr) { - topLevelObjects.push(field); - } - } - function parseGroup(parent, rule) { - if (edition >= 2023) { - throw illegal("group"); - } - var name = next(); - if (!nameRe.test(name)) - throw illegal(name, "name"); - var fieldName = util.lcFirst(name); - if (name === fieldName) - name = util.ucFirst(name); - skip("="); - var id = parseId(next()); - var type = new Type(name); - type.group = true; - var field = new Field(fieldName, id, name, rule); - field.filename = parse3.filename; - ifBlock(type, function parseGroup_block(token2) { - switch (token2) { - case "option": - parseOption(type, token2); - skip(";"); - break; - case "required": - case "repeated": - parseField(type, token2); - break; - case "optional": - if (edition === "proto3") { - parseField(type, "proto3_optional"); - } else { - parseField(type, "optional"); - } - break; - case "message": - parseType(type, token2); - break; - case "enum": - parseEnum(type, token2); - break; - case "reserved": - readRanges(type.reserved || (type.reserved = []), true); - break; - /* istanbul ignore next */ - default: - throw illegal(token2); - } - }); - parent.add(type).add(field); - } - function parseMapField(parent) { - skip("<"); - var keyType = next(); - if (types.mapKey[keyType] === void 0) - throw illegal(keyType, "type"); - skip(","); - var valueType = next(); - if (!typeRefRe.test(valueType)) - throw illegal(valueType, "type"); - skip(">"); - var name = next(); - if (!nameRe.test(name)) - throw illegal(name, "name"); - skip("="); - var field = new MapField(applyCase(name), parseId(next()), keyType, valueType); - ifBlock(field, function parseMapField_block(token2) { - if (token2 === "option") { - parseOption(field, token2); - skip(";"); - } else - throw illegal(token2); - }, function parseMapField_line() { - parseInlineOptions(field); - }); - parent.add(field); - } - function parseOneOf(parent, token2) { - if (!nameRe.test(token2 = next())) - throw illegal(token2, "name"); - var oneof = new OneOf(applyCase(token2)); - ifBlock(oneof, function parseOneOf_block(token3) { - if (token3 === "option") { - parseOption(oneof, token3); - skip(";"); - } else { - push(token3); - parseField(oneof, "optional"); - } - }); - parent.add(oneof); - } - function parseEnum(parent, token2) { - if (!nameRe.test(token2 = next())) - throw illegal(token2, "name"); - var enm = new Enum(token2); - ifBlock(enm, function parseEnum_block(token3) { - switch (token3) { - case "option": - parseOption(enm, token3); - skip(";"); - break; - case "reserved": - readRanges(enm.reserved || (enm.reserved = []), true); - if (enm.reserved === void 0) enm.reserved = []; - break; - default: - parseEnumValue(enm, token3); - } - }); - parent.add(enm); - if (parent === ptr) { - topLevelObjects.push(enm); - } - } - function parseEnumValue(parent, token2) { - if (!nameRe.test(token2)) - throw illegal(token2, "name"); - skip("="); - var value = parseId(next(), true), dummy = { - options: void 0 - }; - dummy.getOption = function(name) { - return this.options[name]; - }; - dummy.setOption = function(name, value2) { - ReflectionObject.prototype.setOption.call(dummy, name, value2); - }; - dummy.setParsedOption = function() { - return void 0; - }; - ifBlock(dummy, function parseEnumValue_block(token3) { - if (token3 === "option") { - parseOption(dummy, token3); - skip(";"); - } else - throw illegal(token3); - }, function parseEnumValue_line() { - parseInlineOptions(dummy); - }); - parent.add(token2, value, dummy.comment, dummy.parsedOptions || dummy.options); - } - function parseOption(parent, token2) { - var option; - var propName; - var isOption = true; - if (token2 === "option") { - token2 = next(); - } - while (token2 !== "=") { - if (token2 === "(") { - var parensValue = next(); - skip(")"); - token2 = "(" + parensValue + ")"; - } - if (isOption) { - isOption = false; - if (token2.includes(".") && !token2.includes("(")) { - var tokens = token2.split("."); - option = tokens[0] + "."; - token2 = tokens[1]; - continue; - } - option = token2; - } else { - propName = propName ? propName += token2 : token2; - } - token2 = next(); - } - var name = propName ? option.concat(propName) : option; - var optionValue = parseOptionValue(parent, name); - propName = propName && propName[0] === "." ? propName.slice(1) : propName; - option = option && option[option.length - 1] === "." ? option.slice(0, -1) : option; - setParsedOption(parent, option, optionValue, propName); - } - function parseOptionValue(parent, name) { - if (skip("{", true)) { - var objectResult = {}; - while (!skip("}", true)) { - if (!nameRe.test(token = next())) { - throw illegal(token, "name"); - } - if (token === null) { - throw illegal(token, "end of input"); - } - var value; - var propName = token; - skip(":", true); - if (peek() === "{") { - value = parseOptionValue(parent, name + "." + token); - } else if (peek() === "[") { - value = []; - var lastValue; - if (skip("[", true)) { - do { - lastValue = readValue(true); - value.push(lastValue); - } while (skip(",", true)); - skip("]"); - if (typeof lastValue !== "undefined") { - setOption(parent, name + "." + token, lastValue); - } - } - } else { - value = readValue(true); - setOption(parent, name + "." + token, value); - } - var prevValue = objectResult[propName]; - if (prevValue) - value = [].concat(prevValue).concat(value); - if (propName !== "__proto__") - objectResult[propName] = value; - skip(",", true); - skip(";", true); - } - return objectResult; - } - var simpleValue = readValue(true); - setOption(parent, name, simpleValue); - return simpleValue; - } - function setOption(parent, name, value) { - if (ptr === parent && /^features\./.test(name)) { - topLevelOptions[name] = value; - return; - } - if (parent.setOption) - parent.setOption(name, value); - } - function setParsedOption(parent, name, value, propName) { - if (parent.setParsedOption) - parent.setParsedOption(name, value, propName); - } - function parseInlineOptions(parent) { - if (skip("[", true)) { - do { - parseOption(parent, "option"); - } while (skip(",", true)); - skip("]"); - } - return parent; - } - function parseService(parent, token2) { - if (!nameRe.test(token2 = next())) - throw illegal(token2, "service name"); - var service = new Service(token2); - ifBlock(service, function parseService_block(token3) { - if (parseCommon(service, token3)) { - return; - } - if (token3 === "rpc") - parseMethod(service, token3); - else - throw illegal(token3); - }); - parent.add(service); - if (parent === ptr) { - topLevelObjects.push(service); - } - } - function parseMethod(parent, token2) { - var commentText = cmnt(); - var type = token2; - if (!nameRe.test(token2 = next())) - throw illegal(token2, "name"); - var name = token2, requestType, requestStream, responseType, responseStream; - skip("("); - if (skip("stream", true)) - requestStream = true; - if (!typeRefRe.test(token2 = next())) - throw illegal(token2); - requestType = token2; - skip(")"); - skip("returns"); - skip("("); - if (skip("stream", true)) - responseStream = true; - if (!typeRefRe.test(token2 = next())) - throw illegal(token2); - responseType = token2; - skip(")"); - var method = new Method(name, type, requestType, responseType, requestStream, responseStream); - method.comment = commentText; - ifBlock(method, function parseMethod_block(token3) { - if (token3 === "option") { - parseOption(method, token3); - skip(";"); - } else - throw illegal(token3); - }); - parent.add(method); - } - function parseExtension(parent, token2) { - if (!typeRefRe.test(token2 = next())) - throw illegal(token2, "reference"); - var reference = token2; - ifBlock(null, function parseExtension_block(token3) { - switch (token3) { - case "required": - case "repeated": - parseField(parent, token3, reference); - break; - case "optional": - if (edition === "proto3") { - parseField(parent, "proto3_optional", reference); - } else { - parseField(parent, "optional", reference); - } - break; - default: - if (edition === "proto2" || !typeRefRe.test(token3)) - throw illegal(token3); - push(token3); - parseField(parent, "optional", reference); - break; - } - }); - } - var token; - while ((token = next()) !== null) { - switch (token) { - case "package": - if (!head) - throw illegal(token); - parsePackage(); - break; - case "import": - if (!head) - throw illegal(token); - parseImport(); - break; - case "syntax": - if (!head) - throw illegal(token); - parseSyntax(); - break; - case "edition": - if (!head) - throw illegal(token); - parseEdition(); - break; - case "option": - parseOption(ptr, token); - skip(";", true); - break; - default: - if (parseCommon(ptr, token)) { - head = false; - continue; - } - throw illegal(token); - } - } - resolveFileFeatures(); - parse3.filename = null; - return { - "package": pkg, - "imports": imports, - weakImports, - root - }; - } - } -}); - -// node_modules/protobufjs/src/common.js -var require_common2 = __commonJS({ - "node_modules/protobufjs/src/common.js"(exports2, module2) { - "use strict"; - module2.exports = common; - var commonRe = /\/|\./; - function common(name, json) { - if (!commonRe.test(name)) { - name = "google/protobuf/" + name + ".proto"; - json = { nested: { google: { nested: { protobuf: { nested: json } } } } }; - } - common[name] = json; - } - common("any", { - /** - * Properties of a google.protobuf.Any message. - * @interface IAny - * @type {Object} - * @property {string} [typeUrl] - * @property {Uint8Array} [bytes] - * @memberof common - */ - Any: { - fields: { - type_url: { - type: "string", - id: 1 - }, - value: { - type: "bytes", - id: 2 - } - } - } - }); - var timeType; - common("duration", { - /** - * Properties of a google.protobuf.Duration message. - * @interface IDuration - * @type {Object} - * @property {number|Long} [seconds] - * @property {number} [nanos] - * @memberof common - */ - Duration: timeType = { - fields: { - seconds: { - type: "int64", - id: 1 - }, - nanos: { - type: "int32", - id: 2 - } - } - } - }); - common("timestamp", { - /** - * Properties of a google.protobuf.Timestamp message. - * @interface ITimestamp - * @type {Object} - * @property {number|Long} [seconds] - * @property {number} [nanos] - * @memberof common - */ - Timestamp: timeType - }); - common("empty", { - /** - * Properties of a google.protobuf.Empty message. - * @interface IEmpty - * @memberof common - */ - Empty: { - fields: {} - } - }); - common("struct", { - /** - * Properties of a google.protobuf.Struct message. - * @interface IStruct - * @type {Object} - * @property {Object.} [fields] - * @memberof common - */ - Struct: { - fields: { - fields: { - keyType: "string", - type: "Value", - id: 1 - } - } - }, - /** - * Properties of a google.protobuf.Value message. - * @interface IValue - * @type {Object} - * @property {string} [kind] - * @property {0} [nullValue] - * @property {number} [numberValue] - * @property {string} [stringValue] - * @property {boolean} [boolValue] - * @property {IStruct} [structValue] - * @property {IListValue} [listValue] - * @memberof common - */ - Value: { - oneofs: { - kind: { - oneof: [ - "nullValue", - "numberValue", - "stringValue", - "boolValue", - "structValue", - "listValue" - ] - } - }, - fields: { - nullValue: { - type: "NullValue", - id: 1 - }, - numberValue: { - type: "double", - id: 2 - }, - stringValue: { - type: "string", - id: 3 - }, - boolValue: { - type: "bool", - id: 4 - }, - structValue: { - type: "Struct", - id: 5 - }, - listValue: { - type: "ListValue", - id: 6 - } - } - }, - NullValue: { - values: { - NULL_VALUE: 0 - } - }, - /** - * Properties of a google.protobuf.ListValue message. - * @interface IListValue - * @type {Object} - * @property {Array.} [values] - * @memberof common - */ - ListValue: { - fields: { - values: { - rule: "repeated", - type: "Value", - id: 1 - } - } - } - }); - common("wrappers", { - /** - * Properties of a google.protobuf.DoubleValue message. - * @interface IDoubleValue - * @type {Object} - * @property {number} [value] - * @memberof common - */ - DoubleValue: { - fields: { - value: { - type: "double", - id: 1 - } - } - }, - /** - * Properties of a google.protobuf.FloatValue message. - * @interface IFloatValue - * @type {Object} - * @property {number} [value] - * @memberof common - */ - FloatValue: { - fields: { - value: { - type: "float", - id: 1 - } - } - }, - /** - * Properties of a google.protobuf.Int64Value message. - * @interface IInt64Value - * @type {Object} - * @property {number|Long} [value] - * @memberof common - */ - Int64Value: { - fields: { - value: { - type: "int64", - id: 1 - } - } - }, - /** - * Properties of a google.protobuf.UInt64Value message. - * @interface IUInt64Value - * @type {Object} - * @property {number|Long} [value] - * @memberof common - */ - UInt64Value: { - fields: { - value: { - type: "uint64", - id: 1 - } - } - }, - /** - * Properties of a google.protobuf.Int32Value message. - * @interface IInt32Value - * @type {Object} - * @property {number} [value] - * @memberof common - */ - Int32Value: { - fields: { - value: { - type: "int32", - id: 1 - } - } - }, - /** - * Properties of a google.protobuf.UInt32Value message. - * @interface IUInt32Value - * @type {Object} - * @property {number} [value] - * @memberof common - */ - UInt32Value: { - fields: { - value: { - type: "uint32", - id: 1 - } - } - }, - /** - * Properties of a google.protobuf.BoolValue message. - * @interface IBoolValue - * @type {Object} - * @property {boolean} [value] - * @memberof common - */ - BoolValue: { - fields: { - value: { - type: "bool", - id: 1 - } - } - }, - /** - * Properties of a google.protobuf.StringValue message. - * @interface IStringValue - * @type {Object} - * @property {string} [value] - * @memberof common - */ - StringValue: { - fields: { - value: { - type: "string", - id: 1 - } - } - }, - /** - * Properties of a google.protobuf.BytesValue message. - * @interface IBytesValue - * @type {Object} - * @property {Uint8Array} [value] - * @memberof common - */ - BytesValue: { - fields: { - value: { - type: "bytes", - id: 1 - } - } - } - }); - common("field_mask", { - /** - * Properties of a google.protobuf.FieldMask message. - * @interface IDoubleValue - * @type {Object} - * @property {number} [value] - * @memberof common - */ - FieldMask: { - fields: { - paths: { - rule: "repeated", - type: "string", - id: 1 - } - } - } - }); - common.get = function get(file) { - return common[file] || null; - }; - } -}); - -// node_modules/protobufjs/src/index.js -var require_src2 = __commonJS({ - "node_modules/protobufjs/src/index.js"(exports2, module2) { - "use strict"; - var protobuf = module2.exports = require_index_light(); - protobuf.build = "full"; - protobuf.tokenize = require_tokenize(); - protobuf.parse = require_parse2(); - protobuf.common = require_common2(); - protobuf.Root._configure(protobuf.Type, protobuf.parse, protobuf.common); - } -}); - -// node_modules/protobufjs/index.js -var require_protobufjs = __commonJS({ - "node_modules/protobufjs/index.js"(exports2, module2) { - "use strict"; - module2.exports = require_src2(); - } -}); - -// node_modules/protobufjs/google/protobuf/descriptor.json -var require_descriptor = __commonJS({ - "node_modules/protobufjs/google/protobuf/descriptor.json"(exports2, module2) { - module2.exports = { - nested: { - google: { - nested: { - protobuf: { - options: { - go_package: "google.golang.org/protobuf/types/descriptorpb", - java_package: "com.google.protobuf", - java_outer_classname: "DescriptorProtos", - csharp_namespace: "Google.Protobuf.Reflection", - objc_class_prefix: "GPB", - cc_enable_arenas: true, - optimize_for: "SPEED" - }, - nested: { - FileDescriptorSet: { - edition: "proto2", - fields: { - file: { - rule: "repeated", - type: "FileDescriptorProto", - id: 1 - } - }, - extensions: [ - [ - 536e6, - 536e6 - ] - ] - }, - Edition: { - edition: "proto2", - values: { - EDITION_UNKNOWN: 0, - EDITION_LEGACY: 900, - EDITION_PROTO2: 998, - EDITION_PROTO3: 999, - EDITION_2023: 1e3, - EDITION_2024: 1001, - EDITION_1_TEST_ONLY: 1, - EDITION_2_TEST_ONLY: 2, - EDITION_99997_TEST_ONLY: 99997, - EDITION_99998_TEST_ONLY: 99998, - EDITION_99999_TEST_ONLY: 99999, - EDITION_MAX: 2147483647 - } - }, - FileDescriptorProto: { - edition: "proto2", - fields: { - name: { - type: "string", - id: 1 - }, - package: { - type: "string", - id: 2 - }, - dependency: { - rule: "repeated", - type: "string", - id: 3 - }, - publicDependency: { - rule: "repeated", - type: "int32", - id: 10 - }, - weakDependency: { - rule: "repeated", - type: "int32", - id: 11 - }, - optionDependency: { - rule: "repeated", - type: "string", - id: 15 - }, - messageType: { - rule: "repeated", - type: "DescriptorProto", - id: 4 - }, - enumType: { - rule: "repeated", - type: "EnumDescriptorProto", - id: 5 - }, - service: { - rule: "repeated", - type: "ServiceDescriptorProto", - id: 6 - }, - extension: { - rule: "repeated", - type: "FieldDescriptorProto", - id: 7 - }, - options: { - type: "FileOptions", - id: 8 - }, - sourceCodeInfo: { - type: "SourceCodeInfo", - id: 9 - }, - syntax: { - type: "string", - id: 12 - }, - edition: { - type: "Edition", - id: 14 - } - } - }, - DescriptorProto: { - edition: "proto2", - fields: { - name: { - type: "string", - id: 1 - }, - field: { - rule: "repeated", - type: "FieldDescriptorProto", - id: 2 - }, - extension: { - rule: "repeated", - type: "FieldDescriptorProto", - id: 6 - }, - nestedType: { - rule: "repeated", - type: "DescriptorProto", - id: 3 - }, - enumType: { - rule: "repeated", - type: "EnumDescriptorProto", - id: 4 - }, - extensionRange: { - rule: "repeated", - type: "ExtensionRange", - id: 5 - }, - oneofDecl: { - rule: "repeated", - type: "OneofDescriptorProto", - id: 8 - }, - options: { - type: "MessageOptions", - id: 7 - }, - reservedRange: { - rule: "repeated", - type: "ReservedRange", - id: 9 - }, - reservedName: { - rule: "repeated", - type: "string", - id: 10 - }, - visibility: { - type: "SymbolVisibility", - id: 11 - } - }, - nested: { - ExtensionRange: { - fields: { - start: { - type: "int32", - id: 1 - }, - end: { - type: "int32", - id: 2 - }, - options: { - type: "ExtensionRangeOptions", - id: 3 - } - } - }, - ReservedRange: { - fields: { - start: { - type: "int32", - id: 1 - }, - end: { - type: "int32", - id: 2 - } - } - } - } - }, - ExtensionRangeOptions: { - edition: "proto2", - fields: { - uninterpretedOption: { - rule: "repeated", - type: "UninterpretedOption", - id: 999 - }, - declaration: { - rule: "repeated", - type: "Declaration", - id: 2, - options: { - retention: "RETENTION_SOURCE" - } - }, - features: { - type: "FeatureSet", - id: 50 - }, - verification: { - type: "VerificationState", - id: 3, - options: { - default: "UNVERIFIED", - retention: "RETENTION_SOURCE" - } - } - }, - extensions: [ - [ - 1e3, - 536870911 - ] - ], - nested: { - Declaration: { - fields: { - number: { - type: "int32", - id: 1 - }, - fullName: { - type: "string", - id: 2 - }, - type: { - type: "string", - id: 3 - }, - reserved: { - type: "bool", - id: 5 - }, - repeated: { - type: "bool", - id: 6 - } - }, - reserved: [ - [ - 4, - 4 - ] - ] - }, - VerificationState: { - values: { - DECLARATION: 0, - UNVERIFIED: 1 - } - } - } - }, - FieldDescriptorProto: { - edition: "proto2", - fields: { - name: { - type: "string", - id: 1 - }, - number: { - type: "int32", - id: 3 - }, - label: { - type: "Label", - id: 4 - }, - type: { - type: "Type", - id: 5 - }, - typeName: { - type: "string", - id: 6 - }, - extendee: { - type: "string", - id: 2 - }, - defaultValue: { - type: "string", - id: 7 - }, - oneofIndex: { - type: "int32", - id: 9 - }, - jsonName: { - type: "string", - id: 10 - }, - options: { - type: "FieldOptions", - id: 8 - }, - proto3Optional: { - type: "bool", - id: 17 - } - }, - nested: { - Type: { - values: { - TYPE_DOUBLE: 1, - TYPE_FLOAT: 2, - TYPE_INT64: 3, - TYPE_UINT64: 4, - TYPE_INT32: 5, - TYPE_FIXED64: 6, - TYPE_FIXED32: 7, - TYPE_BOOL: 8, - TYPE_STRING: 9, - TYPE_GROUP: 10, - TYPE_MESSAGE: 11, - TYPE_BYTES: 12, - TYPE_UINT32: 13, - TYPE_ENUM: 14, - TYPE_SFIXED32: 15, - TYPE_SFIXED64: 16, - TYPE_SINT32: 17, - TYPE_SINT64: 18 - } - }, - Label: { - values: { - LABEL_OPTIONAL: 1, - LABEL_REPEATED: 3, - LABEL_REQUIRED: 2 - } - } - } - }, - OneofDescriptorProto: { - edition: "proto2", - fields: { - name: { - type: "string", - id: 1 - }, - options: { - type: "OneofOptions", - id: 2 - } - } - }, - EnumDescriptorProto: { - edition: "proto2", - fields: { - name: { - type: "string", - id: 1 - }, - value: { - rule: "repeated", - type: "EnumValueDescriptorProto", - id: 2 - }, - options: { - type: "EnumOptions", - id: 3 - }, - reservedRange: { - rule: "repeated", - type: "EnumReservedRange", - id: 4 - }, - reservedName: { - rule: "repeated", - type: "string", - id: 5 - }, - visibility: { - type: "SymbolVisibility", - id: 6 - } - }, - nested: { - EnumReservedRange: { - fields: { - start: { - type: "int32", - id: 1 - }, - end: { - type: "int32", - id: 2 - } - } - } - } - }, - EnumValueDescriptorProto: { - edition: "proto2", - fields: { - name: { - type: "string", - id: 1 - }, - number: { - type: "int32", - id: 2 - }, - options: { - type: "EnumValueOptions", - id: 3 - } - } - }, - ServiceDescriptorProto: { - edition: "proto2", - fields: { - name: { - type: "string", - id: 1 - }, - method: { - rule: "repeated", - type: "MethodDescriptorProto", - id: 2 - }, - options: { - type: "ServiceOptions", - id: 3 - } - } - }, - MethodDescriptorProto: { - edition: "proto2", - fields: { - name: { - type: "string", - id: 1 - }, - inputType: { - type: "string", - id: 2 - }, - outputType: { - type: "string", - id: 3 - }, - options: { - type: "MethodOptions", - id: 4 - }, - clientStreaming: { - type: "bool", - id: 5 - }, - serverStreaming: { - type: "bool", - id: 6 - } - } - }, - FileOptions: { - edition: "proto2", - fields: { - javaPackage: { - type: "string", - id: 1 - }, - javaOuterClassname: { - type: "string", - id: 8 - }, - javaMultipleFiles: { - type: "bool", - id: 10 - }, - javaGenerateEqualsAndHash: { - type: "bool", - id: 20, - options: { - deprecated: true - } - }, - javaStringCheckUtf8: { - type: "bool", - id: 27 - }, - optimizeFor: { - type: "OptimizeMode", - id: 9, - options: { - default: "SPEED" - } - }, - goPackage: { - type: "string", - id: 11 - }, - ccGenericServices: { - type: "bool", - id: 16 - }, - javaGenericServices: { - type: "bool", - id: 17 - }, - pyGenericServices: { - type: "bool", - id: 18 - }, - deprecated: { - type: "bool", - id: 23 - }, - ccEnableArenas: { - type: "bool", - id: 31, - options: { - default: true - } - }, - objcClassPrefix: { - type: "string", - id: 36 - }, - csharpNamespace: { - type: "string", - id: 37 - }, - swiftPrefix: { - type: "string", - id: 39 - }, - phpClassPrefix: { - type: "string", - id: 40 - }, - phpNamespace: { - type: "string", - id: 41 - }, - phpMetadataNamespace: { - type: "string", - id: 44 - }, - rubyPackage: { - type: "string", - id: 45 - }, - features: { - type: "FeatureSet", - id: 50 - }, - uninterpretedOption: { - rule: "repeated", - type: "UninterpretedOption", - id: 999 - } - }, - extensions: [ - [ - 1e3, - 536870911 - ] - ], - reserved: [ - [ - 42, - 42 - ], - [ - 38, - 38 - ], - "php_generic_services" - ], - nested: { - OptimizeMode: { - values: { - SPEED: 1, - CODE_SIZE: 2, - LITE_RUNTIME: 3 - } - } - } - }, - MessageOptions: { - edition: "proto2", - fields: { - messageSetWireFormat: { - type: "bool", - id: 1 - }, - noStandardDescriptorAccessor: { - type: "bool", - id: 2 - }, - deprecated: { - type: "bool", - id: 3 - }, - mapEntry: { - type: "bool", - id: 7 - }, - deprecatedLegacyJsonFieldConflicts: { - type: "bool", - id: 11, - options: { - deprecated: true - } - }, - features: { - type: "FeatureSet", - id: 12 - }, - uninterpretedOption: { - rule: "repeated", - type: "UninterpretedOption", - id: 999 - } - }, - extensions: [ - [ - 1e3, - 536870911 - ] - ], - reserved: [ - [ - 4, - 4 - ], - [ - 5, - 5 - ], - [ - 6, - 6 - ], - [ - 8, - 8 - ], - [ - 9, - 9 - ] - ] - }, - FieldOptions: { - edition: "proto2", - fields: { - ctype: { - type: "CType", - id: 1, - options: { - default: "STRING" - } - }, - packed: { - type: "bool", - id: 2 - }, - jstype: { - type: "JSType", - id: 6, - options: { - default: "JS_NORMAL" - } - }, - lazy: { - type: "bool", - id: 5 - }, - unverifiedLazy: { - type: "bool", - id: 15 - }, - deprecated: { - type: "bool", - id: 3 - }, - weak: { - type: "bool", - id: 10, - options: { - deprecated: true - } - }, - debugRedact: { - type: "bool", - id: 16 - }, - retention: { - type: "OptionRetention", - id: 17 - }, - targets: { - rule: "repeated", - type: "OptionTargetType", - id: 19 - }, - editionDefaults: { - rule: "repeated", - type: "EditionDefault", - id: 20 - }, - features: { - type: "FeatureSet", - id: 21 - }, - featureSupport: { - type: "FeatureSupport", - id: 22 - }, - uninterpretedOption: { - rule: "repeated", - type: "UninterpretedOption", - id: 999 - } - }, - extensions: [ - [ - 1e3, - 536870911 - ] - ], - reserved: [ - [ - 4, - 4 - ], - [ - 18, - 18 - ] - ], - nested: { - CType: { - values: { - STRING: 0, - CORD: 1, - STRING_PIECE: 2 - } - }, - JSType: { - values: { - JS_NORMAL: 0, - JS_STRING: 1, - JS_NUMBER: 2 - } - }, - OptionRetention: { - values: { - RETENTION_UNKNOWN: 0, - RETENTION_RUNTIME: 1, - RETENTION_SOURCE: 2 - } - }, - OptionTargetType: { - values: { - TARGET_TYPE_UNKNOWN: 0, - TARGET_TYPE_FILE: 1, - TARGET_TYPE_EXTENSION_RANGE: 2, - TARGET_TYPE_MESSAGE: 3, - TARGET_TYPE_FIELD: 4, - TARGET_TYPE_ONEOF: 5, - TARGET_TYPE_ENUM: 6, - TARGET_TYPE_ENUM_ENTRY: 7, - TARGET_TYPE_SERVICE: 8, - TARGET_TYPE_METHOD: 9 - } - }, - EditionDefault: { - fields: { - edition: { - type: "Edition", - id: 3 - }, - value: { - type: "string", - id: 2 - } - } - }, - FeatureSupport: { - fields: { - editionIntroduced: { - type: "Edition", - id: 1 - }, - editionDeprecated: { - type: "Edition", - id: 2 - }, - deprecationWarning: { - type: "string", - id: 3 - }, - editionRemoved: { - type: "Edition", - id: 4 - } - } - } - } - }, - OneofOptions: { - edition: "proto2", - fields: { - features: { - type: "FeatureSet", - id: 1 - }, - uninterpretedOption: { - rule: "repeated", - type: "UninterpretedOption", - id: 999 - } - }, - extensions: [ - [ - 1e3, - 536870911 - ] - ] - }, - EnumOptions: { - edition: "proto2", - fields: { - allowAlias: { - type: "bool", - id: 2 - }, - deprecated: { - type: "bool", - id: 3 - }, - deprecatedLegacyJsonFieldConflicts: { - type: "bool", - id: 6, - options: { - deprecated: true - } - }, - features: { - type: "FeatureSet", - id: 7 - }, - uninterpretedOption: { - rule: "repeated", - type: "UninterpretedOption", - id: 999 - } - }, - extensions: [ - [ - 1e3, - 536870911 - ] - ], - reserved: [ - [ - 5, - 5 - ] - ] - }, - EnumValueOptions: { - edition: "proto2", - fields: { - deprecated: { - type: "bool", - id: 1 - }, - features: { - type: "FeatureSet", - id: 2 - }, - debugRedact: { - type: "bool", - id: 3 - }, - featureSupport: { - type: "FieldOptions.FeatureSupport", - id: 4 - }, - uninterpretedOption: { - rule: "repeated", - type: "UninterpretedOption", - id: 999 - } - }, - extensions: [ - [ - 1e3, - 536870911 - ] - ] - }, - ServiceOptions: { - edition: "proto2", - fields: { - features: { - type: "FeatureSet", - id: 34 - }, - deprecated: { - type: "bool", - id: 33 - }, - uninterpretedOption: { - rule: "repeated", - type: "UninterpretedOption", - id: 999 - } - }, - extensions: [ - [ - 1e3, - 536870911 - ] - ] - }, - MethodOptions: { - edition: "proto2", - fields: { - deprecated: { - type: "bool", - id: 33 - }, - idempotencyLevel: { - type: "IdempotencyLevel", - id: 34, - options: { - default: "IDEMPOTENCY_UNKNOWN" - } - }, - features: { - type: "FeatureSet", - id: 35 - }, - uninterpretedOption: { - rule: "repeated", - type: "UninterpretedOption", - id: 999 - } - }, - extensions: [ - [ - 1e3, - 536870911 - ] - ], - nested: { - IdempotencyLevel: { - values: { - IDEMPOTENCY_UNKNOWN: 0, - NO_SIDE_EFFECTS: 1, - IDEMPOTENT: 2 - } - } - } - }, - UninterpretedOption: { - edition: "proto2", - fields: { - name: { - rule: "repeated", - type: "NamePart", - id: 2 - }, - identifierValue: { - type: "string", - id: 3 - }, - positiveIntValue: { - type: "uint64", - id: 4 - }, - negativeIntValue: { - type: "int64", - id: 5 - }, - doubleValue: { - type: "double", - id: 6 - }, - stringValue: { - type: "bytes", - id: 7 - }, - aggregateValue: { - type: "string", - id: 8 - } - }, - nested: { - NamePart: { - fields: { - namePart: { - rule: "required", - type: "string", - id: 1 - }, - isExtension: { - rule: "required", - type: "bool", - id: 2 - } - } - } - } - }, - FeatureSet: { - edition: "proto2", - fields: { - fieldPresence: { - type: "FieldPresence", - id: 1, - options: { - retention: "RETENTION_RUNTIME", - targets: "TARGET_TYPE_FILE", - "feature_support.edition_introduced": "EDITION_2023", - "edition_defaults.edition": "EDITION_2023", - "edition_defaults.value": "EXPLICIT" - } - }, - enumType: { - type: "EnumType", - id: 2, - options: { - retention: "RETENTION_RUNTIME", - targets: "TARGET_TYPE_FILE", - "feature_support.edition_introduced": "EDITION_2023", - "edition_defaults.edition": "EDITION_PROTO3", - "edition_defaults.value": "OPEN" - } - }, - repeatedFieldEncoding: { - type: "RepeatedFieldEncoding", - id: 3, - options: { - retention: "RETENTION_RUNTIME", - targets: "TARGET_TYPE_FILE", - "feature_support.edition_introduced": "EDITION_2023", - "edition_defaults.edition": "EDITION_PROTO3", - "edition_defaults.value": "PACKED" - } - }, - utf8Validation: { - type: "Utf8Validation", - id: 4, - options: { - retention: "RETENTION_RUNTIME", - targets: "TARGET_TYPE_FILE", - "feature_support.edition_introduced": "EDITION_2023", - "edition_defaults.edition": "EDITION_PROTO3", - "edition_defaults.value": "VERIFY" - } - }, - messageEncoding: { - type: "MessageEncoding", - id: 5, - options: { - retention: "RETENTION_RUNTIME", - targets: "TARGET_TYPE_FILE", - "feature_support.edition_introduced": "EDITION_2023", - "edition_defaults.edition": "EDITION_LEGACY", - "edition_defaults.value": "LENGTH_PREFIXED" - } - }, - jsonFormat: { - type: "JsonFormat", - id: 6, - options: { - retention: "RETENTION_RUNTIME", - targets: "TARGET_TYPE_FILE", - "feature_support.edition_introduced": "EDITION_2023", - "edition_defaults.edition": "EDITION_PROTO3", - "edition_defaults.value": "ALLOW" - } - }, - enforceNamingStyle: { - type: "EnforceNamingStyle", - id: 7, - options: { - retention: "RETENTION_SOURCE", - targets: "TARGET_TYPE_METHOD", - "feature_support.edition_introduced": "EDITION_2024", - "edition_defaults.edition": "EDITION_2024", - "edition_defaults.value": "STYLE2024" - } - }, - defaultSymbolVisibility: { - type: "VisibilityFeature.DefaultSymbolVisibility", - id: 8, - options: { - retention: "RETENTION_SOURCE", - targets: "TARGET_TYPE_FILE", - "feature_support.edition_introduced": "EDITION_2024", - "edition_defaults.edition": "EDITION_2024", - "edition_defaults.value": "EXPORT_TOP_LEVEL" - } - } - }, - extensions: [ - [ - 1e3, - 9994 - ], - [ - 9995, - 9999 - ], - [ - 1e4, - 1e4 - ] - ], - reserved: [ - [ - 999, - 999 - ] - ], - nested: { - FieldPresence: { - values: { - FIELD_PRESENCE_UNKNOWN: 0, - EXPLICIT: 1, - IMPLICIT: 2, - LEGACY_REQUIRED: 3 - } - }, - EnumType: { - values: { - ENUM_TYPE_UNKNOWN: 0, - OPEN: 1, - CLOSED: 2 - } - }, - RepeatedFieldEncoding: { - values: { - REPEATED_FIELD_ENCODING_UNKNOWN: 0, - PACKED: 1, - EXPANDED: 2 - } - }, - Utf8Validation: { - values: { - UTF8_VALIDATION_UNKNOWN: 0, - VERIFY: 2, - NONE: 3 - } - }, - MessageEncoding: { - values: { - MESSAGE_ENCODING_UNKNOWN: 0, - LENGTH_PREFIXED: 1, - DELIMITED: 2 - } - }, - JsonFormat: { - values: { - JSON_FORMAT_UNKNOWN: 0, - ALLOW: 1, - LEGACY_BEST_EFFORT: 2 - } - }, - EnforceNamingStyle: { - values: { - ENFORCE_NAMING_STYLE_UNKNOWN: 0, - STYLE2024: 1, - STYLE_LEGACY: 2 - } - }, - VisibilityFeature: { - fields: {}, - reserved: [ - [ - 1, - 536870911 - ] - ], - nested: { - DefaultSymbolVisibility: { - values: { - DEFAULT_SYMBOL_VISIBILITY_UNKNOWN: 0, - EXPORT_ALL: 1, - EXPORT_TOP_LEVEL: 2, - LOCAL_ALL: 3, - STRICT: 4 - } - } - } - } - } - }, - FeatureSetDefaults: { - edition: "proto2", - fields: { - defaults: { - rule: "repeated", - type: "FeatureSetEditionDefault", - id: 1 - }, - minimumEdition: { - type: "Edition", - id: 4 - }, - maximumEdition: { - type: "Edition", - id: 5 - } - }, - nested: { - FeatureSetEditionDefault: { - fields: { - edition: { - type: "Edition", - id: 3 - }, - overridableFeatures: { - type: "FeatureSet", - id: 4 - }, - fixedFeatures: { - type: "FeatureSet", - id: 5 - } - }, - reserved: [ - [ - 1, - 1 - ], - [ - 2, - 2 - ], - "features" - ] - } - } - }, - SourceCodeInfo: { - edition: "proto2", - fields: { - location: { - rule: "repeated", - type: "Location", - id: 1 - } - }, - extensions: [ - [ - 536e6, - 536e6 - ] - ], - nested: { - Location: { - fields: { - path: { - rule: "repeated", - type: "int32", - id: 1, - options: { - packed: true - } - }, - span: { - rule: "repeated", - type: "int32", - id: 2, - options: { - packed: true - } - }, - leadingComments: { - type: "string", - id: 3 - }, - trailingComments: { - type: "string", - id: 4 - }, - leadingDetachedComments: { - rule: "repeated", - type: "string", - id: 6 - } - } - } - } - }, - GeneratedCodeInfo: { - edition: "proto2", - fields: { - annotation: { - rule: "repeated", - type: "Annotation", - id: 1 - } - }, - nested: { - Annotation: { - fields: { - path: { - rule: "repeated", - type: "int32", - id: 1, - options: { - packed: true - } - }, - sourceFile: { - type: "string", - id: 2 - }, - begin: { - type: "int32", - id: 3 - }, - end: { - type: "int32", - id: 4 - }, - semantic: { - type: "Semantic", - id: 5 - } - }, - nested: { - Semantic: { - values: { - NONE: 0, - SET: 1, - ALIAS: 2 - } - } - } - } - } - }, - SymbolVisibility: { - edition: "proto2", - values: { - VISIBILITY_UNSET: 0, - VISIBILITY_LOCAL: 1, - VISIBILITY_EXPORT: 2 - } - } - } - } - } - } - } - }; - } -}); - -// node_modules/protobufjs/ext/descriptor/index.js -var require_descriptor2 = __commonJS({ - "node_modules/protobufjs/ext/descriptor/index.js"(exports2, module2) { - "use strict"; - var $protobuf = require_protobufjs(); - module2.exports = exports2 = $protobuf.descriptor = $protobuf.Root.fromJSON(require_descriptor()).lookup(".google.protobuf"); - var Namespace = $protobuf.Namespace; - var Root = $protobuf.Root; - var Enum = $protobuf.Enum; - var Type = $protobuf.Type; - var Field = $protobuf.Field; - var MapField = $protobuf.MapField; - var OneOf = $protobuf.OneOf; - var Service = $protobuf.Service; - var Method = $protobuf.Method; - var patterns = $protobuf.util.patterns; - var numberRe = patterns.numberRe; - var typeRefRe = patterns.typeRefRe; - Root.fromDescriptor = function fromDescriptor(descriptor) { - if (typeof descriptor.length === "number") - descriptor = exports2.FileDescriptorSet.decode(descriptor); - var root = new Root(); - if (descriptor.file) { - var fileDescriptor, filePackage; - for (var j = 0, i; j < descriptor.file.length; ++j) { - filePackage = root; - if ((fileDescriptor = descriptor.file[j])["package"] && fileDescriptor["package"].length) - filePackage = root.define(fileDescriptor["package"]); - var edition = editionFromDescriptor(fileDescriptor); - if (fileDescriptor.name && fileDescriptor.name.length) - root.files.push(filePackage.filename = fileDescriptor.name); - if (fileDescriptor.messageType) - for (i = 0; i < fileDescriptor.messageType.length; ++i) - filePackage.add(Type.fromDescriptor(fileDescriptor.messageType[i], edition)); - if (fileDescriptor.enumType) - for (i = 0; i < fileDescriptor.enumType.length; ++i) - filePackage.add(Enum.fromDescriptor(fileDescriptor.enumType[i], edition)); - if (fileDescriptor.extension) - for (i = 0; i < fileDescriptor.extension.length; ++i) - filePackage.add(Field.fromDescriptor(fileDescriptor.extension[i], edition)); - if (fileDescriptor.service) - for (i = 0; i < fileDescriptor.service.length; ++i) - filePackage.add(Service.fromDescriptor(fileDescriptor.service[i], edition)); - var opts = fromDescriptorOptions(fileDescriptor.options, exports2.FileOptions); - if (opts) { - var ks = Object.keys(opts); - for (i = 0; i < ks.length; ++i) - filePackage.setOption(ks[i], opts[ks[i]]); - } - } - } - return root.resolveAll(); - }; - Root.prototype.toDescriptor = function toDescriptor(edition) { - var set = exports2.FileDescriptorSet.create(); - Root_toDescriptorRecursive(this, set.file, edition); - return set; - }; - function Root_toDescriptorRecursive(ns, files, edition) { - var file = exports2.FileDescriptorProto.create({ name: ns.filename || (ns.fullName.substring(1).replace(/\./g, "_") || "root") + ".proto" }); - editionToDescriptor(edition, file); - if (!(ns instanceof Root)) - file["package"] = ns.fullName.substring(1); - for (var i = 0, nested; i < ns.nestedArray.length; ++i) - if ((nested = ns._nestedArray[i]) instanceof Type) - file.messageType.push(nested.toDescriptor(edition)); - else if (nested instanceof Enum) - file.enumType.push(nested.toDescriptor()); - else if (nested instanceof Field) - file.extension.push(nested.toDescriptor(edition)); - else if (nested instanceof Service) - file.service.push(nested.toDescriptor()); - else if (nested instanceof /* plain */ - Namespace) - Root_toDescriptorRecursive(nested, files, edition); - file.options = toDescriptorOptions(ns.options, exports2.FileOptions); - if (file.messageType.length + file.enumType.length + file.extension.length + file.service.length) - files.push(file); - } - var unnamedMessageIndex = 0; - Type.fromDescriptor = function fromDescriptor(descriptor, edition, nested) { - if (typeof descriptor.length === "number") - descriptor = exports2.DescriptorProto.decode(descriptor); - var type = new Type(descriptor.name.length ? descriptor.name : "Type" + unnamedMessageIndex++, fromDescriptorOptions(descriptor.options, exports2.MessageOptions)), i; - if (!nested) - type._edition = edition; - if (descriptor.oneofDecl) - for (i = 0; i < descriptor.oneofDecl.length; ++i) - type.add(OneOf.fromDescriptor(descriptor.oneofDecl[i])); - if (descriptor.field) - for (i = 0; i < descriptor.field.length; ++i) { - var field = Field.fromDescriptor(descriptor.field[i], edition, true); - type.add(field); - if (descriptor.field[i].hasOwnProperty("oneofIndex")) - type.oneofsArray[descriptor.field[i].oneofIndex].add(field); - } - if (descriptor.extension) - for (i = 0; i < descriptor.extension.length; ++i) - type.add(Field.fromDescriptor(descriptor.extension[i], edition, true)); - if (descriptor.nestedType) - for (i = 0; i < descriptor.nestedType.length; ++i) { - type.add(Type.fromDescriptor(descriptor.nestedType[i], edition, true)); - if (descriptor.nestedType[i].options && descriptor.nestedType[i].options.mapEntry) - type.setOption("map_entry", true); - } - if (descriptor.enumType) - for (i = 0; i < descriptor.enumType.length; ++i) - type.add(Enum.fromDescriptor(descriptor.enumType[i], edition, true)); - if (descriptor.extensionRange && descriptor.extensionRange.length) { - type.extensions = []; - for (i = 0; i < descriptor.extensionRange.length; ++i) - type.extensions.push([descriptor.extensionRange[i].start, descriptor.extensionRange[i].end]); - } - if (descriptor.reservedRange && descriptor.reservedRange.length || descriptor.reservedName && descriptor.reservedName.length) { - type.reserved = []; - if (descriptor.reservedRange) - for (i = 0; i < descriptor.reservedRange.length; ++i) - type.reserved.push([descriptor.reservedRange[i].start, descriptor.reservedRange[i].end]); - if (descriptor.reservedName) - for (i = 0; i < descriptor.reservedName.length; ++i) - type.reserved.push(descriptor.reservedName[i]); - } - return type; - }; - Type.prototype.toDescriptor = function toDescriptor(edition) { - var descriptor = exports2.DescriptorProto.create({ name: this.name }), i; - for (i = 0; i < this.fieldsArray.length; ++i) { - var fieldDescriptor; - descriptor.field.push(fieldDescriptor = this._fieldsArray[i].toDescriptor(edition)); - if (this._fieldsArray[i] instanceof MapField) { - var keyType = toDescriptorType(this._fieldsArray[i].keyType, this._fieldsArray[i].resolvedKeyType, false), valueType = toDescriptorType(this._fieldsArray[i].type, this._fieldsArray[i].resolvedType, false), valueTypeName = valueType === /* type */ - 11 || valueType === /* enum */ - 14 ? this._fieldsArray[i].resolvedType && shortname(this.parent, this._fieldsArray[i].resolvedType) || this._fieldsArray[i].type : void 0; - descriptor.nestedType.push(exports2.DescriptorProto.create({ - name: fieldDescriptor.typeName, - field: [ - exports2.FieldDescriptorProto.create({ name: "key", number: 1, label: 1, type: keyType }), - // can't reference a type or enum - exports2.FieldDescriptorProto.create({ name: "value", number: 2, label: 1, type: valueType, typeName: valueTypeName }) - ], - options: exports2.MessageOptions.create({ mapEntry: true }) - })); - } - } - for (i = 0; i < this.oneofsArray.length; ++i) - descriptor.oneofDecl.push(this._oneofsArray[i].toDescriptor()); - for (i = 0; i < this.nestedArray.length; ++i) { - if (this._nestedArray[i] instanceof Field) - descriptor.field.push(this._nestedArray[i].toDescriptor(edition)); - else if (this._nestedArray[i] instanceof Type) - descriptor.nestedType.push(this._nestedArray[i].toDescriptor(edition)); - else if (this._nestedArray[i] instanceof Enum) - descriptor.enumType.push(this._nestedArray[i].toDescriptor()); - } - if (this.extensions) - for (i = 0; i < this.extensions.length; ++i) - descriptor.extensionRange.push(exports2.DescriptorProto.ExtensionRange.create({ start: this.extensions[i][0], end: this.extensions[i][1] })); - if (this.reserved) - for (i = 0; i < this.reserved.length; ++i) - if (typeof this.reserved[i] === "string") - descriptor.reservedName.push(this.reserved[i]); - else - descriptor.reservedRange.push(exports2.DescriptorProto.ReservedRange.create({ start: this.reserved[i][0], end: this.reserved[i][1] })); - descriptor.options = toDescriptorOptions(this.options, exports2.MessageOptions); - return descriptor; - }; - Field.fromDescriptor = function fromDescriptor(descriptor, edition, nested) { - if (typeof descriptor.length === "number") - descriptor = exports2.DescriptorProto.decode(descriptor); - if (typeof descriptor.number !== "number") - throw Error("missing field id"); - var typeName = descriptor.typeName, fieldType; - if (typeName != null && typeName !== "") { - if (typeof typeName !== "string" || !typeRefRe.test(typeName)) - throw Error("illegal type name: " + typeName); - fieldType = typeName; - } else - fieldType = fromDescriptorType(descriptor.type); - var fieldRule; - switch (descriptor.label) { - // 0 is reserved for errors - case 1: - fieldRule = void 0; - break; - case 2: - fieldRule = "required"; - break; - case 3: - fieldRule = "repeated"; - break; - default: - throw Error("illegal label: " + descriptor.label); - } - var extendee = descriptor.extendee; - if (extendee != null && extendee !== "") { - if (typeof extendee !== "string" || !typeRefRe.test(extendee)) - throw Error("illegal type name: " + extendee); - } else - extendee = void 0; - var field = new Field( - descriptor.name.length ? descriptor.name : "field" + descriptor.number, - descriptor.number, - fieldType, - fieldRule, - extendee - ); - if (!nested) - field._edition = edition; - field.options = fromDescriptorOptions(descriptor.options, exports2.FieldOptions); - if (descriptor.proto3_optional) - field.options.proto3_optional = true; - if (descriptor.defaultValue && descriptor.defaultValue.length) { - var defaultValue = descriptor.defaultValue; - switch (defaultValue) { - case "true": - case "TRUE": - defaultValue = true; - break; - case "false": - case "FALSE": - defaultValue = false; - break; - default: - var match = numberRe.exec(defaultValue); - if (match) - defaultValue = parseInt(defaultValue); - break; - } - field.setOption("default", defaultValue); - } - if (packableDescriptorType(descriptor.type)) { - if (edition === "proto3") { - if (descriptor.options && !descriptor.options.packed) - field.setOption("packed", false); - } else if ((!edition || edition === "proto2") && descriptor.options && descriptor.options.packed) - field.setOption("packed", true); - } - return field; - }; - Field.prototype.toDescriptor = function toDescriptor(edition) { - var descriptor = exports2.FieldDescriptorProto.create({ name: this.name, number: this.id }); - if (this.map) { - descriptor.type = 11; - descriptor.typeName = $protobuf.util.ucFirst(this.name); - descriptor.label = 3; - } else { - switch (descriptor.type = toDescriptorType(this.type, this.resolve().resolvedType, this.delimited)) { - case 10: - // group - case 11: - // type - case 14: - descriptor.typeName = this.resolvedType ? shortname(this.parent, this.resolvedType) : this.type; - break; - } - if (this.rule === "repeated") { - descriptor.label = 3; - } else if (this.required && edition === "proto2") { - descriptor.label = 2; - } else { - descriptor.label = 1; - } - } - descriptor.extendee = this.extensionField ? this.extensionField.parent.fullName : this.extend; - if (this.partOf && this.parent instanceof Type) { - if ((descriptor.oneofIndex = this.parent.oneofsArray.indexOf(this.partOf)) < 0) - throw Error("missing oneof"); - } - if (this.options) { - descriptor.options = toDescriptorOptions(this.options, exports2.FieldOptions); - if (this.options["default"] != null) - descriptor.defaultValue = String(this.options["default"]); - if (this.options.proto3_optional) - descriptor.proto3_optional = true; - } - if (edition === "proto3") { - if (!this.packed) - (descriptor.options || (descriptor.options = exports2.FieldOptions.create())).packed = false; - } else if ((!edition || edition === "proto2") && this.packed) - (descriptor.options || (descriptor.options = exports2.FieldOptions.create())).packed = true; - return descriptor; - }; - var unnamedEnumIndex = 0; - Enum.fromDescriptor = function fromDescriptor(descriptor, edition, nested) { - if (typeof descriptor.length === "number") - descriptor = exports2.EnumDescriptorProto.decode(descriptor); - var values = {}; - if (descriptor.value) - for (var i = 0; i < descriptor.value.length; ++i) { - var name = descriptor.value[i].name, value = descriptor.value[i].number || 0; - values[name && name.length ? name : "NAME" + value] = value; - } - var enm = new Enum( - descriptor.name && descriptor.name.length ? descriptor.name : "Enum" + unnamedEnumIndex++, - values, - fromDescriptorOptions(descriptor.options, exports2.EnumOptions) - ); - if (!nested) - enm._edition = edition; - return enm; - }; - Enum.prototype.toDescriptor = function toDescriptor() { - var values = []; - for (var i = 0, ks = Object.keys(this.values); i < ks.length; ++i) - values.push(exports2.EnumValueDescriptorProto.create({ name: ks[i], number: this.values[ks[i]] })); - return exports2.EnumDescriptorProto.create({ - name: this.name, - value: values, - options: toDescriptorOptions(this.options, exports2.EnumOptions) - }); - }; - var unnamedOneofIndex = 0; - OneOf.fromDescriptor = function fromDescriptor(descriptor) { - if (typeof descriptor.length === "number") - descriptor = exports2.OneofDescriptorProto.decode(descriptor); - return new OneOf( - // unnamedOneOfIndex is global, not per type, because we have no ref to a type here - descriptor.name && descriptor.name.length ? descriptor.name : "oneof" + unnamedOneofIndex++ - // fromDescriptorOptions(descriptor.options, exports.OneofOptions) - only uninterpreted_option - ); - }; - OneOf.prototype.toDescriptor = function toDescriptor() { - return exports2.OneofDescriptorProto.create({ - name: this.name - // options: toDescriptorOptions(this.options, exports.OneofOptions) - only uninterpreted_option - }); - }; - var unnamedServiceIndex = 0; - Service.fromDescriptor = function fromDescriptor(descriptor, edition, nested) { - if (typeof descriptor.length === "number") - descriptor = exports2.ServiceDescriptorProto.decode(descriptor); - var service = new Service(descriptor.name && descriptor.name.length ? descriptor.name : "Service" + unnamedServiceIndex++, fromDescriptorOptions(descriptor.options, exports2.ServiceOptions)); - if (!nested) - service._edition = edition; - if (descriptor.method) - for (var i = 0; i < descriptor.method.length; ++i) - service.add(Method.fromDescriptor(descriptor.method[i])); - return service; - }; - Service.prototype.toDescriptor = function toDescriptor() { - var methods = []; - for (var i = 0; i < this.methodsArray.length; ++i) - methods.push(this._methodsArray[i].toDescriptor()); - return exports2.ServiceDescriptorProto.create({ - name: this.name, - method: methods, - options: toDescriptorOptions(this.options, exports2.ServiceOptions) - }); - }; - var unnamedMethodIndex = 0; - Method.fromDescriptor = function fromDescriptor(descriptor) { - if (typeof descriptor.length === "number") - descriptor = exports2.MethodDescriptorProto.decode(descriptor); - var inputType = descriptor.inputType, outputType = descriptor.outputType; - if (inputType != null && inputType !== "") { - if (typeof inputType !== "string" || !typeRefRe.test(inputType)) - throw Error("illegal type name: " + inputType); - } - if (outputType != null && outputType !== "") { - if (typeof outputType !== "string" || !typeRefRe.test(outputType)) - throw Error("illegal type name: " + outputType); - } - return new Method( - // unnamedMethodIndex is global, not per service, because we have no ref to a service here - descriptor.name && descriptor.name.length ? descriptor.name : "Method" + unnamedMethodIndex++, - "rpc", - inputType, - outputType, - Boolean(descriptor.clientStreaming), - Boolean(descriptor.serverStreaming), - fromDescriptorOptions(descriptor.options, exports2.MethodOptions) - ); - }; - Method.prototype.toDescriptor = function toDescriptor() { - return exports2.MethodDescriptorProto.create({ - name: this.name, - inputType: this.resolvedRequestType ? this.resolvedRequestType.fullName : this.requestType, - outputType: this.resolvedResponseType ? this.resolvedResponseType.fullName : this.responseType, - clientStreaming: this.requestStream, - serverStreaming: this.responseStream, - options: toDescriptorOptions(this.options, exports2.MethodOptions) - }); - }; - function fromDescriptorType(type) { - switch (type) { - // 0 is reserved for errors - case 1: - return "double"; - case 2: - return "float"; - case 3: - return "int64"; - case 4: - return "uint64"; - case 5: - return "int32"; - case 6: - return "fixed64"; - case 7: - return "fixed32"; - case 8: - return "bool"; - case 9: - return "string"; - case 12: - return "bytes"; - case 13: - return "uint32"; - case 15: - return "sfixed32"; - case 16: - return "sfixed64"; - case 17: - return "sint32"; - case 18: - return "sint64"; - } - throw Error("illegal type: " + type); - } - function packableDescriptorType(type) { - switch (type) { - case 1: - // double - case 2: - // float - case 3: - // int64 - case 4: - // uint64 - case 5: - // int32 - case 6: - // fixed64 - case 7: - // fixed32 - case 8: - // bool - case 13: - // uint32 - case 14: - // enum (!) - case 15: - // sfixed32 - case 16: - // sfixed64 - case 17: - // sint32 - case 18: - return true; - } - return false; - } - function toDescriptorType(type, resolvedType, delimited) { - switch (type) { - // 0 is reserved for errors - case "double": - return 1; - case "float": - return 2; - case "int64": - return 3; - case "uint64": - return 4; - case "int32": - return 5; - case "fixed64": - return 6; - case "fixed32": - return 7; - case "bool": - return 8; - case "string": - return 9; - case "bytes": - return 12; - case "uint32": - return 13; - case "sfixed32": - return 15; - case "sfixed64": - return 16; - case "sint32": - return 17; - case "sint64": - return 18; - } - if (resolvedType instanceof Enum) - return 14; - if (resolvedType instanceof Type) - return delimited ? 10 : 11; - throw Error("illegal type: " + type); - } - function fromDescriptorOptionsRecursive(obj, type) { - var val = {}; - for (var i = 0, field, key; i < type.fieldsArray.length; ++i) { - if ((key = (field = type._fieldsArray[i]).name) === "uninterpretedOption") continue; - if (!Object.prototype.hasOwnProperty.call(obj, key)) continue; - var newKey = underScore(key); - if (field.resolvedType instanceof Type) { - val[newKey] = fromDescriptorOptionsRecursive(obj[key], field.resolvedType); - } else if (field.resolvedType instanceof Enum) { - val[newKey] = field.resolvedType.valuesById[obj[key]]; - } else { - val[newKey] = obj[key]; - } - } - return val; - } - function fromDescriptorOptions(options, type) { - if (!options) - return void 0; - return fromDescriptorOptionsRecursive(type.toObject(options), type); - } - function toDescriptorOptionsRecursive(obj, type) { - var val = {}; - var keys = Object.keys(obj); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - var newKey = $protobuf.util.camelCase(key); - if (!Object.prototype.hasOwnProperty.call(type.fields, newKey)) continue; - var field = type.fields[newKey]; - if (field.resolvedType instanceof Type) { - val[newKey] = toDescriptorOptionsRecursive(obj[key], field.resolvedType); - } else { - val[newKey] = obj[key]; - } - if (field.repeated && !Array.isArray(val[newKey])) { - val[newKey] = [val[newKey]]; - } - } - return val; - } - function toDescriptorOptions(options, type) { - if (!options) - return void 0; - return type.fromObject(toDescriptorOptionsRecursive(options, type)); - } - function shortname(from, to) { - var fromPath = from.fullName.split("."), toPath = to.fullName.split("."), i = 0, j = 0, k = toPath.length - 1; - if (!(from instanceof Root) && to instanceof Namespace) - while (i < fromPath.length && j < k && fromPath[i] === toPath[j]) { - var other = to.lookup(fromPath[i++], true); - if (other !== null && other !== to) - break; - ++j; - } - else - for (; i < fromPath.length && j < k && fromPath[i] === toPath[j]; ++i, ++j) ; - return toPath.slice(j).join("."); - } - function underScore(str) { - return str.substring(0, 1) + str.substring(1).replace(/([A-Z])(?=[a-z]|$)/g, function($0, $1) { - return "_" + $1.toLowerCase(); - }); - } - function editionFromDescriptor(fileDescriptor) { - if (fileDescriptor.syntax === "editions") { - switch (fileDescriptor.edition) { - case exports2.Edition.EDITION_2023: - return "2023"; - default: - throw new Error("Unsupported edition " + fileDescriptor.edition); - } - } - if (fileDescriptor.syntax === "proto3") { - return "proto3"; - } - return "proto2"; - } - function editionToDescriptor(edition, fileDescriptor) { - if (!edition) return; - if (edition === "proto2" || edition === "proto3") { - fileDescriptor.syntax = edition; - } else { - fileDescriptor.syntax = "editions"; - switch (edition) { - case "2023": - fileDescriptor.edition = exports2.Edition.EDITION_2023; - break; - default: - throw new Error("Unsupported edition " + edition); - } - } - } - } -}); - -// node_modules/protobufjs/google/protobuf/api.json -var require_api2 = __commonJS({ - "node_modules/protobufjs/google/protobuf/api.json"(exports2, module2) { - module2.exports = { - nested: { - google: { - nested: { - protobuf: { - nested: { - Api: { - fields: { - name: { - type: "string", - id: 1 - }, - methods: { - rule: "repeated", - type: "Method", - id: 2 - }, - options: { - rule: "repeated", - type: "Option", - id: 3 - }, - version: { - type: "string", - id: 4 - }, - sourceContext: { - type: "SourceContext", - id: 5 - }, - mixins: { - rule: "repeated", - type: "Mixin", - id: 6 - }, - syntax: { - type: "Syntax", - id: 7 - } - } - }, - Method: { - fields: { - name: { - type: "string", - id: 1 - }, - requestTypeUrl: { - type: "string", - id: 2 - }, - requestStreaming: { - type: "bool", - id: 3 - }, - responseTypeUrl: { - type: "string", - id: 4 - }, - responseStreaming: { - type: "bool", - id: 5 - }, - options: { - rule: "repeated", - type: "Option", - id: 6 - }, - syntax: { - type: "Syntax", - id: 7 - } - } - }, - Mixin: { - fields: { - name: { - type: "string", - id: 1 - }, - root: { - type: "string", - id: 2 - } - } - }, - SourceContext: { - fields: { - fileName: { - type: "string", - id: 1 - } - } - }, - Option: { - fields: { - name: { - type: "string", - id: 1 - }, - value: { - type: "Any", - id: 2 - } - } - }, - Syntax: { - values: { - SYNTAX_PROTO2: 0, - SYNTAX_PROTO3: 1 - } - } - } - } - } - } - } - }; - } -}); - -// node_modules/protobufjs/google/protobuf/source_context.json -var require_source_context = __commonJS({ - "node_modules/protobufjs/google/protobuf/source_context.json"(exports2, module2) { - module2.exports = { - nested: { - google: { - nested: { - protobuf: { - nested: { - SourceContext: { - fields: { - fileName: { - type: "string", - id: 1 - } - } - } - } - } - } - } - } - }; - } -}); - -// node_modules/protobufjs/google/protobuf/type.json -var require_type2 = __commonJS({ - "node_modules/protobufjs/google/protobuf/type.json"(exports2, module2) { - module2.exports = { - nested: { - google: { - nested: { - protobuf: { - nested: { - Type: { - fields: { - name: { - type: "string", - id: 1 - }, - fields: { - rule: "repeated", - type: "Field", - id: 2 - }, - oneofs: { - rule: "repeated", - type: "string", - id: 3 - }, - options: { - rule: "repeated", - type: "Option", - id: 4 - }, - sourceContext: { - type: "SourceContext", - id: 5 - }, - syntax: { - type: "Syntax", - id: 6 - } - } - }, - Field: { - fields: { - kind: { - type: "Kind", - id: 1 - }, - cardinality: { - type: "Cardinality", - id: 2 - }, - number: { - type: "int32", - id: 3 - }, - name: { - type: "string", - id: 4 - }, - typeUrl: { - type: "string", - id: 6 - }, - oneofIndex: { - type: "int32", - id: 7 - }, - packed: { - type: "bool", - id: 8 - }, - options: { - rule: "repeated", - type: "Option", - id: 9 - }, - jsonName: { - type: "string", - id: 10 - }, - defaultValue: { - type: "string", - id: 11 - } - }, - nested: { - Kind: { - values: { - TYPE_UNKNOWN: 0, - TYPE_DOUBLE: 1, - TYPE_FLOAT: 2, - TYPE_INT64: 3, - TYPE_UINT64: 4, - TYPE_INT32: 5, - TYPE_FIXED64: 6, - TYPE_FIXED32: 7, - TYPE_BOOL: 8, - TYPE_STRING: 9, - TYPE_GROUP: 10, - TYPE_MESSAGE: 11, - TYPE_BYTES: 12, - TYPE_UINT32: 13, - TYPE_ENUM: 14, - TYPE_SFIXED32: 15, - TYPE_SFIXED64: 16, - TYPE_SINT32: 17, - TYPE_SINT64: 18 - } - }, - Cardinality: { - values: { - CARDINALITY_UNKNOWN: 0, - CARDINALITY_OPTIONAL: 1, - CARDINALITY_REQUIRED: 2, - CARDINALITY_REPEATED: 3 - } - } - } - }, - Enum: { - fields: { - name: { - type: "string", - id: 1 - }, - enumvalue: { - rule: "repeated", - type: "EnumValue", - id: 2 - }, - options: { - rule: "repeated", - type: "Option", - id: 3 - }, - sourceContext: { - type: "SourceContext", - id: 4 - }, - syntax: { - type: "Syntax", - id: 5 - } - } - }, - EnumValue: { - fields: { - name: { - type: "string", - id: 1 - }, - number: { - type: "int32", - id: 2 - }, - options: { - rule: "repeated", - type: "Option", - id: 3 - } - } - }, - Option: { - fields: { - name: { - type: "string", - id: 1 - }, - value: { - type: "Any", - id: 2 - } - } - }, - Syntax: { - values: { - SYNTAX_PROTO2: 0, - SYNTAX_PROTO3: 1 - } - }, - Any: { - fields: { - type_url: { - type: "string", - id: 1 - }, - value: { - type: "bytes", - id: 2 - } - } - }, - SourceContext: { - fields: { - fileName: { - type: "string", - id: 1 - } - } - } - } - } - } - } - } - }; - } -}); - -// node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/util.js -var require_util11 = __commonJS({ - "node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/util.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.addCommonProtos = exports2.loadProtosWithOptionsSync = exports2.loadProtosWithOptions = void 0; - var fs3 = require("fs"); - var path = require("path"); - var Protobuf = require_protobufjs(); - function addIncludePathResolver(root, includePaths) { - const originalResolvePath = root.resolvePath; - root.resolvePath = (origin, target) => { - if (path.isAbsolute(target)) { - return target; - } - for (const directory of includePaths) { - const fullPath = path.join(directory, target); - try { - fs3.accessSync(fullPath, fs3.constants.R_OK); - return fullPath; - } catch (err) { - continue; - } - } - process.emitWarning(`${target} not found in any of the include paths ${includePaths}`); - return originalResolvePath(origin, target); - }; - } - async function loadProtosWithOptions(filename, options) { - const root = new Protobuf.Root(); - options = options || {}; - if (!!options.includeDirs) { - if (!Array.isArray(options.includeDirs)) { - return Promise.reject(new Error("The includeDirs option must be an array")); - } - addIncludePathResolver(root, options.includeDirs); - } - const loadedRoot = await root.load(filename, options); - loadedRoot.resolveAll(); - return loadedRoot; - } - exports2.loadProtosWithOptions = loadProtosWithOptions; - function loadProtosWithOptionsSync(filename, options) { - const root = new Protobuf.Root(); - options = options || {}; - if (!!options.includeDirs) { - if (!Array.isArray(options.includeDirs)) { - throw new Error("The includeDirs option must be an array"); - } - addIncludePathResolver(root, options.includeDirs); - } - const loadedRoot = root.loadSync(filename, options); - loadedRoot.resolveAll(); - return loadedRoot; - } - exports2.loadProtosWithOptionsSync = loadProtosWithOptionsSync; - function addCommonProtos() { - const apiDescriptor = require_api2(); - const descriptorDescriptor = require_descriptor(); - const sourceContextDescriptor = require_source_context(); - const typeDescriptor = require_type2(); - Protobuf.common("api", apiDescriptor.nested.google.nested.protobuf.nested); - Protobuf.common("descriptor", descriptorDescriptor.nested.google.nested.protobuf.nested); - Protobuf.common("source_context", sourceContextDescriptor.nested.google.nested.protobuf.nested); - Protobuf.common("type", typeDescriptor.nested.google.nested.protobuf.nested); - } - exports2.addCommonProtos = addCommonProtos; - } -}); - -// node_modules/long/umd/index.js -var require_umd = __commonJS({ - "node_modules/long/umd/index.js"(exports2, module2) { - (function(global2, factory) { - function unwrapDefault(exports3) { - return "default" in exports3 ? exports3.default : exports3; - } - if (typeof define === "function" && define.amd) { - define([], function() { - var exports3 = {}; - factory(exports3); - return unwrapDefault(exports3); - }); - } else if (typeof exports2 === "object") { - factory(exports2); - if (typeof module2 === "object") module2.exports = unwrapDefault(exports2); - } else { - (function() { - var exports3 = {}; - factory(exports3); - global2.Long = unwrapDefault(exports3); - })(); - } - })( - typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : exports2, - function(_exports) { - "use strict"; - Object.defineProperty(_exports, "__esModule", { - value: true - }); - _exports.default = void 0; - var wasm = null; - try { - wasm = new WebAssembly.Instance( - new WebAssembly.Module( - new Uint8Array([ - // \0asm - 0, - 97, - 115, - 109, - // version 1 - 1, - 0, - 0, - 0, - // section "type" - 1, - 13, - 2, - // 0, () => i32 - 96, - 0, - 1, - 127, - // 1, (i32, i32, i32, i32) => i32 - 96, - 4, - 127, - 127, - 127, - 127, - 1, - 127, - // section "function" - 3, - 7, - 6, - // 0, type 0 - 0, - // 1, type 1 - 1, - // 2, type 1 - 1, - // 3, type 1 - 1, - // 4, type 1 - 1, - // 5, type 1 - 1, - // section "global" - 6, - 6, - 1, - // 0, "high", mutable i32 - 127, - 1, - 65, - 0, - 11, - // section "export" - 7, - 50, - 6, - // 0, "mul" - 3, - 109, - 117, - 108, - 0, - 1, - // 1, "div_s" - 5, - 100, - 105, - 118, - 95, - 115, - 0, - 2, - // 2, "div_u" - 5, - 100, - 105, - 118, - 95, - 117, - 0, - 3, - // 3, "rem_s" - 5, - 114, - 101, - 109, - 95, - 115, - 0, - 4, - // 4, "rem_u" - 5, - 114, - 101, - 109, - 95, - 117, - 0, - 5, - // 5, "get_high" - 8, - 103, - 101, - 116, - 95, - 104, - 105, - 103, - 104, - 0, - 0, - // section "code" - 10, - 191, - 1, - 6, - // 0, "get_high" - 4, - 0, - 35, - 0, - 11, - // 1, "mul" - 36, - 1, - 1, - 126, - 32, - 0, - 173, - 32, - 1, - 173, - 66, - 32, - 134, - 132, - 32, - 2, - 173, - 32, - 3, - 173, - 66, - 32, - 134, - 132, - 126, - 34, - 4, - 66, - 32, - 135, - 167, - 36, - 0, - 32, - 4, - 167, - 11, - // 2, "div_s" - 36, - 1, - 1, - 126, - 32, - 0, - 173, - 32, - 1, - 173, - 66, - 32, - 134, - 132, - 32, - 2, - 173, - 32, - 3, - 173, - 66, - 32, - 134, - 132, - 127, - 34, - 4, - 66, - 32, - 135, - 167, - 36, - 0, - 32, - 4, - 167, - 11, - // 3, "div_u" - 36, - 1, - 1, - 126, - 32, - 0, - 173, - 32, - 1, - 173, - 66, - 32, - 134, - 132, - 32, - 2, - 173, - 32, - 3, - 173, - 66, - 32, - 134, - 132, - 128, - 34, - 4, - 66, - 32, - 135, - 167, - 36, - 0, - 32, - 4, - 167, - 11, - // 4, "rem_s" - 36, - 1, - 1, - 126, - 32, - 0, - 173, - 32, - 1, - 173, - 66, - 32, - 134, - 132, - 32, - 2, - 173, - 32, - 3, - 173, - 66, - 32, - 134, - 132, - 129, - 34, - 4, - 66, - 32, - 135, - 167, - 36, - 0, - 32, - 4, - 167, - 11, - // 5, "rem_u" - 36, - 1, - 1, - 126, - 32, - 0, - 173, - 32, - 1, - 173, - 66, - 32, - 134, - 132, - 32, - 2, - 173, - 32, - 3, - 173, - 66, - 32, - 134, - 132, - 130, - 34, - 4, - 66, - 32, - 135, - 167, - 36, - 0, - 32, - 4, - 167, - 11 - ]) - ), - {} - ).exports; - } catch { - } - function Long(low, high, unsigned) { - this.low = low | 0; - this.high = high | 0; - this.unsigned = !!unsigned; - } - Long.prototype.__isLong__; - Object.defineProperty(Long.prototype, "__isLong__", { - value: true - }); - function isLong(obj) { - return (obj && obj["__isLong__"]) === true; - } - function ctz32(value) { - var c = Math.clz32(value & -value); - return value ? 31 - c : c; - } - Long.isLong = isLong; - var INT_CACHE = {}; - var UINT_CACHE = {}; - function fromInt(value, unsigned) { - var obj, cachedObj, cache; - if (unsigned) { - value >>>= 0; - if (cache = 0 <= value && value < 256) { - cachedObj = UINT_CACHE[value]; - if (cachedObj) return cachedObj; - } - obj = fromBits(value, 0, true); - if (cache) UINT_CACHE[value] = obj; - return obj; - } else { - value |= 0; - if (cache = -128 <= value && value < 128) { - cachedObj = INT_CACHE[value]; - if (cachedObj) return cachedObj; - } - obj = fromBits(value, value < 0 ? -1 : 0, false); - if (cache) INT_CACHE[value] = obj; - return obj; - } - } - Long.fromInt = fromInt; - function fromNumber(value, unsigned) { - if (isNaN(value)) return unsigned ? UZERO : ZERO; - if (unsigned) { - if (value < 0) return UZERO; - if (value >= TWO_PWR_64_DBL) return MAX_UNSIGNED_VALUE; - } else { - if (value <= -TWO_PWR_63_DBL) return MIN_VALUE; - if (value + 1 >= TWO_PWR_63_DBL) return MAX_VALUE; - } - if (value < 0) return fromNumber(-value, unsigned).neg(); - return fromBits( - value % TWO_PWR_32_DBL | 0, - value / TWO_PWR_32_DBL | 0, - unsigned - ); - } - Long.fromNumber = fromNumber; - function fromBits(lowBits, highBits, unsigned) { - return new Long(lowBits, highBits, unsigned); - } - Long.fromBits = fromBits; - var pow_dbl = Math.pow; - function fromString(str, unsigned, radix) { - if (str.length === 0) throw Error("empty string"); - if (typeof unsigned === "number") { - radix = unsigned; - unsigned = false; - } else { - unsigned = !!unsigned; - } - if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity") - return unsigned ? UZERO : ZERO; - radix = radix || 10; - if (radix < 2 || 36 < radix) throw RangeError("radix"); - var p; - if ((p = str.indexOf("-")) > 0) throw Error("interior hyphen"); - else if (p === 0) { - return fromString(str.substring(1), unsigned, radix).neg(); - } - var radixToPower = fromNumber(pow_dbl(radix, 8)); - var result = ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = fromNumber(pow_dbl(radix, size)); - result = result.mul(power).add(fromNumber(value)); - } else { - result = result.mul(radixToPower); - result = result.add(fromNumber(value)); - } - } - result.unsigned = unsigned; - return result; - } - Long.fromString = fromString; - function fromValue(val, unsigned) { - if (typeof val === "number") return fromNumber(val, unsigned); - if (typeof val === "string") return fromString(val, unsigned); - return fromBits( - val.low, - val.high, - typeof unsigned === "boolean" ? unsigned : val.unsigned - ); - } - Long.fromValue = fromValue; - var TWO_PWR_16_DBL = 1 << 16; - var TWO_PWR_24_DBL = 1 << 24; - var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; - var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; - var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; - var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL); - var ZERO = fromInt(0); - Long.ZERO = ZERO; - var UZERO = fromInt(0, true); - Long.UZERO = UZERO; - var ONE = fromInt(1); - Long.ONE = ONE; - var UONE = fromInt(1, true); - Long.UONE = UONE; - var NEG_ONE = fromInt(-1); - Long.NEG_ONE = NEG_ONE; - var MAX_VALUE = fromBits(4294967295 | 0, 2147483647 | 0, false); - Long.MAX_VALUE = MAX_VALUE; - var MAX_UNSIGNED_VALUE = fromBits(4294967295 | 0, 4294967295 | 0, true); - Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE; - var MIN_VALUE = fromBits(0, 2147483648 | 0, false); - Long.MIN_VALUE = MIN_VALUE; - var LongPrototype = Long.prototype; - LongPrototype.toInt = function toInt() { - return this.unsigned ? this.low >>> 0 : this.low; - }; - LongPrototype.toNumber = function toNumber() { - if (this.unsigned) - return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); - return this.high * TWO_PWR_32_DBL + (this.low >>> 0); - }; - LongPrototype.toString = function toString(radix) { - radix = radix || 10; - if (radix < 2 || 36 < radix) throw RangeError("radix"); - if (this.isZero()) return "0"; - if (this.isNegative()) { - if (this.eq(MIN_VALUE)) { - var radixLong = fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this); - return div.toString(radix) + rem1.toInt().toString(radix); - } else return "-" + this.neg().toString(radix); - } - var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned), rem = this; - var result = ""; - while (true) { - var remDiv = rem.div(radixToPower), intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0, digits = intval.toString(radix); - rem = remDiv; - if (rem.isZero()) return digits + result; - else { - while (digits.length < 6) digits = "0" + digits; - result = "" + digits + result; - } - } - }; - LongPrototype.getHighBits = function getHighBits() { - return this.high; - }; - LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() { - return this.high >>> 0; - }; - LongPrototype.getLowBits = function getLowBits() { - return this.low; - }; - LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() { - return this.low >>> 0; - }; - LongPrototype.getNumBitsAbs = function getNumBitsAbs() { - if (this.isNegative()) - return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); - var val = this.high != 0 ? this.high : this.low; - for (var bit = 31; bit > 0; bit--) if ((val & 1 << bit) != 0) break; - return this.high != 0 ? bit + 33 : bit + 1; - }; - LongPrototype.isSafeInteger = function isSafeInteger() { - var top11Bits = this.high >> 21; - if (!top11Bits) return true; - if (this.unsigned) return false; - return top11Bits === -1 && !(this.low === 0 && this.high === -2097152); - }; - LongPrototype.isZero = function isZero() { - return this.high === 0 && this.low === 0; - }; - LongPrototype.eqz = LongPrototype.isZero; - LongPrototype.isNegative = function isNegative() { - return !this.unsigned && this.high < 0; - }; - LongPrototype.isPositive = function isPositive() { - return this.unsigned || this.high >= 0; - }; - LongPrototype.isOdd = function isOdd() { - return (this.low & 1) === 1; - }; - LongPrototype.isEven = function isEven() { - return (this.low & 1) === 0; - }; - LongPrototype.equals = function equals(other) { - if (!isLong(other)) other = fromValue(other); - if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) - return false; - return this.high === other.high && this.low === other.low; - }; - LongPrototype.eq = LongPrototype.equals; - LongPrototype.notEquals = function notEquals(other) { - return !this.eq( - /* validates */ - other - ); - }; - LongPrototype.neq = LongPrototype.notEquals; - LongPrototype.ne = LongPrototype.notEquals; - LongPrototype.lessThan = function lessThan(other) { - return this.comp( - /* validates */ - other - ) < 0; - }; - LongPrototype.lt = LongPrototype.lessThan; - LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) { - return this.comp( - /* validates */ - other - ) <= 0; - }; - LongPrototype.lte = LongPrototype.lessThanOrEqual; - LongPrototype.le = LongPrototype.lessThanOrEqual; - LongPrototype.greaterThan = function greaterThan(other) { - return this.comp( - /* validates */ - other - ) > 0; - }; - LongPrototype.gt = LongPrototype.greaterThan; - LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) { - return this.comp( - /* validates */ - other - ) >= 0; - }; - LongPrototype.gte = LongPrototype.greaterThanOrEqual; - LongPrototype.ge = LongPrototype.greaterThanOrEqual; - LongPrototype.compare = function compare(other) { - if (!isLong(other)) other = fromValue(other); - if (this.eq(other)) return 0; - var thisNeg = this.isNegative(), otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) return -1; - if (!thisNeg && otherNeg) return 1; - if (!this.unsigned) return this.sub(other).isNegative() ? -1 : 1; - return other.high >>> 0 > this.high >>> 0 || other.high === this.high && other.low >>> 0 > this.low >>> 0 ? -1 : 1; - }; - LongPrototype.comp = LongPrototype.compare; - LongPrototype.negate = function negate() { - if (!this.unsigned && this.eq(MIN_VALUE)) return MIN_VALUE; - return this.not().add(ONE); - }; - LongPrototype.neg = LongPrototype.negate; - LongPrototype.add = function add(addend) { - if (!isLong(addend)) addend = fromValue(addend); - var a48 = this.high >>> 16; - var a32 = this.high & 65535; - var a16 = this.low >>> 16; - var a00 = this.low & 65535; - var b48 = addend.high >>> 16; - var b32 = addend.high & 65535; - var b16 = addend.low >>> 16; - var b00 = addend.low & 65535; - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 65535; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 65535; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 65535; - c48 += a48 + b48; - c48 &= 65535; - return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned); - }; - LongPrototype.subtract = function subtract(subtrahend) { - if (!isLong(subtrahend)) subtrahend = fromValue(subtrahend); - return this.add(subtrahend.neg()); - }; - LongPrototype.sub = LongPrototype.subtract; - LongPrototype.multiply = function multiply(multiplier) { - if (this.isZero()) return this; - if (!isLong(multiplier)) multiplier = fromValue(multiplier); - if (wasm) { - var low = wasm["mul"]( - this.low, - this.high, - multiplier.low, - multiplier.high - ); - return fromBits(low, wasm["get_high"](), this.unsigned); - } - if (multiplier.isZero()) return this.unsigned ? UZERO : ZERO; - if (this.eq(MIN_VALUE)) return multiplier.isOdd() ? MIN_VALUE : ZERO; - if (multiplier.eq(MIN_VALUE)) return this.isOdd() ? MIN_VALUE : ZERO; - if (this.isNegative()) { - if (multiplier.isNegative()) return this.neg().mul(multiplier.neg()); - else return this.neg().mul(multiplier).neg(); - } else if (multiplier.isNegative()) - return this.mul(multiplier.neg()).neg(); - if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24)) - return fromNumber( - this.toNumber() * multiplier.toNumber(), - this.unsigned - ); - var a48 = this.high >>> 16; - var a32 = this.high & 65535; - var a16 = this.low >>> 16; - var a00 = this.low & 65535; - var b48 = multiplier.high >>> 16; - var b32 = multiplier.high & 65535; - var b16 = multiplier.low >>> 16; - var b00 = multiplier.low & 65535; - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 65535; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 65535; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 65535; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 65535; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 65535; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 65535; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 65535; - return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned); - }; - LongPrototype.mul = LongPrototype.multiply; - LongPrototype.divide = function divide(divisor) { - if (!isLong(divisor)) divisor = fromValue(divisor); - if (divisor.isZero()) throw Error("division by zero"); - if (wasm) { - if (!this.unsigned && this.high === -2147483648 && divisor.low === -1 && divisor.high === -1) { - return this; - } - var low = (this.unsigned ? wasm["div_u"] : wasm["div_s"])( - this.low, - this.high, - divisor.low, - divisor.high - ); - return fromBits(low, wasm["get_high"](), this.unsigned); - } - if (this.isZero()) return this.unsigned ? UZERO : ZERO; - var approx, rem, res; - if (!this.unsigned) { - if (this.eq(MIN_VALUE)) { - if (divisor.eq(ONE) || divisor.eq(NEG_ONE)) - return MIN_VALUE; - else if (divisor.eq(MIN_VALUE)) return ONE; - else { - var halfThis = this.shr(1); - approx = halfThis.div(divisor).shl(1); - if (approx.eq(ZERO)) { - return divisor.isNegative() ? ONE : NEG_ONE; - } else { - rem = this.sub(divisor.mul(approx)); - res = approx.add(rem.div(divisor)); - return res; - } - } - } else if (divisor.eq(MIN_VALUE)) return this.unsigned ? UZERO : ZERO; - if (this.isNegative()) { - if (divisor.isNegative()) return this.neg().div(divisor.neg()); - return this.neg().div(divisor).neg(); - } else if (divisor.isNegative()) return this.div(divisor.neg()).neg(); - res = ZERO; - } else { - if (!divisor.unsigned) divisor = divisor.toUnsigned(); - if (divisor.gt(this)) return UZERO; - if (divisor.gt(this.shru(1))) - return UONE; - res = UZERO; - } - rem = this; - while (rem.gte(divisor)) { - approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); - var log2 = Math.ceil(Math.log(approx) / Math.LN2), delta = log2 <= 48 ? 1 : pow_dbl(2, log2 - 48), approxRes = fromNumber(approx), approxRem = approxRes.mul(divisor); - while (approxRem.isNegative() || approxRem.gt(rem)) { - approx -= delta; - approxRes = fromNumber(approx, this.unsigned); - approxRem = approxRes.mul(divisor); - } - if (approxRes.isZero()) approxRes = ONE; - res = res.add(approxRes); - rem = rem.sub(approxRem); - } - return res; - }; - LongPrototype.div = LongPrototype.divide; - LongPrototype.modulo = function modulo(divisor) { - if (!isLong(divisor)) divisor = fromValue(divisor); - if (wasm) { - var low = (this.unsigned ? wasm["rem_u"] : wasm["rem_s"])( - this.low, - this.high, - divisor.low, - divisor.high - ); - return fromBits(low, wasm["get_high"](), this.unsigned); - } - return this.sub(this.div(divisor).mul(divisor)); - }; - LongPrototype.mod = LongPrototype.modulo; - LongPrototype.rem = LongPrototype.modulo; - LongPrototype.not = function not() { - return fromBits(~this.low, ~this.high, this.unsigned); - }; - LongPrototype.countLeadingZeros = function countLeadingZeros() { - return this.high ? Math.clz32(this.high) : Math.clz32(this.low) + 32; - }; - LongPrototype.clz = LongPrototype.countLeadingZeros; - LongPrototype.countTrailingZeros = function countTrailingZeros() { - return this.low ? ctz32(this.low) : ctz32(this.high) + 32; - }; - LongPrototype.ctz = LongPrototype.countTrailingZeros; - LongPrototype.and = function and(other) { - if (!isLong(other)) other = fromValue(other); - return fromBits( - this.low & other.low, - this.high & other.high, - this.unsigned - ); - }; - LongPrototype.or = function or(other) { - if (!isLong(other)) other = fromValue(other); - return fromBits( - this.low | other.low, - this.high | other.high, - this.unsigned - ); - }; - LongPrototype.xor = function xor(other) { - if (!isLong(other)) other = fromValue(other); - return fromBits( - this.low ^ other.low, - this.high ^ other.high, - this.unsigned - ); - }; - LongPrototype.shiftLeft = function shiftLeft(numBits) { - if (isLong(numBits)) numBits = numBits.toInt(); - if ((numBits &= 63) === 0) return this; - else if (numBits < 32) - return fromBits( - this.low << numBits, - this.high << numBits | this.low >>> 32 - numBits, - this.unsigned - ); - else return fromBits(0, this.low << numBits - 32, this.unsigned); - }; - LongPrototype.shl = LongPrototype.shiftLeft; - LongPrototype.shiftRight = function shiftRight(numBits) { - if (isLong(numBits)) numBits = numBits.toInt(); - if ((numBits &= 63) === 0) return this; - else if (numBits < 32) - return fromBits( - this.low >>> numBits | this.high << 32 - numBits, - this.high >> numBits, - this.unsigned - ); - else - return fromBits( - this.high >> numBits - 32, - this.high >= 0 ? 0 : -1, - this.unsigned - ); - }; - LongPrototype.shr = LongPrototype.shiftRight; - LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) { - if (isLong(numBits)) numBits = numBits.toInt(); - if ((numBits &= 63) === 0) return this; - if (numBits < 32) - return fromBits( - this.low >>> numBits | this.high << 32 - numBits, - this.high >>> numBits, - this.unsigned - ); - if (numBits === 32) return fromBits(this.high, 0, this.unsigned); - return fromBits(this.high >>> numBits - 32, 0, this.unsigned); - }; - LongPrototype.shru = LongPrototype.shiftRightUnsigned; - LongPrototype.shr_u = LongPrototype.shiftRightUnsigned; - LongPrototype.rotateLeft = function rotateLeft(numBits) { - var b; - if (isLong(numBits)) numBits = numBits.toInt(); - if ((numBits &= 63) === 0) return this; - if (numBits === 32) return fromBits(this.high, this.low, this.unsigned); - if (numBits < 32) { - b = 32 - numBits; - return fromBits( - this.low << numBits | this.high >>> b, - this.high << numBits | this.low >>> b, - this.unsigned - ); - } - numBits -= 32; - b = 32 - numBits; - return fromBits( - this.high << numBits | this.low >>> b, - this.low << numBits | this.high >>> b, - this.unsigned - ); - }; - LongPrototype.rotl = LongPrototype.rotateLeft; - LongPrototype.rotateRight = function rotateRight(numBits) { - var b; - if (isLong(numBits)) numBits = numBits.toInt(); - if ((numBits &= 63) === 0) return this; - if (numBits === 32) return fromBits(this.high, this.low, this.unsigned); - if (numBits < 32) { - b = 32 - numBits; - return fromBits( - this.high << b | this.low >>> numBits, - this.low << b | this.high >>> numBits, - this.unsigned - ); - } - numBits -= 32; - b = 32 - numBits; - return fromBits( - this.low << b | this.high >>> numBits, - this.high << b | this.low >>> numBits, - this.unsigned - ); - }; - LongPrototype.rotr = LongPrototype.rotateRight; - LongPrototype.toSigned = function toSigned() { - if (!this.unsigned) return this; - return fromBits(this.low, this.high, false); - }; - LongPrototype.toUnsigned = function toUnsigned() { - if (this.unsigned) return this; - return fromBits(this.low, this.high, true); - }; - LongPrototype.toBytes = function toBytes(le) { - return le ? this.toBytesLE() : this.toBytesBE(); - }; - LongPrototype.toBytesLE = function toBytesLE() { - var hi = this.high, lo = this.low; - return [ - lo & 255, - lo >>> 8 & 255, - lo >>> 16 & 255, - lo >>> 24, - hi & 255, - hi >>> 8 & 255, - hi >>> 16 & 255, - hi >>> 24 - ]; - }; - LongPrototype.toBytesBE = function toBytesBE() { - var hi = this.high, lo = this.low; - return [ - hi >>> 24, - hi >>> 16 & 255, - hi >>> 8 & 255, - hi & 255, - lo >>> 24, - lo >>> 16 & 255, - lo >>> 8 & 255, - lo & 255 - ]; - }; - Long.fromBytes = function fromBytes(bytes, unsigned, le) { - return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); - }; - Long.fromBytesLE = function fromBytesLE(bytes, unsigned) { - return new Long( - bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24, - bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24, - unsigned - ); - }; - Long.fromBytesBE = function fromBytesBE(bytes, unsigned) { - return new Long( - bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7], - bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], - unsigned - ); - }; - if (typeof BigInt === "function") { - Long.fromBigInt = function fromBigInt2(value, unsigned) { - var lowBits = Number(BigInt.asIntN(32, value)); - var highBits = Number(BigInt.asIntN(32, value >> BigInt(32))); - return fromBits(lowBits, highBits, unsigned); - }; - Long.fromValue = function fromValueWithBigInt(value, unsigned) { - if (typeof value === "bigint") return fromBigInt(value, unsigned); - return fromValue(value, unsigned); - }; - LongPrototype.toBigInt = function toBigInt() { - var lowBigInt = BigInt(this.low >>> 0); - var highBigInt = BigInt(this.unsigned ? this.high >>> 0 : this.high); - return highBigInt << BigInt(32) | lowBigInt; - }; - } - var _default = _exports.default = Long; - } - ); - } -}); - -// node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/index.js -var require_src3 = __commonJS({ - "node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.loadFileDescriptorSetFromObject = exports2.loadFileDescriptorSetFromBuffer = exports2.fromJSON = exports2.loadSync = exports2.load = exports2.IdempotencyLevel = exports2.isAnyExtension = exports2.Long = void 0; - var camelCase = require_lodash(); - var Protobuf = require_protobufjs(); - var descriptor = require_descriptor2(); - var util_1 = require_util11(); - var Long = require_umd(); - exports2.Long = Long; - function isAnyExtension(obj) { - return "@type" in obj && typeof obj["@type"] === "string"; - } - exports2.isAnyExtension = isAnyExtension; - var IdempotencyLevel; - (function(IdempotencyLevel2) { - IdempotencyLevel2["IDEMPOTENCY_UNKNOWN"] = "IDEMPOTENCY_UNKNOWN"; - IdempotencyLevel2["NO_SIDE_EFFECTS"] = "NO_SIDE_EFFECTS"; - IdempotencyLevel2["IDEMPOTENT"] = "IDEMPOTENT"; - })(IdempotencyLevel = exports2.IdempotencyLevel || (exports2.IdempotencyLevel = {})); - var descriptorOptions = { - longs: String, - enums: String, - bytes: String, - defaults: true, - oneofs: true, - json: true - }; - function joinName(baseName, name) { - if (baseName === "") { - return name; - } else { - return baseName + "." + name; - } - } - function isHandledReflectionObject(obj) { - return obj instanceof Protobuf.Service || obj instanceof Protobuf.Type || obj instanceof Protobuf.Enum; - } - function isNamespaceBase(obj) { - return obj instanceof Protobuf.Namespace || obj instanceof Protobuf.Root; - } - function getAllHandledReflectionObjects(obj, parentName) { - const objName = joinName(parentName, obj.name); - if (isHandledReflectionObject(obj)) { - return [[objName, obj]]; - } else { - if (isNamespaceBase(obj) && typeof obj.nested !== "undefined") { - return Object.keys(obj.nested).map((name) => { - return getAllHandledReflectionObjects(obj.nested[name], objName); - }).reduce((accumulator, currentValue) => accumulator.concat(currentValue), []); - } - } - return []; - } - function createDeserializer(cls, options) { - return function deserialize(argBuf) { - return cls.toObject(cls.decode(argBuf), options); - }; - } - function createSerializer(cls) { - return function serialize(arg) { - if (Array.isArray(arg)) { - throw new Error(`Failed to serialize message: expected object with ${cls.name} structure, got array instead`); - } - const message = cls.fromObject(arg); - return cls.encode(message).finish(); - }; - } - function mapMethodOptions(options) { - return (options || []).reduce((obj, item) => { - for (const [key, value] of Object.entries(item)) { - switch (key) { - case "uninterpreted_option": - obj.uninterpreted_option.push(item.uninterpreted_option); - break; - default: - obj[key] = value; - } - } - return obj; - }, { - deprecated: false, - idempotency_level: IdempotencyLevel.IDEMPOTENCY_UNKNOWN, - uninterpreted_option: [] - }); - } - function createMethodDefinition(method, serviceName, options, fileDescriptors) { - const requestType = method.resolvedRequestType; - const responseType = method.resolvedResponseType; - return { - path: "/" + serviceName + "/" + method.name, - requestStream: !!method.requestStream, - responseStream: !!method.responseStream, - requestSerialize: createSerializer(requestType), - requestDeserialize: createDeserializer(requestType, options), - responseSerialize: createSerializer(responseType), - responseDeserialize: createDeserializer(responseType, options), - // TODO(murgatroid99): Find a better way to handle this - originalName: camelCase(method.name), - requestType: createMessageDefinition(requestType, options, fileDescriptors), - responseType: createMessageDefinition(responseType, options, fileDescriptors), - options: mapMethodOptions(method.parsedOptions) - }; - } - function createServiceDefinition(service, name, options, fileDescriptors) { - const def = {}; - for (const method of service.methodsArray) { - def[method.name] = createMethodDefinition(method, name, options, fileDescriptors); - } - return def; - } - function createMessageDefinition(message, options, fileDescriptors) { - const messageDescriptor = message.toDescriptor("proto3"); - return { - format: "Protocol Buffer 3 DescriptorProto", - type: messageDescriptor.$type.toObject(messageDescriptor, descriptorOptions), - fileDescriptorProtos: fileDescriptors, - serialize: createSerializer(message), - deserialize: createDeserializer(message, options) - }; - } - function createEnumDefinition(enumType, fileDescriptors) { - const enumDescriptor = enumType.toDescriptor("proto3"); - return { - format: "Protocol Buffer 3 EnumDescriptorProto", - type: enumDescriptor.$type.toObject(enumDescriptor, descriptorOptions), - fileDescriptorProtos: fileDescriptors - }; - } - function createDefinition(obj, name, options, fileDescriptors) { - if (obj instanceof Protobuf.Service) { - return createServiceDefinition(obj, name, options, fileDescriptors); - } else if (obj instanceof Protobuf.Type) { - return createMessageDefinition(obj, options, fileDescriptors); - } else if (obj instanceof Protobuf.Enum) { - return createEnumDefinition(obj, fileDescriptors); - } else { - throw new Error("Type mismatch in reflection object handling"); - } - } - function createPackageDefinition(root, options) { - const def = {}; - root.resolveAll(); - const descriptorList = root.toDescriptor("proto3").file; - const bufferList = descriptorList.map((value) => Buffer.from(descriptor.FileDescriptorProto.encode(value).finish())); - for (const [name, obj] of getAllHandledReflectionObjects(root, "")) { - def[name] = createDefinition(obj, name, options, bufferList); - } - return def; - } - function createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options) { - options = options || {}; - const root = Protobuf.Root.fromDescriptor(decodedDescriptorSet); - root.resolveAll(); - return createPackageDefinition(root, options); - } - function load(filename, options) { - return (0, util_1.loadProtosWithOptions)(filename, options).then((loadedRoot) => { - return createPackageDefinition(loadedRoot, options); - }); - } - exports2.load = load; - function loadSync(filename, options) { - const loadedRoot = (0, util_1.loadProtosWithOptionsSync)(filename, options); - return createPackageDefinition(loadedRoot, options); - } - exports2.loadSync = loadSync; - function fromJSON(json, options) { - options = options || {}; - const loadedRoot = Protobuf.Root.fromJSON(json); - loadedRoot.resolveAll(); - return createPackageDefinition(loadedRoot, options); - } - exports2.fromJSON = fromJSON; - function loadFileDescriptorSetFromBuffer(descriptorSet, options) { - const decodedDescriptorSet = descriptor.FileDescriptorSet.decode(descriptorSet); - return createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options); - } - exports2.loadFileDescriptorSetFromBuffer = loadFileDescriptorSetFromBuffer; - function loadFileDescriptorSetFromObject(descriptorSet, options) { - const decodedDescriptorSet = descriptor.FileDescriptorSet.fromObject(descriptorSet); - return createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options); - } - exports2.loadFileDescriptorSetFromObject = loadFileDescriptorSetFromObject; - (0, util_1.addCommonProtos)(); - } -}); - -// node_modules/@grpc/grpc-js/build/src/channelz.js -var require_channelz = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/channelz.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.registerChannelzSocket = exports2.registerChannelzServer = exports2.registerChannelzSubchannel = exports2.registerChannelzChannel = exports2.ChannelzCallTrackerStub = exports2.ChannelzCallTracker = exports2.ChannelzChildrenTrackerStub = exports2.ChannelzChildrenTracker = exports2.ChannelzTrace = exports2.ChannelzTraceStub = void 0; - exports2.unregisterChannelzRef = unregisterChannelzRef; - exports2.getChannelzHandlers = getChannelzHandlers; - exports2.getChannelzServiceDefinition = getChannelzServiceDefinition; - exports2.setup = setup; - var net_1 = require("net"); - var ordered_map_1 = require_cjs(); - var connectivity_state_1 = require_connectivity_state(); - var constants_1 = require_constants7(); - var subchannel_address_1 = require_subchannel_address(); - var admin_1 = require_admin(); - var make_client_1 = require_make_client(); - function channelRefToMessage(ref) { - return { - channel_id: ref.id, - name: ref.name - }; - } - function subchannelRefToMessage(ref) { - return { - subchannel_id: ref.id, - name: ref.name - }; - } - function serverRefToMessage(ref) { - return { - server_id: ref.id - }; - } - function socketRefToMessage(ref) { - return { - socket_id: ref.id, - name: ref.name - }; - } - var TARGET_RETAINED_TRACES = 32; - var DEFAULT_MAX_RESULTS = 100; - var ChannelzTraceStub = class { - constructor() { - this.events = []; - this.creationTimestamp = /* @__PURE__ */ new Date(); - this.eventsLogged = 0; - } - addTrace() { - } - getTraceMessage() { - return { - creation_timestamp: dateToProtoTimestamp(this.creationTimestamp), - num_events_logged: this.eventsLogged, - events: [] - }; - } - }; - exports2.ChannelzTraceStub = ChannelzTraceStub; - var ChannelzTrace = class { - constructor() { - this.events = []; - this.eventsLogged = 0; - this.creationTimestamp = /* @__PURE__ */ new Date(); - } - addTrace(severity, description, child) { - const timestamp = /* @__PURE__ */ new Date(); - this.events.push({ - description, - severity, - timestamp, - childChannel: (child === null || child === void 0 ? void 0 : child.kind) === "channel" ? child : void 0, - childSubchannel: (child === null || child === void 0 ? void 0 : child.kind) === "subchannel" ? child : void 0 - }); - if (this.events.length >= TARGET_RETAINED_TRACES * 2) { - this.events = this.events.slice(TARGET_RETAINED_TRACES); - } - this.eventsLogged += 1; - } - getTraceMessage() { - return { - creation_timestamp: dateToProtoTimestamp(this.creationTimestamp), - num_events_logged: this.eventsLogged, - events: this.events.map((event) => { - return { - description: event.description, - severity: event.severity, - timestamp: dateToProtoTimestamp(event.timestamp), - channel_ref: event.childChannel ? channelRefToMessage(event.childChannel) : null, - subchannel_ref: event.childSubchannel ? subchannelRefToMessage(event.childSubchannel) : null - }; - }) - }; - } - }; - exports2.ChannelzTrace = ChannelzTrace; - var ChannelzChildrenTracker = class { - constructor() { - this.channelChildren = new ordered_map_1.OrderedMap(); - this.subchannelChildren = new ordered_map_1.OrderedMap(); - this.socketChildren = new ordered_map_1.OrderedMap(); - this.trackerMap = { - [ - "channel" - /* EntityTypes.channel */ - ]: this.channelChildren, - [ - "subchannel" - /* EntityTypes.subchannel */ - ]: this.subchannelChildren, - [ - "socket" - /* EntityTypes.socket */ - ]: this.socketChildren - }; - } - refChild(child) { - const tracker = this.trackerMap[child.kind]; - const trackedChild = tracker.find(child.id); - if (trackedChild.equals(tracker.end())) { - tracker.setElement(child.id, { - ref: child, - count: 1 - }, trackedChild); - } else { - trackedChild.pointer[1].count += 1; - } - } - unrefChild(child) { - const tracker = this.trackerMap[child.kind]; - const trackedChild = tracker.getElementByKey(child.id); - if (trackedChild !== void 0) { - trackedChild.count -= 1; - if (trackedChild.count === 0) { - tracker.eraseElementByKey(child.id); - } - } - } - getChildLists() { - return { - channels: this.channelChildren, - subchannels: this.subchannelChildren, - sockets: this.socketChildren - }; - } - }; - exports2.ChannelzChildrenTracker = ChannelzChildrenTracker; - var ChannelzChildrenTrackerStub = class extends ChannelzChildrenTracker { - refChild() { - } - unrefChild() { - } - }; - exports2.ChannelzChildrenTrackerStub = ChannelzChildrenTrackerStub; - var ChannelzCallTracker = class { - constructor() { - this.callsStarted = 0; - this.callsSucceeded = 0; - this.callsFailed = 0; - this.lastCallStartedTimestamp = null; - } - addCallStarted() { - this.callsStarted += 1; - this.lastCallStartedTimestamp = /* @__PURE__ */ new Date(); - } - addCallSucceeded() { - this.callsSucceeded += 1; - } - addCallFailed() { - this.callsFailed += 1; - } - }; - exports2.ChannelzCallTracker = ChannelzCallTracker; - var ChannelzCallTrackerStub = class extends ChannelzCallTracker { - addCallStarted() { - } - addCallSucceeded() { - } - addCallFailed() { - } - }; - exports2.ChannelzCallTrackerStub = ChannelzCallTrackerStub; - var entityMaps = { - [ - "channel" - /* EntityTypes.channel */ - ]: new ordered_map_1.OrderedMap(), - [ - "subchannel" - /* EntityTypes.subchannel */ - ]: new ordered_map_1.OrderedMap(), - [ - "server" - /* EntityTypes.server */ - ]: new ordered_map_1.OrderedMap(), - [ - "socket" - /* EntityTypes.socket */ - ]: new ordered_map_1.OrderedMap() - }; - var generateRegisterFn = (kind) => { - let nextId = 1; - function getNextId() { - return nextId++; - } - const entityMap = entityMaps[kind]; - return (name, getInfo, channelzEnabled) => { - const id = getNextId(); - const ref = { id, name, kind }; - if (channelzEnabled) { - entityMap.setElement(id, { ref, getInfo }); - } - return ref; - }; - }; - exports2.registerChannelzChannel = generateRegisterFn( - "channel" - /* EntityTypes.channel */ - ); - exports2.registerChannelzSubchannel = generateRegisterFn( - "subchannel" - /* EntityTypes.subchannel */ - ); - exports2.registerChannelzServer = generateRegisterFn( - "server" - /* EntityTypes.server */ - ); - exports2.registerChannelzSocket = generateRegisterFn( - "socket" - /* EntityTypes.socket */ - ); - function unregisterChannelzRef(ref) { - entityMaps[ref.kind].eraseElementByKey(ref.id); - } - function parseIPv6Section(addressSection) { - const numberValue = Number.parseInt(addressSection, 16); - return [numberValue / 256 | 0, numberValue % 256]; - } - function parseIPv6Chunk(addressChunk) { - if (addressChunk === "") { - return []; - } - const bytePairs = addressChunk.split(":").map((section) => parseIPv6Section(section)); - const result = []; - return result.concat(...bytePairs); - } - function isIPv6MappedIPv4(ipAddress) { - return (0, net_1.isIPv6)(ipAddress) && ipAddress.toLowerCase().startsWith("::ffff:") && (0, net_1.isIPv4)(ipAddress.substring(7)); - } - function ipv4AddressStringToBuffer(ipAddress) { - return Buffer.from(Uint8Array.from(ipAddress.split(".").map((segment) => Number.parseInt(segment)))); - } - function ipAddressStringToBuffer(ipAddress) { - if ((0, net_1.isIPv4)(ipAddress)) { - return ipv4AddressStringToBuffer(ipAddress); - } else if (isIPv6MappedIPv4(ipAddress)) { - return ipv4AddressStringToBuffer(ipAddress.substring(7)); - } else if ((0, net_1.isIPv6)(ipAddress)) { - let leftSection; - let rightSection; - const doubleColonIndex = ipAddress.indexOf("::"); - if (doubleColonIndex === -1) { - leftSection = ipAddress; - rightSection = ""; - } else { - leftSection = ipAddress.substring(0, doubleColonIndex); - rightSection = ipAddress.substring(doubleColonIndex + 2); - } - const leftBuffer = Buffer.from(parseIPv6Chunk(leftSection)); - const rightBuffer = Buffer.from(parseIPv6Chunk(rightSection)); - const middleBuffer = Buffer.alloc(16 - leftBuffer.length - rightBuffer.length, 0); - return Buffer.concat([leftBuffer, middleBuffer, rightBuffer]); - } else { - return null; - } - } - function connectivityStateToMessage(state) { - switch (state) { - case connectivity_state_1.ConnectivityState.CONNECTING: - return { - state: "CONNECTING" - }; - case connectivity_state_1.ConnectivityState.IDLE: - return { - state: "IDLE" - }; - case connectivity_state_1.ConnectivityState.READY: - return { - state: "READY" - }; - case connectivity_state_1.ConnectivityState.SHUTDOWN: - return { - state: "SHUTDOWN" - }; - case connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE: - return { - state: "TRANSIENT_FAILURE" - }; - default: - return { - state: "UNKNOWN" - }; - } - } - function dateToProtoTimestamp(date) { - if (!date) { - return null; - } - const millisSinceEpoch = date.getTime(); - return { - seconds: millisSinceEpoch / 1e3 | 0, - nanos: millisSinceEpoch % 1e3 * 1e6 - }; - } - function getChannelMessage(channelEntry) { - const resolvedInfo = channelEntry.getInfo(); - const channelRef = []; - const subchannelRef = []; - resolvedInfo.children.channels.forEach((el) => { - channelRef.push(channelRefToMessage(el[1].ref)); - }); - resolvedInfo.children.subchannels.forEach((el) => { - subchannelRef.push(subchannelRefToMessage(el[1].ref)); - }); - return { - ref: channelRefToMessage(channelEntry.ref), - data: { - target: resolvedInfo.target, - state: connectivityStateToMessage(resolvedInfo.state), - calls_started: resolvedInfo.callTracker.callsStarted, - calls_succeeded: resolvedInfo.callTracker.callsSucceeded, - calls_failed: resolvedInfo.callTracker.callsFailed, - last_call_started_timestamp: dateToProtoTimestamp(resolvedInfo.callTracker.lastCallStartedTimestamp), - trace: resolvedInfo.trace.getTraceMessage() - }, - channel_ref: channelRef, - subchannel_ref: subchannelRef - }; - } - function GetChannel(call, callback) { - const channelId = parseInt(call.request.channel_id, 10); - const channelEntry = entityMaps[ - "channel" - /* EntityTypes.channel */ - ].getElementByKey(channelId); - if (channelEntry === void 0) { - callback({ - code: constants_1.Status.NOT_FOUND, - details: "No channel data found for id " + channelId - }); - return; - } - callback(null, { channel: getChannelMessage(channelEntry) }); - } - function GetTopChannels(call, callback) { - const maxResults = parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS; - const resultList = []; - const startId = parseInt(call.request.start_channel_id, 10); - const channelEntries = entityMaps[ - "channel" - /* EntityTypes.channel */ - ]; - let i; - for (i = channelEntries.lowerBound(startId); !i.equals(channelEntries.end()) && resultList.length < maxResults; i = i.next()) { - resultList.push(getChannelMessage(i.pointer[1])); - } - callback(null, { - channel: resultList, - end: i.equals(channelEntries.end()) - }); - } - function getServerMessage(serverEntry) { - const resolvedInfo = serverEntry.getInfo(); - const listenSocket = []; - resolvedInfo.listenerChildren.sockets.forEach((el) => { - listenSocket.push(socketRefToMessage(el[1].ref)); - }); - return { - ref: serverRefToMessage(serverEntry.ref), - data: { - calls_started: resolvedInfo.callTracker.callsStarted, - calls_succeeded: resolvedInfo.callTracker.callsSucceeded, - calls_failed: resolvedInfo.callTracker.callsFailed, - last_call_started_timestamp: dateToProtoTimestamp(resolvedInfo.callTracker.lastCallStartedTimestamp), - trace: resolvedInfo.trace.getTraceMessage() - }, - listen_socket: listenSocket - }; - } - function GetServer(call, callback) { - const serverId = parseInt(call.request.server_id, 10); - const serverEntries = entityMaps[ - "server" - /* EntityTypes.server */ - ]; - const serverEntry = serverEntries.getElementByKey(serverId); - if (serverEntry === void 0) { - callback({ - code: constants_1.Status.NOT_FOUND, - details: "No server data found for id " + serverId - }); - return; - } - callback(null, { server: getServerMessage(serverEntry) }); - } - function GetServers(call, callback) { - const maxResults = parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS; - const startId = parseInt(call.request.start_server_id, 10); - const serverEntries = entityMaps[ - "server" - /* EntityTypes.server */ - ]; - const resultList = []; - let i; - for (i = serverEntries.lowerBound(startId); !i.equals(serverEntries.end()) && resultList.length < maxResults; i = i.next()) { - resultList.push(getServerMessage(i.pointer[1])); - } - callback(null, { - server: resultList, - end: i.equals(serverEntries.end()) - }); - } - function GetSubchannel(call, callback) { - const subchannelId = parseInt(call.request.subchannel_id, 10); - const subchannelEntry = entityMaps[ - "subchannel" - /* EntityTypes.subchannel */ - ].getElementByKey(subchannelId); - if (subchannelEntry === void 0) { - callback({ - code: constants_1.Status.NOT_FOUND, - details: "No subchannel data found for id " + subchannelId - }); - return; - } - const resolvedInfo = subchannelEntry.getInfo(); - const listenSocket = []; - resolvedInfo.children.sockets.forEach((el) => { - listenSocket.push(socketRefToMessage(el[1].ref)); - }); - const subchannelMessage = { - ref: subchannelRefToMessage(subchannelEntry.ref), - data: { - target: resolvedInfo.target, - state: connectivityStateToMessage(resolvedInfo.state), - calls_started: resolvedInfo.callTracker.callsStarted, - calls_succeeded: resolvedInfo.callTracker.callsSucceeded, - calls_failed: resolvedInfo.callTracker.callsFailed, - last_call_started_timestamp: dateToProtoTimestamp(resolvedInfo.callTracker.lastCallStartedTimestamp), - trace: resolvedInfo.trace.getTraceMessage() - }, - socket_ref: listenSocket - }; - callback(null, { subchannel: subchannelMessage }); - } - function subchannelAddressToAddressMessage(subchannelAddress) { - var _a; - if ((0, subchannel_address_1.isTcpSubchannelAddress)(subchannelAddress)) { - return { - address: "tcpip_address", - tcpip_address: { - ip_address: (_a = ipAddressStringToBuffer(subchannelAddress.host)) !== null && _a !== void 0 ? _a : void 0, - port: subchannelAddress.port - } - }; - } else { - return { - address: "uds_address", - uds_address: { - filename: subchannelAddress.path - } - }; - } - } - function GetSocket(call, callback) { - var _a, _b, _c, _d, _e; - const socketId = parseInt(call.request.socket_id, 10); - const socketEntry = entityMaps[ - "socket" - /* EntityTypes.socket */ - ].getElementByKey(socketId); - if (socketEntry === void 0) { - callback({ - code: constants_1.Status.NOT_FOUND, - details: "No socket data found for id " + socketId - }); - return; - } - const resolvedInfo = socketEntry.getInfo(); - const securityMessage = resolvedInfo.security ? { - model: "tls", - tls: { - cipher_suite: resolvedInfo.security.cipherSuiteStandardName ? "standard_name" : "other_name", - standard_name: (_a = resolvedInfo.security.cipherSuiteStandardName) !== null && _a !== void 0 ? _a : void 0, - other_name: (_b = resolvedInfo.security.cipherSuiteOtherName) !== null && _b !== void 0 ? _b : void 0, - local_certificate: (_c = resolvedInfo.security.localCertificate) !== null && _c !== void 0 ? _c : void 0, - remote_certificate: (_d = resolvedInfo.security.remoteCertificate) !== null && _d !== void 0 ? _d : void 0 - } - } : null; - const socketMessage = { - ref: socketRefToMessage(socketEntry.ref), - local: resolvedInfo.localAddress ? subchannelAddressToAddressMessage(resolvedInfo.localAddress) : null, - remote: resolvedInfo.remoteAddress ? subchannelAddressToAddressMessage(resolvedInfo.remoteAddress) : null, - remote_name: (_e = resolvedInfo.remoteName) !== null && _e !== void 0 ? _e : void 0, - security: securityMessage, - data: { - keep_alives_sent: resolvedInfo.keepAlivesSent, - streams_started: resolvedInfo.streamsStarted, - streams_succeeded: resolvedInfo.streamsSucceeded, - streams_failed: resolvedInfo.streamsFailed, - last_local_stream_created_timestamp: dateToProtoTimestamp(resolvedInfo.lastLocalStreamCreatedTimestamp), - last_remote_stream_created_timestamp: dateToProtoTimestamp(resolvedInfo.lastRemoteStreamCreatedTimestamp), - messages_received: resolvedInfo.messagesReceived, - messages_sent: resolvedInfo.messagesSent, - last_message_received_timestamp: dateToProtoTimestamp(resolvedInfo.lastMessageReceivedTimestamp), - last_message_sent_timestamp: dateToProtoTimestamp(resolvedInfo.lastMessageSentTimestamp), - local_flow_control_window: resolvedInfo.localFlowControlWindow ? { value: resolvedInfo.localFlowControlWindow } : null, - remote_flow_control_window: resolvedInfo.remoteFlowControlWindow ? { value: resolvedInfo.remoteFlowControlWindow } : null - } - }; - callback(null, { socket: socketMessage }); - } - function GetServerSockets(call, callback) { - const serverId = parseInt(call.request.server_id, 10); - const serverEntry = entityMaps[ - "server" - /* EntityTypes.server */ - ].getElementByKey(serverId); - if (serverEntry === void 0) { - callback({ - code: constants_1.Status.NOT_FOUND, - details: "No server data found for id " + serverId - }); - return; - } - const startId = parseInt(call.request.start_socket_id, 10); - const maxResults = parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS; - const resolvedInfo = serverEntry.getInfo(); - const allSockets = resolvedInfo.sessionChildren.sockets; - const resultList = []; - let i; - for (i = allSockets.lowerBound(startId); !i.equals(allSockets.end()) && resultList.length < maxResults; i = i.next()) { - resultList.push(socketRefToMessage(i.pointer[1].ref)); - } - callback(null, { - socket_ref: resultList, - end: i.equals(allSockets.end()) - }); - } - function getChannelzHandlers() { - return { - GetChannel, - GetTopChannels, - GetServer, - GetServers, - GetSubchannel, - GetSocket, - GetServerSockets - }; - } - var loadedChannelzDefinition = null; - function getChannelzServiceDefinition() { - if (loadedChannelzDefinition) { - return loadedChannelzDefinition; - } - const loaderLoadSync = require_src3().loadSync; - const loadedProto = loaderLoadSync("channelz.proto", { - keepCase: true, - longs: String, - enums: String, - defaults: true, - oneofs: true, - includeDirs: [`${__dirname}/../../proto`] - }); - const channelzGrpcObject = (0, make_client_1.loadPackageDefinition)(loadedProto); - loadedChannelzDefinition = channelzGrpcObject.grpc.channelz.v1.Channelz.service; - return loadedChannelzDefinition; - } - function setup() { - (0, admin_1.registerAdminService)(getChannelzServiceDefinition, getChannelzHandlers); - } - } -}); - -// node_modules/@grpc/grpc-js/build/src/call-number.js -var require_call_number = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/call-number.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getNextCallNumber = getNextCallNumber; - var nextCallNumber = 0; - function getNextCallNumber() { - return nextCallNumber++; - } - } -}); - -// node_modules/@grpc/grpc-js/build/src/compression-algorithms.js -var require_compression_algorithms = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/compression-algorithms.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CompressionAlgorithms = void 0; - var CompressionAlgorithms; - (function(CompressionAlgorithms2) { - CompressionAlgorithms2[CompressionAlgorithms2["identity"] = 0] = "identity"; - CompressionAlgorithms2[CompressionAlgorithms2["deflate"] = 1] = "deflate"; - CompressionAlgorithms2[CompressionAlgorithms2["gzip"] = 2] = "gzip"; - })(CompressionAlgorithms || (exports2.CompressionAlgorithms = CompressionAlgorithms = {})); - } -}); - -// node_modules/@grpc/grpc-js/build/src/filter.js -var require_filter = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/filter.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BaseFilter = void 0; - var BaseFilter = class { - async sendMetadata(metadata) { - return metadata; - } - receiveMetadata(metadata) { - return metadata; - } - async sendMessage(message) { - return message; - } - async receiveMessage(message) { - return message; - } - receiveTrailers(status) { - return status; - } - }; - exports2.BaseFilter = BaseFilter; - } -}); - -// node_modules/@grpc/grpc-js/build/src/compression-filter.js -var require_compression_filter = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/compression-filter.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CompressionFilterFactory = exports2.CompressionFilter = void 0; - var zlib = require("zlib"); - var compression_algorithms_1 = require_compression_algorithms(); - var constants_1 = require_constants7(); - var filter_1 = require_filter(); - var logging = require_logging(); - var isCompressionAlgorithmKey = (key) => { - return typeof key === "number" && typeof compression_algorithms_1.CompressionAlgorithms[key] === "string"; - }; - var CompressionHandler = class { - /** - * @param message Raw uncompressed message bytes - * @param compress Indicates whether the message should be compressed - * @return Framed message, compressed if applicable - */ - async writeMessage(message, compress) { - let messageBuffer = message; - if (compress) { - messageBuffer = await this.compressMessage(messageBuffer); - } - const output = Buffer.allocUnsafe(messageBuffer.length + 5); - output.writeUInt8(compress ? 1 : 0, 0); - output.writeUInt32BE(messageBuffer.length, 1); - messageBuffer.copy(output, 5); - return output; - } - /** - * @param data Framed message, possibly compressed - * @return Uncompressed message - */ - async readMessage(data) { - const compressed = data.readUInt8(0) === 1; - let messageBuffer = data.slice(5); - if (compressed) { - messageBuffer = await this.decompressMessage(messageBuffer); - } - return messageBuffer; - } - }; - var IdentityHandler = class extends CompressionHandler { - async compressMessage(message) { - return message; - } - async writeMessage(message, compress) { - const output = Buffer.allocUnsafe(message.length + 5); - output.writeUInt8(0, 0); - output.writeUInt32BE(message.length, 1); - message.copy(output, 5); - return output; - } - decompressMessage(message) { - return Promise.reject(new Error('Received compressed message but "grpc-encoding" header was identity')); - } - }; - var DeflateHandler = class extends CompressionHandler { - constructor(maxRecvMessageLength) { - super(); - this.maxRecvMessageLength = maxRecvMessageLength; - } - compressMessage(message) { - return new Promise((resolve, reject) => { - zlib.deflate(message, (err, output) => { - if (err) { - reject(err); - } else { - resolve(output); - } - }); - }); - } - decompressMessage(message) { - return new Promise((resolve, reject) => { - let totalLength = 0; - const messageParts = []; - const decompresser = zlib.createInflate(); - decompresser.on("error", (error3) => { - reject({ - code: constants_1.Status.INTERNAL, - details: "Failed to decompress deflate-encoded message" - }); - }); - decompresser.on("data", (chunk) => { - messageParts.push(chunk); - totalLength += chunk.byteLength; - if (this.maxRecvMessageLength !== -1 && totalLength > this.maxRecvMessageLength) { - decompresser.destroy(); - reject({ - code: constants_1.Status.RESOURCE_EXHAUSTED, - details: `Received message that decompresses to a size larger than ${this.maxRecvMessageLength}` - }); - } - }); - decompresser.on("end", () => { - resolve(Buffer.concat(messageParts)); - }); - decompresser.write(message); - decompresser.end(); - }); - } - }; - var GzipHandler = class extends CompressionHandler { - constructor(maxRecvMessageLength) { - super(); - this.maxRecvMessageLength = maxRecvMessageLength; - } - compressMessage(message) { - return new Promise((resolve, reject) => { - zlib.gzip(message, (err, output) => { - if (err) { - reject(err); - } else { - resolve(output); - } - }); - }); - } - decompressMessage(message) { - return new Promise((resolve, reject) => { - let totalLength = 0; - const messageParts = []; - const decompresser = zlib.createGunzip(); - decompresser.on("error", (error3) => { - reject({ - code: constants_1.Status.INTERNAL, - details: "Failed to decompress gzip-encoded message" - }); - }); - decompresser.on("data", (chunk) => { - messageParts.push(chunk); - totalLength += chunk.byteLength; - if (this.maxRecvMessageLength !== -1 && totalLength > this.maxRecvMessageLength) { - decompresser.destroy(); - reject({ - code: constants_1.Status.RESOURCE_EXHAUSTED, - details: `Received message that decompresses to a size larger than ${this.maxRecvMessageLength}` - }); - } - }); - decompresser.on("end", () => { - resolve(Buffer.concat(messageParts)); - }); - decompresser.write(message); - decompresser.end(); - }); - } - }; - var UnknownHandler = class extends CompressionHandler { - constructor(compressionName) { - super(); - this.compressionName = compressionName; - } - compressMessage(message) { - return Promise.reject(new Error(`Received message compressed with unsupported compression method ${this.compressionName}`)); - } - decompressMessage(message) { - return Promise.reject(new Error(`Compression method not supported: ${this.compressionName}`)); - } - }; - function getCompressionHandler(compressionName, maxReceiveMessageSize) { - switch (compressionName) { - case "identity": - return new IdentityHandler(); - case "deflate": - return new DeflateHandler(maxReceiveMessageSize); - case "gzip": - return new GzipHandler(maxReceiveMessageSize); - default: - return new UnknownHandler(compressionName); - } - } - var CompressionFilter = class extends filter_1.BaseFilter { - constructor(channelOptions, sharedFilterConfig) { - var _a, _b, _c; - super(); - this.sharedFilterConfig = sharedFilterConfig; - this.sendCompression = new IdentityHandler(); - this.receiveCompression = new IdentityHandler(); - this.currentCompressionAlgorithm = "identity"; - const compressionAlgorithmKey = channelOptions["grpc.default_compression_algorithm"]; - this.maxReceiveMessageLength = (_a = channelOptions["grpc.max_receive_message_length"]) !== null && _a !== void 0 ? _a : constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH; - this.maxSendMessageLength = (_b = channelOptions["grpc.max_send_message_length"]) !== null && _b !== void 0 ? _b : constants_1.DEFAULT_MAX_SEND_MESSAGE_LENGTH; - if (compressionAlgorithmKey !== void 0) { - if (isCompressionAlgorithmKey(compressionAlgorithmKey)) { - const clientSelectedEncoding = compression_algorithms_1.CompressionAlgorithms[compressionAlgorithmKey]; - const serverSupportedEncodings = (_c = sharedFilterConfig.serverSupportedEncodingHeader) === null || _c === void 0 ? void 0 : _c.split(","); - if (!serverSupportedEncodings || serverSupportedEncodings.includes(clientSelectedEncoding)) { - this.currentCompressionAlgorithm = clientSelectedEncoding; - this.sendCompression = getCompressionHandler(this.currentCompressionAlgorithm, -1); - } - } else { - logging.log(constants_1.LogVerbosity.ERROR, `Invalid value provided for grpc.default_compression_algorithm option: ${compressionAlgorithmKey}`); - } - } - } - async sendMetadata(metadata) { - const headers = await metadata; - headers.set("grpc-accept-encoding", "identity,deflate,gzip"); - headers.set("accept-encoding", "identity"); - if (this.currentCompressionAlgorithm === "identity") { - headers.remove("grpc-encoding"); - } else { - headers.set("grpc-encoding", this.currentCompressionAlgorithm); - } - return headers; - } - receiveMetadata(metadata) { - const receiveEncoding = metadata.get("grpc-encoding"); - if (receiveEncoding.length > 0) { - const encoding = receiveEncoding[0]; - if (typeof encoding === "string") { - this.receiveCompression = getCompressionHandler(encoding, this.maxReceiveMessageLength); - } - } - metadata.remove("grpc-encoding"); - const serverSupportedEncodingsHeader = metadata.get("grpc-accept-encoding")[0]; - if (serverSupportedEncodingsHeader) { - this.sharedFilterConfig.serverSupportedEncodingHeader = serverSupportedEncodingsHeader; - const serverSupportedEncodings = serverSupportedEncodingsHeader.split(","); - if (!serverSupportedEncodings.includes(this.currentCompressionAlgorithm)) { - this.sendCompression = new IdentityHandler(); - this.currentCompressionAlgorithm = "identity"; - } - } - metadata.remove("grpc-accept-encoding"); - return metadata; - } - async sendMessage(message) { - var _a; - const resolvedMessage = await message; - if (this.maxSendMessageLength !== -1 && resolvedMessage.message.length > this.maxSendMessageLength) { - throw { - code: constants_1.Status.RESOURCE_EXHAUSTED, - details: `Attempted to send message with a size larger than ${this.maxSendMessageLength}` - }; - } - let compress; - if (this.sendCompression instanceof IdentityHandler) { - compress = false; - } else { - compress = (((_a = resolvedMessage.flags) !== null && _a !== void 0 ? _a : 0) & 2) === 0; - } - return { - message: await this.sendCompression.writeMessage(resolvedMessage.message, compress), - flags: resolvedMessage.flags - }; - } - async receiveMessage(message) { - return this.receiveCompression.readMessage(await message); - } - }; - exports2.CompressionFilter = CompressionFilter; - var CompressionFilterFactory = class { - constructor(channel, options) { - this.options = options; - this.sharedFilterConfig = {}; - } - createFilter() { - return new CompressionFilter(this.options, this.sharedFilterConfig); - } - }; - exports2.CompressionFilterFactory = CompressionFilterFactory; - } -}); - -// node_modules/@grpc/grpc-js/build/src/control-plane-status.js -var require_control_plane_status = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/control-plane-status.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.restrictControlPlaneStatusCode = restrictControlPlaneStatusCode; - var constants_1 = require_constants7(); - var INAPPROPRIATE_CONTROL_PLANE_CODES = [ - constants_1.Status.OK, - constants_1.Status.INVALID_ARGUMENT, - constants_1.Status.NOT_FOUND, - constants_1.Status.ALREADY_EXISTS, - constants_1.Status.FAILED_PRECONDITION, - constants_1.Status.ABORTED, - constants_1.Status.OUT_OF_RANGE, - constants_1.Status.DATA_LOSS - ]; - function restrictControlPlaneStatusCode(code, details) { - if (INAPPROPRIATE_CONTROL_PLANE_CODES.includes(code)) { - return { - code: constants_1.Status.INTERNAL, - details: `Invalid status from control plane: ${code} ${constants_1.Status[code]} ${details}` - }; - } else { - return { code, details }; - } - } - } -}); - -// node_modules/@grpc/grpc-js/build/src/deadline.js -var require_deadline = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/deadline.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.minDeadline = minDeadline; - exports2.getDeadlineTimeoutString = getDeadlineTimeoutString; - exports2.getRelativeTimeout = getRelativeTimeout; - exports2.deadlineToString = deadlineToString; - exports2.formatDateDifference = formatDateDifference; - function minDeadline(...deadlineList) { - let minValue = Infinity; - for (const deadline of deadlineList) { - const deadlineMsecs = deadline instanceof Date ? deadline.getTime() : deadline; - if (deadlineMsecs < minValue) { - minValue = deadlineMsecs; - } - } - return minValue; - } - var units = [ - ["m", 1], - ["S", 1e3], - ["M", 60 * 1e3], - ["H", 60 * 60 * 1e3] - ]; - function getDeadlineTimeoutString(deadline) { - const now = (/* @__PURE__ */ new Date()).getTime(); - if (deadline instanceof Date) { - deadline = deadline.getTime(); - } - const timeoutMs = Math.max(deadline - now, 0); - for (const [unit, factor] of units) { - const amount = timeoutMs / factor; - if (amount < 1e8) { - return String(Math.ceil(amount)) + unit; - } - } - throw new Error("Deadline is too far in the future"); - } - var MAX_TIMEOUT_TIME = 2147483647; - function getRelativeTimeout(deadline) { - const deadlineMs = deadline instanceof Date ? deadline.getTime() : deadline; - const now = (/* @__PURE__ */ new Date()).getTime(); - const timeout = deadlineMs - now; - if (timeout < 0) { - return 0; - } else if (timeout > MAX_TIMEOUT_TIME) { - return Infinity; - } else { - return timeout; - } - } - function deadlineToString(deadline) { - if (deadline instanceof Date) { - return deadline.toISOString(); - } else { - const dateDeadline = new Date(deadline); - if (Number.isNaN(dateDeadline.getTime())) { - return "" + deadline; - } else { - return dateDeadline.toISOString(); - } - } - } - function formatDateDifference(startDate, endDate) { - return ((endDate.getTime() - startDate.getTime()) / 1e3).toFixed(3) + "s"; - } - } -}); - -// node_modules/@grpc/grpc-js/build/src/filter-stack.js -var require_filter_stack = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/filter-stack.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.FilterStackFactory = exports2.FilterStack = void 0; - var FilterStack = class { - constructor(filters) { - this.filters = filters; - } - sendMetadata(metadata) { - let result = metadata; - for (let i = 0; i < this.filters.length; i++) { - result = this.filters[i].sendMetadata(result); - } - return result; - } - receiveMetadata(metadata) { - let result = metadata; - for (let i = this.filters.length - 1; i >= 0; i--) { - result = this.filters[i].receiveMetadata(result); - } - return result; - } - sendMessage(message) { - let result = message; - for (let i = 0; i < this.filters.length; i++) { - result = this.filters[i].sendMessage(result); - } - return result; - } - receiveMessage(message) { - let result = message; - for (let i = this.filters.length - 1; i >= 0; i--) { - result = this.filters[i].receiveMessage(result); - } - return result; - } - receiveTrailers(status) { - let result = status; - for (let i = this.filters.length - 1; i >= 0; i--) { - result = this.filters[i].receiveTrailers(result); - } - return result; - } - push(filters) { - this.filters.unshift(...filters); - } - getFilters() { - return this.filters; - } - }; - exports2.FilterStack = FilterStack; - var FilterStackFactory = class _FilterStackFactory { - constructor(factories) { - this.factories = factories; - } - push(filterFactories) { - this.factories.unshift(...filterFactories); - } - clone() { - return new _FilterStackFactory([...this.factories]); - } - createFilter() { - return new FilterStack(this.factories.map((factory) => factory.createFilter())); - } - }; - exports2.FilterStackFactory = FilterStackFactory; - } -}); - -// node_modules/@grpc/grpc-js/build/src/single-subchannel-channel.js -var require_single_subchannel_channel = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/single-subchannel-channel.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.SingleSubchannelChannel = void 0; - var call_number_1 = require_call_number(); - var channelz_1 = require_channelz(); - var compression_filter_1 = require_compression_filter(); - var connectivity_state_1 = require_connectivity_state(); - var constants_1 = require_constants7(); - var control_plane_status_1 = require_control_plane_status(); - var deadline_1 = require_deadline(); - var filter_stack_1 = require_filter_stack(); - var metadata_1 = require_metadata(); - var resolver_1 = require_resolver(); - var uri_parser_1 = require_uri_parser(); - var SubchannelCallWrapper = class { - constructor(subchannel, method, filterStackFactory, options, callNumber) { - var _a, _b; - this.subchannel = subchannel; - this.method = method; - this.options = options; - this.callNumber = callNumber; - this.childCall = null; - this.pendingMessage = null; - this.readPending = false; - this.halfClosePending = false; - this.pendingStatus = null; - this.readFilterPending = false; - this.writeFilterPending = false; - const splitPath = this.method.split("/"); - let serviceName = ""; - if (splitPath.length >= 2) { - serviceName = splitPath[1]; - } - const hostname = (_b = (_a = (0, uri_parser_1.splitHostPort)(this.options.host)) === null || _a === void 0 ? void 0 : _a.host) !== null && _b !== void 0 ? _b : "localhost"; - this.serviceUrl = `https://${hostname}/${serviceName}`; - const timeout = (0, deadline_1.getRelativeTimeout)(options.deadline); - if (timeout !== Infinity) { - if (timeout <= 0) { - this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, "Deadline exceeded"); - } else { - setTimeout(() => { - this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, "Deadline exceeded"); - }, timeout); - } - } - this.filterStack = filterStackFactory.createFilter(); - } - cancelWithStatus(status, details) { - if (this.childCall) { - this.childCall.cancelWithStatus(status, details); - } else { - this.pendingStatus = { - code: status, - details, - metadata: new metadata_1.Metadata() - }; - } - } - getPeer() { - var _a, _b; - return (_b = (_a = this.childCall) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : this.subchannel.getAddress(); - } - async start(metadata, listener) { - if (this.pendingStatus) { - listener.onReceiveStatus(this.pendingStatus); - return; - } - if (this.subchannel.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) { - listener.onReceiveStatus({ - code: constants_1.Status.UNAVAILABLE, - details: "Subchannel not ready", - metadata: new metadata_1.Metadata() - }); - return; - } - const filteredMetadata = await this.filterStack.sendMetadata(Promise.resolve(metadata)); - let credsMetadata; - try { - credsMetadata = await this.subchannel.getCallCredentials().generateMetadata({ method_name: this.method, service_url: this.serviceUrl }); - } catch (e) { - const error3 = e; - const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(typeof error3.code === "number" ? error3.code : constants_1.Status.UNKNOWN, `Getting metadata from plugin failed with error: ${error3.message}`); - listener.onReceiveStatus({ - code, - details, - metadata: new metadata_1.Metadata() - }); - return; - } - credsMetadata.merge(filteredMetadata); - const childListener = { - onReceiveMetadata: async (metadata2) => { - listener.onReceiveMetadata(await this.filterStack.receiveMetadata(metadata2)); - }, - onReceiveMessage: async (message) => { - this.readFilterPending = true; - const filteredMessage = await this.filterStack.receiveMessage(message); - this.readFilterPending = false; - listener.onReceiveMessage(filteredMessage); - if (this.pendingStatus) { - listener.onReceiveStatus(this.pendingStatus); - } - }, - onReceiveStatus: async (status) => { - const filteredStatus = await this.filterStack.receiveTrailers(status); - if (this.readFilterPending) { - this.pendingStatus = filteredStatus; - } else { - listener.onReceiveStatus(filteredStatus); - } - } - }; - this.childCall = this.subchannel.createCall(credsMetadata, this.options.host, this.method, childListener); - if (this.readPending) { - this.childCall.startRead(); - } - if (this.pendingMessage) { - this.childCall.sendMessageWithContext(this.pendingMessage.context, this.pendingMessage.message); - } - if (this.halfClosePending && !this.writeFilterPending) { - this.childCall.halfClose(); - } - } - async sendMessageWithContext(context3, message) { - this.writeFilterPending = true; - const filteredMessage = await this.filterStack.sendMessage(Promise.resolve({ message, flags: context3.flags })); - this.writeFilterPending = false; - if (this.childCall) { - this.childCall.sendMessageWithContext(context3, filteredMessage.message); - if (this.halfClosePending) { - this.childCall.halfClose(); - } - } else { - this.pendingMessage = { context: context3, message: filteredMessage.message }; - } - } - startRead() { - if (this.childCall) { - this.childCall.startRead(); - } else { - this.readPending = true; - } - } - halfClose() { - if (this.childCall && !this.writeFilterPending) { - this.childCall.halfClose(); - } else { - this.halfClosePending = true; - } - } - getCallNumber() { - return this.callNumber; - } - setCredentials(credentials) { - throw new Error("Method not implemented."); - } - getAuthContext() { - if (this.childCall) { - return this.childCall.getAuthContext(); - } else { - return null; - } - } - }; - var SingleSubchannelChannel = class { - constructor(subchannel, target, options) { - this.subchannel = subchannel; - this.target = target; - this.channelzEnabled = false; - this.channelzTrace = new channelz_1.ChannelzTrace(); - this.callTracker = new channelz_1.ChannelzCallTracker(); - this.childrenTracker = new channelz_1.ChannelzChildrenTracker(); - this.channelzEnabled = options["grpc.enable_channelz"] !== 0; - this.channelzRef = (0, channelz_1.registerChannelzChannel)((0, uri_parser_1.uriToString)(target), () => ({ - target: `${(0, uri_parser_1.uriToString)(target)} (${subchannel.getAddress()})`, - state: this.subchannel.getConnectivityState(), - trace: this.channelzTrace, - callTracker: this.callTracker, - children: this.childrenTracker.getChildLists() - }), this.channelzEnabled); - if (this.channelzEnabled) { - this.childrenTracker.refChild(subchannel.getChannelzRef()); - } - this.filterStackFactory = new filter_stack_1.FilterStackFactory([new compression_filter_1.CompressionFilterFactory(this, options)]); - } - close() { - if (this.channelzEnabled) { - this.childrenTracker.unrefChild(this.subchannel.getChannelzRef()); - } - (0, channelz_1.unregisterChannelzRef)(this.channelzRef); - } - getTarget() { - return (0, uri_parser_1.uriToString)(this.target); - } - getConnectivityState(tryToConnect) { - throw new Error("Method not implemented."); - } - watchConnectivityState(currentState, deadline, callback) { - throw new Error("Method not implemented."); - } - getChannelzRef() { - return this.channelzRef; - } - createCall(method, deadline) { - const callOptions = { - deadline, - host: (0, resolver_1.getDefaultAuthority)(this.target), - flags: constants_1.Propagate.DEFAULTS, - parentCall: null - }; - return new SubchannelCallWrapper(this.subchannel, method, this.filterStackFactory, callOptions, (0, call_number_1.getNextCallNumber)()); - } - }; - exports2.SingleSubchannelChannel = SingleSubchannelChannel; - } -}); - -// node_modules/@grpc/grpc-js/build/src/subchannel.js -var require_subchannel = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/subchannel.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Subchannel = void 0; - var connectivity_state_1 = require_connectivity_state(); - var backoff_timeout_1 = require_backoff_timeout(); - var logging = require_logging(); - var constants_1 = require_constants7(); - var uri_parser_1 = require_uri_parser(); - var subchannel_address_1 = require_subchannel_address(); - var channelz_1 = require_channelz(); - var single_subchannel_channel_1 = require_single_subchannel_channel(); - var TRACER_NAME = "subchannel"; - var KEEPALIVE_MAX_TIME_MS = ~(1 << 31); - var Subchannel = class { - /** - * A class representing a connection to a single backend. - * @param channelTarget The target string for the channel as a whole - * @param subchannelAddress The address for the backend that this subchannel - * will connect to - * @param options The channel options, plus any specific subchannel options - * for this subchannel - * @param credentials The channel credentials used to establish this - * connection - */ - constructor(channelTarget, subchannelAddress, options, credentials, connector) { - var _a; - this.channelTarget = channelTarget; - this.subchannelAddress = subchannelAddress; - this.options = options; - this.connector = connector; - this.connectivityState = connectivity_state_1.ConnectivityState.IDLE; - this.transport = null; - this.continueConnecting = false; - this.stateListeners = /* @__PURE__ */ new Set(); - this.refcount = 0; - this.channelzEnabled = true; - this.dataProducers = /* @__PURE__ */ new Map(); - this.subchannelChannel = null; - const backoffOptions = { - initialDelay: options["grpc.initial_reconnect_backoff_ms"], - maxDelay: options["grpc.max_reconnect_backoff_ms"] - }; - this.backoffTimeout = new backoff_timeout_1.BackoffTimeout(() => { - this.handleBackoffTimer(); - }, backoffOptions); - this.backoffTimeout.unref(); - this.subchannelAddressString = (0, subchannel_address_1.subchannelAddressToString)(subchannelAddress); - this.keepaliveTime = (_a = options["grpc.keepalive_time_ms"]) !== null && _a !== void 0 ? _a : -1; - if (options["grpc.enable_channelz"] === 0) { - this.channelzEnabled = false; - this.channelzTrace = new channelz_1.ChannelzTraceStub(); - this.callTracker = new channelz_1.ChannelzCallTrackerStub(); - this.childrenTracker = new channelz_1.ChannelzChildrenTrackerStub(); - this.streamTracker = new channelz_1.ChannelzCallTrackerStub(); - } else { - this.channelzTrace = new channelz_1.ChannelzTrace(); - this.callTracker = new channelz_1.ChannelzCallTracker(); - this.childrenTracker = new channelz_1.ChannelzChildrenTracker(); - this.streamTracker = new channelz_1.ChannelzCallTracker(); - } - this.channelzRef = (0, channelz_1.registerChannelzSubchannel)(this.subchannelAddressString, () => this.getChannelzInfo(), this.channelzEnabled); - this.channelzTrace.addTrace("CT_INFO", "Subchannel created"); - this.trace("Subchannel constructed with options " + JSON.stringify(options, void 0, 2)); - this.secureConnector = credentials._createSecureConnector(channelTarget, options); - } - getChannelzInfo() { - return { - state: this.connectivityState, - trace: this.channelzTrace, - callTracker: this.callTracker, - children: this.childrenTracker.getChildLists(), - target: this.subchannelAddressString - }; - } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); - } - refTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, "subchannel_refcount", "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); - } - handleBackoffTimer() { - if (this.continueConnecting) { - this.transitionToState([connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE], connectivity_state_1.ConnectivityState.CONNECTING); - } else { - this.transitionToState([connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE], connectivity_state_1.ConnectivityState.IDLE); - } - } - /** - * Start a backoff timer with the current nextBackoff timeout - */ - startBackoff() { - this.backoffTimeout.runOnce(); - } - stopBackoff() { - this.backoffTimeout.stop(); - this.backoffTimeout.reset(); - } - startConnectingInternal() { - let options = this.options; - if (options["grpc.keepalive_time_ms"]) { - const adjustedKeepaliveTime = Math.min(this.keepaliveTime, KEEPALIVE_MAX_TIME_MS); - options = Object.assign(Object.assign({}, options), { "grpc.keepalive_time_ms": adjustedKeepaliveTime }); - } - this.connector.connect(this.subchannelAddress, this.secureConnector, options).then((transport) => { - if (this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING], connectivity_state_1.ConnectivityState.READY)) { - this.transport = transport; - if (this.channelzEnabled) { - this.childrenTracker.refChild(transport.getChannelzRef()); - } - transport.addDisconnectListener((tooManyPings) => { - this.transitionToState([connectivity_state_1.ConnectivityState.READY], connectivity_state_1.ConnectivityState.IDLE); - if (tooManyPings && this.keepaliveTime > 0) { - this.keepaliveTime *= 2; - logging.log(constants_1.LogVerbosity.ERROR, `Connection to ${(0, uri_parser_1.uriToString)(this.channelTarget)} at ${this.subchannelAddressString} rejected by server because of excess pings. Increasing ping interval to ${this.keepaliveTime} ms`); - } - }); - } else { - transport.shutdown(); - } - }, (error3) => { - this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING], connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, `${error3}`); - }); - } - /** - * Initiate a state transition from any element of oldStates to the new - * state. If the current connectivityState is not in oldStates, do nothing. - * @param oldStates The set of states to transition from - * @param newState The state to transition to - * @returns True if the state changed, false otherwise - */ - transitionToState(oldStates, newState, errorMessage) { - var _a, _b; - if (oldStates.indexOf(this.connectivityState) === -1) { - return false; - } - if (errorMessage) { - this.trace(connectivity_state_1.ConnectivityState[this.connectivityState] + " -> " + connectivity_state_1.ConnectivityState[newState] + ' with error "' + errorMessage + '"'); - } else { - this.trace(connectivity_state_1.ConnectivityState[this.connectivityState] + " -> " + connectivity_state_1.ConnectivityState[newState]); - } - if (this.channelzEnabled) { - this.channelzTrace.addTrace("CT_INFO", "Connectivity state change to " + connectivity_state_1.ConnectivityState[newState]); - } - const previousState = this.connectivityState; - this.connectivityState = newState; - switch (newState) { - case connectivity_state_1.ConnectivityState.READY: - this.stopBackoff(); - break; - case connectivity_state_1.ConnectivityState.CONNECTING: - this.startBackoff(); - this.startConnectingInternal(); - this.continueConnecting = false; - break; - case connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE: - if (this.channelzEnabled && this.transport) { - this.childrenTracker.unrefChild(this.transport.getChannelzRef()); - } - (_a = this.transport) === null || _a === void 0 ? void 0 : _a.shutdown(); - this.transport = null; - if (!this.backoffTimeout.isRunning()) { - process.nextTick(() => { - this.handleBackoffTimer(); - }); - } - break; - case connectivity_state_1.ConnectivityState.IDLE: - if (this.channelzEnabled && this.transport) { - this.childrenTracker.unrefChild(this.transport.getChannelzRef()); - } - (_b = this.transport) === null || _b === void 0 ? void 0 : _b.shutdown(); - this.transport = null; - break; - default: - throw new Error(`Invalid state: unknown ConnectivityState ${newState}`); - } - for (const listener of this.stateListeners) { - listener(this, previousState, newState, this.keepaliveTime, errorMessage); - } - return true; - } - ref() { - this.refTrace("refcount " + this.refcount + " -> " + (this.refcount + 1)); - this.refcount += 1; - } - unref() { - this.refTrace("refcount " + this.refcount + " -> " + (this.refcount - 1)); - this.refcount -= 1; - if (this.refcount === 0) { - this.channelzTrace.addTrace("CT_INFO", "Shutting down"); - (0, channelz_1.unregisterChannelzRef)(this.channelzRef); - this.secureConnector.destroy(); - process.nextTick(() => { - this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING, connectivity_state_1.ConnectivityState.READY], connectivity_state_1.ConnectivityState.IDLE); - }); - } - } - unrefIfOneRef() { - if (this.refcount === 1) { - this.unref(); - return true; - } - return false; - } - createCall(metadata, host, method, listener) { - if (!this.transport) { - throw new Error("Cannot create call, subchannel not READY"); - } - let statsTracker; - if (this.channelzEnabled) { - this.callTracker.addCallStarted(); - this.streamTracker.addCallStarted(); - statsTracker = { - onCallEnd: (status) => { - if (status.code === constants_1.Status.OK) { - this.callTracker.addCallSucceeded(); - } else { - this.callTracker.addCallFailed(); - } - } - }; - } else { - statsTracker = {}; - } - return this.transport.createCall(metadata, host, method, listener, statsTracker); - } - /** - * If the subchannel is currently IDLE, start connecting and switch to the - * CONNECTING state. If the subchannel is current in TRANSIENT_FAILURE, - * the next time it would transition to IDLE, start connecting again instead. - * Otherwise, do nothing. - */ - startConnecting() { - process.nextTick(() => { - if (!this.transitionToState([connectivity_state_1.ConnectivityState.IDLE], connectivity_state_1.ConnectivityState.CONNECTING)) { - if (this.connectivityState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { - this.continueConnecting = true; - } - } - }); - } - /** - * Get the subchannel's current connectivity state. - */ - getConnectivityState() { - return this.connectivityState; - } - /** - * Add a listener function to be called whenever the subchannel's - * connectivity state changes. - * @param listener - */ - addConnectivityStateListener(listener) { - this.stateListeners.add(listener); - } - /** - * Remove a listener previously added with `addConnectivityStateListener` - * @param listener A reference to a function previously passed to - * `addConnectivityStateListener` - */ - removeConnectivityStateListener(listener) { - this.stateListeners.delete(listener); - } - /** - * Reset the backoff timeout, and immediately start connecting if in backoff. - */ - resetBackoff() { - process.nextTick(() => { - this.backoffTimeout.reset(); - this.transitionToState([connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE], connectivity_state_1.ConnectivityState.CONNECTING); - }); - } - getAddress() { - return this.subchannelAddressString; - } - getChannelzRef() { - return this.channelzRef; - } - isHealthy() { - return true; - } - addHealthStateWatcher(listener) { - } - removeHealthStateWatcher(listener) { - } - getRealSubchannel() { - return this; - } - realSubchannelEquals(other) { - return other.getRealSubchannel() === this; - } - throttleKeepalive(newKeepaliveTime) { - if (newKeepaliveTime > this.keepaliveTime) { - this.keepaliveTime = newKeepaliveTime; - } - } - getCallCredentials() { - return this.secureConnector.getCallCredentials(); - } - getChannel() { - if (!this.subchannelChannel) { - this.subchannelChannel = new single_subchannel_channel_1.SingleSubchannelChannel(this, this.channelTarget, this.options); - } - return this.subchannelChannel; - } - addDataWatcher(dataWatcher) { - throw new Error("Not implemented"); - } - getOrCreateDataProducer(name, createDataProducer) { - const existingProducer = this.dataProducers.get(name); - if (existingProducer) { - return existingProducer; - } - const newProducer = createDataProducer(this); - this.dataProducers.set(name, newProducer); - return newProducer; - } - removeDataProducer(name) { - this.dataProducers.delete(name); - } - }; - exports2.Subchannel = Subchannel; - } -}); - -// node_modules/@grpc/grpc-js/build/src/environment.js -var require_environment = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/environment.js"(exports2) { - "use strict"; - var _a; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.GRPC_NODE_USE_ALTERNATIVE_RESOLVER = void 0; - exports2.GRPC_NODE_USE_ALTERNATIVE_RESOLVER = ((_a = process.env.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) !== null && _a !== void 0 ? _a : "false") === "true"; - } -}); - -// node_modules/@grpc/grpc-js/build/src/resolver-dns.js -var require_resolver_dns = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/resolver-dns.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DEFAULT_PORT = void 0; - exports2.setup = setup; - var resolver_1 = require_resolver(); - var dns_1 = require("dns"); - var service_config_1 = require_service_config(); - var constants_1 = require_constants7(); - var call_interface_1 = require_call_interface(); - var metadata_1 = require_metadata(); - var logging = require_logging(); - var constants_2 = require_constants7(); - var uri_parser_1 = require_uri_parser(); - var net_1 = require("net"); - var backoff_timeout_1 = require_backoff_timeout(); - var environment_1 = require_environment(); - var TRACER_NAME = "dns_resolver"; - function trace(text) { - logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, text); - } - exports2.DEFAULT_PORT = 443; - var DEFAULT_MIN_TIME_BETWEEN_RESOLUTIONS_MS = 3e4; - var DnsResolver = class { - constructor(target, listener, channelOptions) { - var _a, _b, _c; - this.target = target; - this.listener = listener; - this.pendingLookupPromise = null; - this.pendingTxtPromise = null; - this.latestLookupResult = null; - this.latestServiceConfigResult = null; - this.continueResolving = false; - this.isNextResolutionTimerRunning = false; - this.isServiceConfigEnabled = true; - this.returnedIpResult = false; - this.alternativeResolver = new dns_1.promises.Resolver(); - trace("Resolver constructed for target " + (0, uri_parser_1.uriToString)(target)); - if (target.authority) { - this.alternativeResolver.setServers([target.authority]); - } - const hostPort = (0, uri_parser_1.splitHostPort)(target.path); - if (hostPort === null) { - this.ipResult = null; - this.dnsHostname = null; - this.port = null; - } else { - if ((0, net_1.isIPv4)(hostPort.host) || (0, net_1.isIPv6)(hostPort.host)) { - this.ipResult = [ - { - addresses: [ - { - host: hostPort.host, - port: (_a = hostPort.port) !== null && _a !== void 0 ? _a : exports2.DEFAULT_PORT - } - ] - } - ]; - this.dnsHostname = null; - this.port = null; - } else { - this.ipResult = null; - this.dnsHostname = hostPort.host; - this.port = (_b = hostPort.port) !== null && _b !== void 0 ? _b : exports2.DEFAULT_PORT; - } - } - this.percentage = Math.random() * 100; - if (channelOptions["grpc.service_config_disable_resolution"] === 1) { - this.isServiceConfigEnabled = false; - } - this.defaultResolutionError = { - code: constants_1.Status.UNAVAILABLE, - details: `Name resolution failed for target ${(0, uri_parser_1.uriToString)(this.target)}`, - metadata: new metadata_1.Metadata() - }; - const backoffOptions = { - initialDelay: channelOptions["grpc.initial_reconnect_backoff_ms"], - maxDelay: channelOptions["grpc.max_reconnect_backoff_ms"] - }; - this.backoff = new backoff_timeout_1.BackoffTimeout(() => { - if (this.continueResolving) { - this.startResolutionWithBackoff(); - } - }, backoffOptions); - this.backoff.unref(); - this.minTimeBetweenResolutionsMs = (_c = channelOptions["grpc.dns_min_time_between_resolutions_ms"]) !== null && _c !== void 0 ? _c : DEFAULT_MIN_TIME_BETWEEN_RESOLUTIONS_MS; - this.nextResolutionTimer = setTimeout(() => { - }, 0); - clearTimeout(this.nextResolutionTimer); - } - /** - * If the target is an IP address, just provide that address as a result. - * Otherwise, initiate A, AAAA, and TXT lookups - */ - startResolution() { - if (this.ipResult !== null) { - if (!this.returnedIpResult) { - trace("Returning IP address for target " + (0, uri_parser_1.uriToString)(this.target)); - setImmediate(() => { - this.listener((0, call_interface_1.statusOrFromValue)(this.ipResult), {}, null, ""); - }); - this.returnedIpResult = true; - } - this.backoff.stop(); - this.backoff.reset(); - this.stopNextResolutionTimer(); - return; - } - if (this.dnsHostname === null) { - trace("Failed to parse DNS address " + (0, uri_parser_1.uriToString)(this.target)); - setImmediate(() => { - this.listener((0, call_interface_1.statusOrFromError)({ - code: constants_1.Status.UNAVAILABLE, - details: `Failed to parse DNS address ${(0, uri_parser_1.uriToString)(this.target)}` - }), {}, null, ""); - }); - this.stopNextResolutionTimer(); - } else { - if (this.pendingLookupPromise !== null) { - return; - } - trace("Looking up DNS hostname " + this.dnsHostname); - this.latestLookupResult = null; - const hostname = this.dnsHostname; - this.pendingLookupPromise = this.lookup(hostname); - this.pendingLookupPromise.then((addressList) => { - if (this.pendingLookupPromise === null) { - return; - } - this.pendingLookupPromise = null; - this.latestLookupResult = (0, call_interface_1.statusOrFromValue)(addressList.map((address) => ({ - addresses: [address] - }))); - const allAddressesString = "[" + addressList.map((addr) => addr.host + ":" + addr.port).join(",") + "]"; - trace("Resolved addresses for target " + (0, uri_parser_1.uriToString)(this.target) + ": " + allAddressesString); - const healthStatus = this.listener(this.latestLookupResult, {}, this.latestServiceConfigResult, ""); - this.handleHealthStatus(healthStatus); - }, (err) => { - if (this.pendingLookupPromise === null) { - return; - } - trace("Resolution error for target " + (0, uri_parser_1.uriToString)(this.target) + ": " + err.message); - this.pendingLookupPromise = null; - this.stopNextResolutionTimer(); - this.listener((0, call_interface_1.statusOrFromError)(this.defaultResolutionError), {}, this.latestServiceConfigResult, ""); - }); - if (this.isServiceConfigEnabled && this.pendingTxtPromise === null) { - this.pendingTxtPromise = this.resolveTxt(hostname); - this.pendingTxtPromise.then((txtRecord) => { - if (this.pendingTxtPromise === null) { - return; - } - this.pendingTxtPromise = null; - let serviceConfig; - try { - serviceConfig = (0, service_config_1.extractAndSelectServiceConfig)(txtRecord, this.percentage); - if (serviceConfig) { - this.latestServiceConfigResult = (0, call_interface_1.statusOrFromValue)(serviceConfig); - } else { - this.latestServiceConfigResult = null; - } - } catch (err) { - this.latestServiceConfigResult = (0, call_interface_1.statusOrFromError)({ - code: constants_1.Status.UNAVAILABLE, - details: `Parsing service config failed with error ${err.message}` - }); - } - if (this.latestLookupResult !== null) { - this.listener(this.latestLookupResult, {}, this.latestServiceConfigResult, ""); - } - }, (err) => { - }); - } - } - } - /** - * The ResolverListener returns a boolean indicating whether the LB policy - * accepted the resolution result. A false result on an otherwise successful - * resolution should be treated as a resolution failure. - * @param healthStatus - */ - handleHealthStatus(healthStatus) { - if (healthStatus) { - this.backoff.stop(); - this.backoff.reset(); - } else { - this.continueResolving = true; - } - } - async lookup(hostname) { - if (environment_1.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) { - trace("Using alternative DNS resolver."); - const records = await Promise.allSettled([ - this.alternativeResolver.resolve4(hostname), - this.alternativeResolver.resolve6(hostname) - ]); - if (records.every((result) => result.status === "rejected")) { - throw new Error(records[0].reason); - } - return records.reduce((acc, result) => { - return result.status === "fulfilled" ? [...acc, ...result.value] : acc; - }, []).map((addr) => ({ - host: addr, - port: +this.port - })); - } - const addressList = await dns_1.promises.lookup(hostname, { all: true }); - return addressList.map((addr) => ({ host: addr.address, port: +this.port })); - } - async resolveTxt(hostname) { - if (environment_1.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) { - trace("Using alternative DNS resolver."); - return this.alternativeResolver.resolveTxt(hostname); - } - return dns_1.promises.resolveTxt(hostname); - } - startNextResolutionTimer() { - var _a, _b; - clearTimeout(this.nextResolutionTimer); - this.nextResolutionTimer = setTimeout(() => { - this.stopNextResolutionTimer(); - if (this.continueResolving) { - this.startResolutionWithBackoff(); - } - }, this.minTimeBetweenResolutionsMs); - (_b = (_a = this.nextResolutionTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - this.isNextResolutionTimerRunning = true; - } - stopNextResolutionTimer() { - clearTimeout(this.nextResolutionTimer); - this.isNextResolutionTimerRunning = false; - } - startResolutionWithBackoff() { - if (this.pendingLookupPromise === null) { - this.continueResolving = false; - this.backoff.runOnce(); - this.startNextResolutionTimer(); - this.startResolution(); - } - } - updateResolution() { - if (this.pendingLookupPromise === null) { - if (this.isNextResolutionTimerRunning || this.backoff.isRunning()) { - if (this.isNextResolutionTimerRunning) { - trace('resolution update delayed by "min time between resolutions" rate limit'); - } else { - trace("resolution update delayed by backoff timer until " + this.backoff.getEndTime().toISOString()); - } - this.continueResolving = true; - } else { - this.startResolutionWithBackoff(); - } - } - } - /** - * Reset the resolver to the same state it had when it was created. In-flight - * DNS requests cannot be cancelled, but they are discarded and their results - * will be ignored. - */ - destroy() { - this.continueResolving = false; - this.backoff.reset(); - this.backoff.stop(); - this.stopNextResolutionTimer(); - this.pendingLookupPromise = null; - this.pendingTxtPromise = null; - this.latestLookupResult = null; - this.latestServiceConfigResult = null; - this.returnedIpResult = false; - } - /** - * Get the default authority for the given target. For IP targets, that is - * the IP address. For DNS targets, it is the hostname. - * @param target - */ - static getDefaultAuthority(target) { - return target.path; - } - }; - function setup() { - (0, resolver_1.registerResolver)("dns", DnsResolver); - (0, resolver_1.registerDefaultScheme)("dns"); - } - } -}); - -// node_modules/@grpc/grpc-js/build/src/http_proxy.js -var require_http_proxy = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/http_proxy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.parseCIDR = parseCIDR; - exports2.mapProxyName = mapProxyName; - exports2.getProxiedConnection = getProxiedConnection; - var logging_1 = require_logging(); - var constants_1 = require_constants7(); - var net_1 = require("net"); - var http2 = require("http"); - var logging = require_logging(); - var subchannel_address_1 = require_subchannel_address(); - var uri_parser_1 = require_uri_parser(); - var url_1 = require("url"); - var resolver_dns_1 = require_resolver_dns(); - var TRACER_NAME = "proxy"; - function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); - } - function getProxyInfo() { - let proxyEnv = ""; - let envVar = ""; - if (process.env.grpc_proxy) { - envVar = "grpc_proxy"; - proxyEnv = process.env.grpc_proxy; - } else if (process.env.https_proxy) { - envVar = "https_proxy"; - proxyEnv = process.env.https_proxy; - } else if (process.env.http_proxy) { - envVar = "http_proxy"; - proxyEnv = process.env.http_proxy; - } else { - return {}; - } - let proxyUrl; - try { - proxyUrl = new url_1.URL(proxyEnv); - } catch (e) { - (0, logging_1.log)(constants_1.LogVerbosity.ERROR, `cannot parse value of "${envVar}" env var`); - return {}; - } - if (proxyUrl.protocol !== "http:") { - (0, logging_1.log)(constants_1.LogVerbosity.ERROR, `"${proxyUrl.protocol}" scheme not supported in proxy URI`); - return {}; - } - let userCred = null; - if (proxyUrl.username) { - if (proxyUrl.password) { - (0, logging_1.log)(constants_1.LogVerbosity.INFO, "userinfo found in proxy URI"); - userCred = decodeURIComponent(`${proxyUrl.username}:${proxyUrl.password}`); - } else { - userCred = proxyUrl.username; - } - } - const hostname = proxyUrl.hostname; - let port = proxyUrl.port; - if (port === "") { - port = "80"; - } - const result = { - address: `${hostname}:${port}` - }; - if (userCred) { - result.creds = userCred; - } - trace("Proxy server " + result.address + " set by environment variable " + envVar); - return result; - } - function getNoProxyHostList() { - let noProxyStr = process.env.no_grpc_proxy; - let envVar = "no_grpc_proxy"; - if (!noProxyStr) { - noProxyStr = process.env.no_proxy; - envVar = "no_proxy"; - } - if (noProxyStr) { - trace("No proxy server list set by environment variable " + envVar); - return noProxyStr.split(","); - } else { - return []; - } - } - function parseCIDR(cidrString) { - const splitRange = cidrString.split("/"); - if (splitRange.length !== 2) { - return null; - } - const prefixLength = parseInt(splitRange[1], 10); - if (!(0, net_1.isIPv4)(splitRange[0]) || Number.isNaN(prefixLength) || prefixLength < 0 || prefixLength > 32) { - return null; - } - return { - ip: ipToInt(splitRange[0]), - prefixLength - }; - } - function ipToInt(ip) { - return ip.split(".").reduce((acc, octet) => (acc << 8) + parseInt(octet, 10), 0); - } - function isIpInCIDR(cidr, serverHost) { - const ip = cidr.ip; - const mask = -1 << 32 - cidr.prefixLength; - const hostIP = ipToInt(serverHost); - return (hostIP & mask) === (ip & mask); - } - function hostMatchesNoProxyList(serverHost) { - for (const host of getNoProxyHostList()) { - const parsedCIDR = parseCIDR(host); - if ((0, net_1.isIPv4)(serverHost) && parsedCIDR && isIpInCIDR(parsedCIDR, serverHost)) { - return true; - } else if (serverHost.endsWith(host)) { - return true; - } - } - return false; - } - function mapProxyName(target, options) { - var _a; - const noProxyResult = { - target, - extraOptions: {} - }; - if (((_a = options["grpc.enable_http_proxy"]) !== null && _a !== void 0 ? _a : 1) === 0) { - return noProxyResult; - } - if (target.scheme === "unix") { - return noProxyResult; - } - const proxyInfo = getProxyInfo(); - if (!proxyInfo.address) { - return noProxyResult; - } - const hostPort = (0, uri_parser_1.splitHostPort)(target.path); - if (!hostPort) { - return noProxyResult; - } - const serverHost = hostPort.host; - if (hostMatchesNoProxyList(serverHost)) { - trace("Not using proxy for target in no_proxy list: " + (0, uri_parser_1.uriToString)(target)); - return noProxyResult; - } - const extraOptions = { - "grpc.http_connect_target": (0, uri_parser_1.uriToString)(target) - }; - if (proxyInfo.creds) { - extraOptions["grpc.http_connect_creds"] = proxyInfo.creds; - } - return { - target: { - scheme: "dns", - path: proxyInfo.address - }, - extraOptions - }; - } - function getProxiedConnection(address, channelOptions) { - var _a; - if (!("grpc.http_connect_target" in channelOptions)) { - return Promise.resolve(null); - } - const realTarget = channelOptions["grpc.http_connect_target"]; - const parsedTarget = (0, uri_parser_1.parseUri)(realTarget); - if (parsedTarget === null) { - return Promise.resolve(null); - } - const splitHostPost = (0, uri_parser_1.splitHostPort)(parsedTarget.path); - if (splitHostPost === null) { - return Promise.resolve(null); - } - const hostPort = `${splitHostPost.host}:${(_a = splitHostPost.port) !== null && _a !== void 0 ? _a : resolver_dns_1.DEFAULT_PORT}`; - const options = { - method: "CONNECT", - path: hostPort - }; - const headers = { - Host: hostPort - }; - if ((0, subchannel_address_1.isTcpSubchannelAddress)(address)) { - options.host = address.host; - options.port = address.port; - } else { - options.socketPath = address.path; - } - if ("grpc.http_connect_creds" in channelOptions) { - headers["Proxy-Authorization"] = "Basic " + Buffer.from(channelOptions["grpc.http_connect_creds"]).toString("base64"); - } - options.headers = headers; - const proxyAddressString = (0, subchannel_address_1.subchannelAddressToString)(address); - trace("Using proxy " + proxyAddressString + " to connect to " + options.path); - return new Promise((resolve, reject) => { - const request2 = http2.request(options); - request2.once("connect", (res, socket, head) => { - request2.removeAllListeners(); - socket.removeAllListeners(); - if (res.statusCode === 200) { - trace("Successfully connected to " + options.path + " through proxy " + proxyAddressString); - if (head.length > 0) { - socket.unshift(head); - } - trace("Successfully established a plaintext connection to " + options.path + " through proxy " + proxyAddressString); - resolve(socket); - } else { - (0, logging_1.log)(constants_1.LogVerbosity.ERROR, "Failed to connect to " + options.path + " through proxy " + proxyAddressString + " with status " + res.statusCode); - reject(); - } - }); - request2.once("error", (err) => { - request2.removeAllListeners(); - (0, logging_1.log)(constants_1.LogVerbosity.ERROR, "Failed to connect to proxy " + proxyAddressString + " with error " + err.message); - reject(); - }); - request2.end(); - }); - } - } -}); - -// node_modules/@grpc/grpc-js/build/src/stream-decoder.js -var require_stream_decoder = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/stream-decoder.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.StreamDecoder = void 0; - var ReadState; - (function(ReadState2) { - ReadState2[ReadState2["NO_DATA"] = 0] = "NO_DATA"; - ReadState2[ReadState2["READING_SIZE"] = 1] = "READING_SIZE"; - ReadState2[ReadState2["READING_MESSAGE"] = 2] = "READING_MESSAGE"; - })(ReadState || (ReadState = {})); - var StreamDecoder = class { - constructor(maxReadMessageLength) { - this.maxReadMessageLength = maxReadMessageLength; - this.readState = ReadState.NO_DATA; - this.readCompressFlag = Buffer.alloc(1); - this.readPartialSize = Buffer.alloc(4); - this.readSizeRemaining = 4; - this.readMessageSize = 0; - this.readPartialMessage = []; - this.readMessageRemaining = 0; - } - write(data) { - let readHead = 0; - let toRead; - const result = []; - while (readHead < data.length) { - switch (this.readState) { - case ReadState.NO_DATA: - this.readCompressFlag = data.slice(readHead, readHead + 1); - readHead += 1; - this.readState = ReadState.READING_SIZE; - this.readPartialSize.fill(0); - this.readSizeRemaining = 4; - this.readMessageSize = 0; - this.readMessageRemaining = 0; - this.readPartialMessage = []; - break; - case ReadState.READING_SIZE: - toRead = Math.min(data.length - readHead, this.readSizeRemaining); - data.copy(this.readPartialSize, 4 - this.readSizeRemaining, readHead, readHead + toRead); - this.readSizeRemaining -= toRead; - readHead += toRead; - if (this.readSizeRemaining === 0) { - this.readMessageSize = this.readPartialSize.readUInt32BE(0); - if (this.maxReadMessageLength !== -1 && this.readMessageSize > this.maxReadMessageLength) { - throw new Error(`Received message larger than max (${this.readMessageSize} vs ${this.maxReadMessageLength})`); - } - this.readMessageRemaining = this.readMessageSize; - if (this.readMessageRemaining > 0) { - this.readState = ReadState.READING_MESSAGE; - } else { - const message = Buffer.concat([this.readCompressFlag, this.readPartialSize], 5); - this.readState = ReadState.NO_DATA; - result.push(message); - } - } - break; - case ReadState.READING_MESSAGE: - toRead = Math.min(data.length - readHead, this.readMessageRemaining); - this.readPartialMessage.push(data.slice(readHead, readHead + toRead)); - this.readMessageRemaining -= toRead; - readHead += toRead; - if (this.readMessageRemaining === 0) { - const framedMessageBuffers = [ - this.readCompressFlag, - this.readPartialSize - ].concat(this.readPartialMessage); - const framedMessage = Buffer.concat(framedMessageBuffers, this.readMessageSize + 5); - this.readState = ReadState.NO_DATA; - result.push(framedMessage); - } - break; - default: - throw new Error("Unexpected read state"); - } - } - return result; - } - }; - exports2.StreamDecoder = StreamDecoder; - } -}); - -// node_modules/@grpc/grpc-js/build/src/subchannel-call.js -var require_subchannel_call = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/subchannel-call.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Http2SubchannelCall = void 0; - var http2 = require("http2"); - var os = require("os"); - var constants_1 = require_constants7(); - var metadata_1 = require_metadata(); - var stream_decoder_1 = require_stream_decoder(); - var logging = require_logging(); - var constants_2 = require_constants7(); - var TRACER_NAME = "subchannel_call"; - function getSystemErrorName(errno) { - for (const [name, num] of Object.entries(os.constants.errno)) { - if (num === errno) { - return name; - } - } - return "Unknown system error " + errno; - } - function mapHttpStatusCode(code) { - const details = `Received HTTP status code ${code}`; - let mappedStatusCode; - switch (code) { - // TODO(murgatroid99): handle 100 and 101 - case 400: - mappedStatusCode = constants_1.Status.INTERNAL; - break; - case 401: - mappedStatusCode = constants_1.Status.UNAUTHENTICATED; - break; - case 403: - mappedStatusCode = constants_1.Status.PERMISSION_DENIED; - break; - case 404: - mappedStatusCode = constants_1.Status.UNIMPLEMENTED; - break; - case 429: - case 502: - case 503: - case 504: - mappedStatusCode = constants_1.Status.UNAVAILABLE; - break; - default: - mappedStatusCode = constants_1.Status.UNKNOWN; - } - return { - code: mappedStatusCode, - details, - metadata: new metadata_1.Metadata() - }; - } - var Http2SubchannelCall = class { - constructor(http2Stream, callEventTracker, listener, transport, callId) { - var _a; - this.http2Stream = http2Stream; - this.callEventTracker = callEventTracker; - this.listener = listener; - this.transport = transport; - this.callId = callId; - this.isReadFilterPending = false; - this.isPushPending = false; - this.canPush = false; - this.readsClosed = false; - this.statusOutput = false; - this.unpushedReadMessages = []; - this.finalStatus = null; - this.internalError = null; - this.serverEndedCall = false; - this.connectionDropped = false; - const maxReceiveMessageLength = (_a = transport.getOptions()["grpc.max_receive_message_length"]) !== null && _a !== void 0 ? _a : constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH; - this.decoder = new stream_decoder_1.StreamDecoder(maxReceiveMessageLength); - http2Stream.on("response", (headers, flags) => { - let headersString = ""; - for (const header of Object.keys(headers)) { - headersString += " " + header + ": " + headers[header] + "\n"; - } - this.trace("Received server headers:\n" + headersString); - this.httpStatusCode = headers[":status"]; - if (flags & http2.constants.NGHTTP2_FLAG_END_STREAM) { - this.handleTrailers(headers); - } else { - let metadata; - try { - metadata = metadata_1.Metadata.fromHttp2Headers(headers); - } catch (error3) { - this.endCall({ - code: constants_1.Status.UNKNOWN, - details: error3.message, - metadata: new metadata_1.Metadata() - }); - return; - } - this.listener.onReceiveMetadata(metadata); - } - }); - http2Stream.on("trailers", (headers) => { - this.handleTrailers(headers); - }); - http2Stream.on("data", (data) => { - if (this.statusOutput) { - return; - } - this.trace("receive HTTP/2 data frame of length " + data.length); - let messages; - try { - messages = this.decoder.write(data); - } catch (e) { - if (this.httpStatusCode !== void 0 && this.httpStatusCode !== 200) { - const mappedStatus = mapHttpStatusCode(this.httpStatusCode); - this.cancelWithStatus(mappedStatus.code, mappedStatus.details); - } else { - this.cancelWithStatus(constants_1.Status.RESOURCE_EXHAUSTED, e.message); - } - return; - } - for (const message of messages) { - this.trace("parsed message of length " + message.length); - this.callEventTracker.addMessageReceived(); - this.tryPush(message); - } - }); - http2Stream.on("end", () => { - this.readsClosed = true; - this.maybeOutputStatus(); - }); - http2Stream.on("close", () => { - this.serverEndedCall = true; - process.nextTick(() => { - var _a2; - this.trace("HTTP/2 stream closed with code " + http2Stream.rstCode); - if (((_a2 = this.finalStatus) === null || _a2 === void 0 ? void 0 : _a2.code) === constants_1.Status.OK) { - return; - } - let code; - let details = ""; - switch (http2Stream.rstCode) { - case http2.constants.NGHTTP2_NO_ERROR: - if (this.finalStatus !== null) { - return; - } - if (this.httpStatusCode && this.httpStatusCode !== 200) { - const mappedStatus = mapHttpStatusCode(this.httpStatusCode); - code = mappedStatus.code; - details = mappedStatus.details; - } else { - code = constants_1.Status.INTERNAL; - details = `Received RST_STREAM with code ${http2Stream.rstCode} (Call ended without gRPC status)`; - } - break; - case http2.constants.NGHTTP2_REFUSED_STREAM: - code = constants_1.Status.UNAVAILABLE; - details = "Stream refused by server"; - break; - case http2.constants.NGHTTP2_CANCEL: - if (this.connectionDropped) { - code = constants_1.Status.UNAVAILABLE; - details = "Connection dropped"; - } else { - code = constants_1.Status.CANCELLED; - details = "Call cancelled"; - } - break; - case http2.constants.NGHTTP2_ENHANCE_YOUR_CALM: - code = constants_1.Status.RESOURCE_EXHAUSTED; - details = "Bandwidth exhausted or memory limit exceeded"; - break; - case http2.constants.NGHTTP2_INADEQUATE_SECURITY: - code = constants_1.Status.PERMISSION_DENIED; - details = "Protocol not secure enough"; - break; - case http2.constants.NGHTTP2_INTERNAL_ERROR: - code = constants_1.Status.INTERNAL; - if (this.internalError === null) { - details = `Received RST_STREAM with code ${http2Stream.rstCode} (Internal server error)`; - } else { - if (this.internalError.code === "ECONNRESET" || this.internalError.code === "ETIMEDOUT") { - code = constants_1.Status.UNAVAILABLE; - details = this.internalError.message; - } else { - details = `Received RST_STREAM with code ${http2Stream.rstCode} triggered by internal client error: ${this.internalError.message}`; - } - } - break; - default: - code = constants_1.Status.INTERNAL; - details = `Received RST_STREAM with code ${http2Stream.rstCode}`; - } - this.endCall({ - code, - details, - metadata: new metadata_1.Metadata(), - rstCode: http2Stream.rstCode - }); - }); - }); - http2Stream.on("error", (err) => { - if (err.code !== "ERR_HTTP2_STREAM_ERROR") { - this.trace("Node error event: message=" + err.message + " code=" + err.code + " errno=" + getSystemErrorName(err.errno) + " syscall=" + err.syscall); - this.internalError = err; - } - this.callEventTracker.onStreamEnd(false); - }); - } - getDeadlineInfo() { - return [`remote_addr=${this.getPeer()}`]; - } - onDisconnect() { - this.connectionDropped = true; - setImmediate(() => { - this.endCall({ - code: constants_1.Status.UNAVAILABLE, - details: "Connection dropped", - metadata: new metadata_1.Metadata() - }); - }); - } - outputStatus() { - if (!this.statusOutput) { - this.statusOutput = true; - this.trace("ended with status: code=" + this.finalStatus.code + ' details="' + this.finalStatus.details + '"'); - this.callEventTracker.onCallEnd(this.finalStatus); - process.nextTick(() => { - this.listener.onReceiveStatus(this.finalStatus); - }); - this.http2Stream.resume(); - } - } - trace(text) { - logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callId + "] " + text); - } - /** - * On first call, emits a 'status' event with the given StatusObject. - * Subsequent calls are no-ops. - * @param status The status of the call. - */ - endCall(status) { - if (this.finalStatus === null || this.finalStatus.code === constants_1.Status.OK) { - this.finalStatus = status; - this.maybeOutputStatus(); - } - this.destroyHttp2Stream(); - } - maybeOutputStatus() { - if (this.finalStatus !== null) { - if (this.finalStatus.code !== constants_1.Status.OK || this.readsClosed && this.unpushedReadMessages.length === 0 && !this.isReadFilterPending && !this.isPushPending) { - this.outputStatus(); - } - } - } - push(message) { - this.trace("pushing to reader message of length " + (message instanceof Buffer ? message.length : null)); - this.canPush = false; - this.isPushPending = true; - process.nextTick(() => { - this.isPushPending = false; - if (this.statusOutput) { - return; - } - this.listener.onReceiveMessage(message); - this.maybeOutputStatus(); - }); - } - tryPush(messageBytes) { - if (this.canPush) { - this.http2Stream.pause(); - this.push(messageBytes); - } else { - this.trace("unpushedReadMessages.push message of length " + messageBytes.length); - this.unpushedReadMessages.push(messageBytes); - } - } - handleTrailers(headers) { - this.serverEndedCall = true; - this.callEventTracker.onStreamEnd(true); - let headersString = ""; - for (const header of Object.keys(headers)) { - headersString += " " + header + ": " + headers[header] + "\n"; - } - this.trace("Received server trailers:\n" + headersString); - let metadata; - try { - metadata = metadata_1.Metadata.fromHttp2Headers(headers); - } catch (e) { - metadata = new metadata_1.Metadata(); - } - const metadataMap = metadata.getMap(); - let status; - if (typeof metadataMap["grpc-status"] === "string") { - const receivedStatus = Number(metadataMap["grpc-status"]); - this.trace("received status code " + receivedStatus + " from server"); - metadata.remove("grpc-status"); - let details = ""; - if (typeof metadataMap["grpc-message"] === "string") { - try { - details = decodeURI(metadataMap["grpc-message"]); - } catch (e) { - details = metadataMap["grpc-message"]; - } - metadata.remove("grpc-message"); - this.trace('received status details string "' + details + '" from server'); - } - status = { - code: receivedStatus, - details, - metadata - }; - } else if (this.httpStatusCode) { - status = mapHttpStatusCode(this.httpStatusCode); - status.metadata = metadata; - } else { - status = { - code: constants_1.Status.UNKNOWN, - details: "No status information received", - metadata - }; - } - this.endCall(status); - } - destroyHttp2Stream() { - var _a; - if (this.http2Stream.destroyed) { - return; - } - if (this.serverEndedCall) { - this.http2Stream.end(); - } else { - let code; - if (((_a = this.finalStatus) === null || _a === void 0 ? void 0 : _a.code) === constants_1.Status.OK) { - code = http2.constants.NGHTTP2_NO_ERROR; - } else { - code = http2.constants.NGHTTP2_CANCEL; - } - this.trace("close http2 stream with code " + code); - this.http2Stream.close(code); - } - } - cancelWithStatus(status, details) { - this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"'); - this.endCall({ code: status, details, metadata: new metadata_1.Metadata() }); - } - getStatus() { - return this.finalStatus; - } - getPeer() { - return this.transport.getPeerName(); - } - getCallNumber() { - return this.callId; - } - getAuthContext() { - return this.transport.getAuthContext(); - } - startRead() { - if (this.finalStatus !== null && this.finalStatus.code !== constants_1.Status.OK) { - this.readsClosed = true; - this.maybeOutputStatus(); - return; - } - this.canPush = true; - if (this.unpushedReadMessages.length > 0) { - const nextMessage = this.unpushedReadMessages.shift(); - this.push(nextMessage); - return; - } - this.http2Stream.resume(); - } - sendMessageWithContext(context3, message) { - this.trace("write() called with message of length " + message.length); - const cb = (error3) => { - process.nextTick(() => { - var _a; - let code = constants_1.Status.UNAVAILABLE; - if ((error3 === null || error3 === void 0 ? void 0 : error3.code) === "ERR_STREAM_WRITE_AFTER_END") { - code = constants_1.Status.INTERNAL; - } - if (error3) { - this.cancelWithStatus(code, `Write error: ${error3.message}`); - } - (_a = context3.callback) === null || _a === void 0 ? void 0 : _a.call(context3); - }); - }; - this.trace("sending data chunk of length " + message.length); - this.callEventTracker.addMessageSent(); - try { - this.http2Stream.write(message, cb); - } catch (error3) { - this.endCall({ - code: constants_1.Status.UNAVAILABLE, - details: `Write failed with error ${error3.message}`, - metadata: new metadata_1.Metadata() - }); - } - } - halfClose() { - this.trace("end() called"); - this.trace("calling end() on HTTP/2 stream"); - this.http2Stream.end(); - } - }; - exports2.Http2SubchannelCall = Http2SubchannelCall; - } -}); - -// node_modules/@grpc/grpc-js/build/src/transport.js -var require_transport = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/transport.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Http2SubchannelConnector = void 0; - var http2 = require("http2"); - var tls_1 = require("tls"); - var channelz_1 = require_channelz(); - var constants_1 = require_constants7(); - var http_proxy_1 = require_http_proxy(); - var logging = require_logging(); - var resolver_1 = require_resolver(); - var subchannel_address_1 = require_subchannel_address(); - var uri_parser_1 = require_uri_parser(); - var net = require("net"); - var subchannel_call_1 = require_subchannel_call(); - var call_number_1 = require_call_number(); - var TRACER_NAME = "transport"; - var FLOW_CONTROL_TRACER_NAME = "transport_flowctrl"; - var clientVersion = require_package2().version; - var { HTTP2_HEADER_AUTHORITY, HTTP2_HEADER_CONTENT_TYPE, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_TE, HTTP2_HEADER_USER_AGENT } = http2.constants; - var KEEPALIVE_TIMEOUT_MS = 2e4; - var tooManyPingsData = Buffer.from("too_many_pings", "ascii"); - var Http2Transport = class { - constructor(session, subchannelAddress, options, remoteName) { - this.session = session; - this.options = options; - this.remoteName = remoteName; - this.keepaliveTimer = null; - this.pendingSendKeepalivePing = false; - this.activeCalls = /* @__PURE__ */ new Set(); - this.disconnectListeners = []; - this.disconnectHandled = false; - this.channelzEnabled = true; - this.keepalivesSent = 0; - this.messagesSent = 0; - this.messagesReceived = 0; - this.lastMessageSentTimestamp = null; - this.lastMessageReceivedTimestamp = null; - this.subchannelAddressString = (0, subchannel_address_1.subchannelAddressToString)(subchannelAddress); - if (options["grpc.enable_channelz"] === 0) { - this.channelzEnabled = false; - this.streamTracker = new channelz_1.ChannelzCallTrackerStub(); - } else { - this.streamTracker = new channelz_1.ChannelzCallTracker(); - } - this.channelzRef = (0, channelz_1.registerChannelzSocket)(this.subchannelAddressString, () => this.getChannelzInfo(), this.channelzEnabled); - this.userAgent = [ - options["grpc.primary_user_agent"], - `grpc-node-js/${clientVersion}`, - options["grpc.secondary_user_agent"] - ].filter((e) => e).join(" "); - if ("grpc.keepalive_time_ms" in options) { - this.keepaliveTimeMs = options["grpc.keepalive_time_ms"]; - } else { - this.keepaliveTimeMs = -1; - } - if ("grpc.keepalive_timeout_ms" in options) { - this.keepaliveTimeoutMs = options["grpc.keepalive_timeout_ms"]; - } else { - this.keepaliveTimeoutMs = KEEPALIVE_TIMEOUT_MS; - } - if ("grpc.keepalive_permit_without_calls" in options) { - this.keepaliveWithoutCalls = options["grpc.keepalive_permit_without_calls"] === 1; - } else { - this.keepaliveWithoutCalls = false; - } - session.once("close", () => { - this.trace("session closed"); - this.handleDisconnect(); - }); - session.once("goaway", (errorCode, lastStreamID, opaqueData) => { - let tooManyPings = false; - if (errorCode === http2.constants.NGHTTP2_ENHANCE_YOUR_CALM && opaqueData && opaqueData.equals(tooManyPingsData)) { - tooManyPings = true; - } - this.trace("connection closed by GOAWAY with code " + errorCode + " and data " + (opaqueData === null || opaqueData === void 0 ? void 0 : opaqueData.toString())); - this.reportDisconnectToOwner(tooManyPings); - }); - session.once("error", (error3) => { - this.trace("connection closed with error " + error3.message); - this.handleDisconnect(); - }); - session.socket.once("close", (hadError) => { - this.trace("connection closed. hadError=" + hadError); - this.handleDisconnect(); - }); - if (logging.isTracerEnabled(TRACER_NAME)) { - session.on("remoteSettings", (settings) => { - this.trace("new settings received" + (this.session !== session ? " on the old connection" : "") + ": " + JSON.stringify(settings)); - }); - session.on("localSettings", (settings) => { - this.trace("local settings acknowledged by remote" + (this.session !== session ? " on the old connection" : "") + ": " + JSON.stringify(settings)); - }); - } - if (this.keepaliveWithoutCalls) { - this.maybeStartKeepalivePingTimer(); - } - if (session.socket instanceof tls_1.TLSSocket) { - this.authContext = { - transportSecurityType: "ssl", - sslPeerCertificate: session.socket.getPeerCertificate() - }; - } else { - this.authContext = {}; - } - } - getChannelzInfo() { - var _a, _b, _c; - const sessionSocket = this.session.socket; - const remoteAddress = sessionSocket.remoteAddress ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.remoteAddress, sessionSocket.remotePort) : null; - const localAddress = sessionSocket.localAddress ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.localAddress, sessionSocket.localPort) : null; - let tlsInfo; - if (this.session.encrypted) { - const tlsSocket = sessionSocket; - const cipherInfo = tlsSocket.getCipher(); - const certificate = tlsSocket.getCertificate(); - const peerCertificate = tlsSocket.getPeerCertificate(); - tlsInfo = { - cipherSuiteStandardName: (_a = cipherInfo.standardName) !== null && _a !== void 0 ? _a : null, - cipherSuiteOtherName: cipherInfo.standardName ? null : cipherInfo.name, - localCertificate: certificate && "raw" in certificate ? certificate.raw : null, - remoteCertificate: peerCertificate && "raw" in peerCertificate ? peerCertificate.raw : null - }; - } else { - tlsInfo = null; - } - const socketInfo = { - remoteAddress, - localAddress, - security: tlsInfo, - remoteName: this.remoteName, - streamsStarted: this.streamTracker.callsStarted, - streamsSucceeded: this.streamTracker.callsSucceeded, - streamsFailed: this.streamTracker.callsFailed, - messagesSent: this.messagesSent, - messagesReceived: this.messagesReceived, - keepAlivesSent: this.keepalivesSent, - lastLocalStreamCreatedTimestamp: this.streamTracker.lastCallStartedTimestamp, - lastRemoteStreamCreatedTimestamp: null, - lastMessageSentTimestamp: this.lastMessageSentTimestamp, - lastMessageReceivedTimestamp: this.lastMessageReceivedTimestamp, - localFlowControlWindow: (_b = this.session.state.localWindowSize) !== null && _b !== void 0 ? _b : null, - remoteFlowControlWindow: (_c = this.session.state.remoteWindowSize) !== null && _c !== void 0 ? _c : null - }; - return socketInfo; - } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); - } - keepaliveTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, "keepalive", "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); - } - flowControlTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, FLOW_CONTROL_TRACER_NAME, "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); - } - internalsTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, "transport_internals", "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); - } - /** - * Indicate to the owner of this object that this transport should no longer - * be used. That happens if the connection drops, or if the server sends a - * GOAWAY. - * @param tooManyPings If true, this was triggered by a GOAWAY with data - * indicating that the session was closed becaues the client sent too many - * pings. - * @returns - */ - reportDisconnectToOwner(tooManyPings) { - if (this.disconnectHandled) { - return; - } - this.disconnectHandled = true; - this.disconnectListeners.forEach((listener) => listener(tooManyPings)); - } - /** - * Handle connection drops, but not GOAWAYs. - */ - handleDisconnect() { - this.clearKeepaliveTimeout(); - this.reportDisconnectToOwner(false); - for (const call of this.activeCalls) { - call.onDisconnect(); - } - setImmediate(() => { - this.session.destroy(); - }); - } - addDisconnectListener(listener) { - this.disconnectListeners.push(listener); - } - canSendPing() { - return !this.session.destroyed && this.keepaliveTimeMs > 0 && (this.keepaliveWithoutCalls || this.activeCalls.size > 0); - } - maybeSendPing() { - var _a, _b; - if (!this.canSendPing()) { - this.pendingSendKeepalivePing = true; - return; - } - if (this.keepaliveTimer) { - console.error("keepaliveTimeout is not null"); - return; - } - if (this.channelzEnabled) { - this.keepalivesSent += 1; - } - this.keepaliveTrace("Sending ping with timeout " + this.keepaliveTimeoutMs + "ms"); - this.keepaliveTimer = setTimeout(() => { - this.keepaliveTimer = null; - this.keepaliveTrace("Ping timeout passed without response"); - this.handleDisconnect(); - }, this.keepaliveTimeoutMs); - (_b = (_a = this.keepaliveTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - let pingSendError = ""; - try { - const pingSentSuccessfully = this.session.ping((err, duration, payload) => { - this.clearKeepaliveTimeout(); - if (err) { - this.keepaliveTrace("Ping failed with error " + err.message); - this.handleDisconnect(); - } else { - this.keepaliveTrace("Received ping response"); - this.maybeStartKeepalivePingTimer(); - } - }); - if (!pingSentSuccessfully) { - pingSendError = "Ping returned false"; - } - } catch (e) { - pingSendError = (e instanceof Error ? e.message : "") || "Unknown error"; - } - if (pingSendError) { - this.keepaliveTrace("Ping send failed: " + pingSendError); - this.handleDisconnect(); - } - } - /** - * Starts the keepalive ping timer if appropriate. If the timer already ran - * out while there were no active requests, instead send a ping immediately. - * If the ping timer is already running or a ping is currently in flight, - * instead do nothing and wait for them to resolve. - */ - maybeStartKeepalivePingTimer() { - var _a, _b; - if (!this.canSendPing()) { - return; - } - if (this.pendingSendKeepalivePing) { - this.pendingSendKeepalivePing = false; - this.maybeSendPing(); - } else if (!this.keepaliveTimer) { - this.keepaliveTrace("Starting keepalive timer for " + this.keepaliveTimeMs + "ms"); - this.keepaliveTimer = setTimeout(() => { - this.keepaliveTimer = null; - this.maybeSendPing(); - }, this.keepaliveTimeMs); - (_b = (_a = this.keepaliveTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - } - } - /** - * Clears whichever keepalive timeout is currently active, if any. - */ - clearKeepaliveTimeout() { - if (this.keepaliveTimer) { - clearTimeout(this.keepaliveTimer); - this.keepaliveTimer = null; - } - } - removeActiveCall(call) { - this.activeCalls.delete(call); - if (this.activeCalls.size === 0) { - this.session.unref(); - } - } - addActiveCall(call) { - this.activeCalls.add(call); - if (this.activeCalls.size === 1) { - this.session.ref(); - if (!this.keepaliveWithoutCalls) { - this.maybeStartKeepalivePingTimer(); - } - } - } - createCall(metadata, host, method, listener, subchannelCallStatsTracker) { - const headers = metadata.toHttp2Headers(); - headers[HTTP2_HEADER_AUTHORITY] = host; - headers[HTTP2_HEADER_USER_AGENT] = this.userAgent; - headers[HTTP2_HEADER_CONTENT_TYPE] = "application/grpc"; - headers[HTTP2_HEADER_METHOD] = "POST"; - headers[HTTP2_HEADER_PATH] = method; - headers[HTTP2_HEADER_TE] = "trailers"; - let http2Stream; - try { - http2Stream = this.session.request(headers); - } catch (e) { - this.handleDisconnect(); - throw e; - } - this.flowControlTrace("local window size: " + this.session.state.localWindowSize + " remote window size: " + this.session.state.remoteWindowSize); - this.internalsTrace("session.closed=" + this.session.closed + " session.destroyed=" + this.session.destroyed + " session.socket.destroyed=" + this.session.socket.destroyed); - let eventTracker; - let call; - if (this.channelzEnabled) { - this.streamTracker.addCallStarted(); - eventTracker = { - addMessageSent: () => { - var _a; - this.messagesSent += 1; - this.lastMessageSentTimestamp = /* @__PURE__ */ new Date(); - (_a = subchannelCallStatsTracker.addMessageSent) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); - }, - addMessageReceived: () => { - var _a; - this.messagesReceived += 1; - this.lastMessageReceivedTimestamp = /* @__PURE__ */ new Date(); - (_a = subchannelCallStatsTracker.addMessageReceived) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); - }, - onCallEnd: (status) => { - var _a; - (_a = subchannelCallStatsTracker.onCallEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, status); - this.removeActiveCall(call); - }, - onStreamEnd: (success) => { - var _a; - if (success) { - this.streamTracker.addCallSucceeded(); - } else { - this.streamTracker.addCallFailed(); - } - (_a = subchannelCallStatsTracker.onStreamEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, success); - } - }; - } else { - eventTracker = { - addMessageSent: () => { - var _a; - (_a = subchannelCallStatsTracker.addMessageSent) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); - }, - addMessageReceived: () => { - var _a; - (_a = subchannelCallStatsTracker.addMessageReceived) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); - }, - onCallEnd: (status) => { - var _a; - (_a = subchannelCallStatsTracker.onCallEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, status); - this.removeActiveCall(call); - }, - onStreamEnd: (success) => { - var _a; - (_a = subchannelCallStatsTracker.onStreamEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, success); - } - }; - } - call = new subchannel_call_1.Http2SubchannelCall(http2Stream, eventTracker, listener, this, (0, call_number_1.getNextCallNumber)()); - this.addActiveCall(call); - return call; - } - getChannelzRef() { - return this.channelzRef; - } - getPeerName() { - return this.subchannelAddressString; - } - getOptions() { - return this.options; - } - getAuthContext() { - return this.authContext; - } - shutdown() { - this.session.close(); - (0, channelz_1.unregisterChannelzRef)(this.channelzRef); - } - }; - var Http2SubchannelConnector = class { - constructor(channelTarget) { - this.channelTarget = channelTarget; - this.session = null; - this.isShutdown = false; - } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, (0, uri_parser_1.uriToString)(this.channelTarget) + " " + text); - } - createSession(secureConnectResult, address, options) { - if (this.isShutdown) { - return Promise.reject(); - } - if (secureConnectResult.socket.closed) { - return Promise.reject("Connection closed before starting HTTP/2 handshake"); - } - return new Promise((resolve, reject) => { - var _a, _b, _c, _d, _e, _f, _g, _h; - let remoteName = null; - let realTarget = this.channelTarget; - if ("grpc.http_connect_target" in options) { - const parsedTarget = (0, uri_parser_1.parseUri)(options["grpc.http_connect_target"]); - if (parsedTarget) { - realTarget = parsedTarget; - remoteName = (0, uri_parser_1.uriToString)(parsedTarget); - } - } - const scheme = secureConnectResult.secure ? "https" : "http"; - const targetPath = (0, resolver_1.getDefaultAuthority)(realTarget); - const closeHandler = () => { - var _a2; - (_a2 = this.session) === null || _a2 === void 0 ? void 0 : _a2.destroy(); - this.session = null; - setImmediate(() => { - if (!reportedError) { - reportedError = true; - reject(`${errorMessage.trim()} (${(/* @__PURE__ */ new Date()).toISOString()})`); - } - }); - }; - const errorHandler = (error3) => { - var _a2; - (_a2 = this.session) === null || _a2 === void 0 ? void 0 : _a2.destroy(); - errorMessage = error3.message; - this.trace("connection failed with error " + errorMessage); - if (!reportedError) { - reportedError = true; - reject(`${errorMessage} (${(/* @__PURE__ */ new Date()).toISOString()})`); - } - }; - const sessionOptions = { - createConnection: (authority, option) => { - return secureConnectResult.socket; - }, - settings: { - initialWindowSize: (_d = (_a = options["grpc-node.flow_control_window"]) !== null && _a !== void 0 ? _a : (_c = (_b = http2.getDefaultSettings) === null || _b === void 0 ? void 0 : _b.call(http2)) === null || _c === void 0 ? void 0 : _c.initialWindowSize) !== null && _d !== void 0 ? _d : 65535 - }, - maxSendHeaderBlockLength: Number.MAX_SAFE_INTEGER, - /* By default, set a very large max session memory limit, to effectively - * disable enforcement of the limit. Some testing indicates that Node's - * behavior degrades badly when this limit is reached, so we solve that - * by disabling the check entirely. */ - maxSessionMemory: (_e = options["grpc-node.max_session_memory"]) !== null && _e !== void 0 ? _e : Number.MAX_SAFE_INTEGER - }; - const session = http2.connect(`${scheme}://${targetPath}`, sessionOptions); - const defaultWin = (_h = (_g = (_f = http2.getDefaultSettings) === null || _f === void 0 ? void 0 : _f.call(http2)) === null || _g === void 0 ? void 0 : _g.initialWindowSize) !== null && _h !== void 0 ? _h : 65535; - const connWin = options["grpc-node.flow_control_window"]; - this.session = session; - let errorMessage = "Failed to connect"; - let reportedError = false; - session.unref(); - session.once("remoteSettings", () => { - var _a2; - if (connWin && connWin > defaultWin) { - try { - session.setLocalWindowSize(connWin); - } catch (_b2) { - const delta = connWin - ((_a2 = session.state.localWindowSize) !== null && _a2 !== void 0 ? _a2 : defaultWin); - if (delta > 0) - session.incrementWindowSize(delta); - } - } - session.removeAllListeners(); - secureConnectResult.socket.removeListener("close", closeHandler); - secureConnectResult.socket.removeListener("error", errorHandler); - resolve(new Http2Transport(session, address, options, remoteName)); - this.session = null; - }); - session.once("close", closeHandler); - session.once("error", errorHandler); - secureConnectResult.socket.once("close", closeHandler); - secureConnectResult.socket.once("error", errorHandler); - }); - } - tcpConnect(address, options) { - return (0, http_proxy_1.getProxiedConnection)(address, options).then((proxiedSocket) => { - if (proxiedSocket) { - return proxiedSocket; - } else { - return new Promise((resolve, reject) => { - const closeCallback = () => { - reject(new Error("Socket closed")); - }; - const errorCallback = (error3) => { - reject(error3); - }; - const socket = net.connect(address, () => { - socket.removeListener("close", closeCallback); - socket.removeListener("error", errorCallback); - resolve(socket); - }); - socket.once("close", closeCallback); - socket.once("error", errorCallback); - }); - } - }); - } - async connect(address, secureConnector, options) { - if (this.isShutdown) { - return Promise.reject(); - } - let tcpConnection = null; - let secureConnectResult = null; - const addressString = (0, subchannel_address_1.subchannelAddressToString)(address); - try { - this.trace(addressString + " Waiting for secureConnector to be ready"); - await secureConnector.waitForReady(); - this.trace(addressString + " secureConnector is ready"); - tcpConnection = await this.tcpConnect(address, options); - tcpConnection.setNoDelay(); - this.trace(addressString + " Established TCP connection"); - secureConnectResult = await secureConnector.connect(tcpConnection); - this.trace(addressString + " Established secure connection"); - return this.createSession(secureConnectResult, address, options); - } catch (e) { - tcpConnection === null || tcpConnection === void 0 ? void 0 : tcpConnection.destroy(); - secureConnectResult === null || secureConnectResult === void 0 ? void 0 : secureConnectResult.socket.destroy(); - throw e; - } - } - shutdown() { - var _a; - this.isShutdown = true; - (_a = this.session) === null || _a === void 0 ? void 0 : _a.close(); - this.session = null; - } - }; - exports2.Http2SubchannelConnector = Http2SubchannelConnector; - } -}); - -// node_modules/@grpc/grpc-js/build/src/subchannel-pool.js -var require_subchannel_pool = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/subchannel-pool.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.SubchannelPool = void 0; - exports2.getSubchannelPool = getSubchannelPool; - var channel_options_1 = require_channel_options(); - var subchannel_1 = require_subchannel(); - var subchannel_address_1 = require_subchannel_address(); - var uri_parser_1 = require_uri_parser(); - var transport_1 = require_transport(); - var REF_CHECK_INTERVAL = 1e4; - var SubchannelPool = class { - /** - * A pool of subchannels use for making connections. Subchannels with the - * exact same parameters will be reused. - */ - constructor() { - this.pool = /* @__PURE__ */ Object.create(null); - this.cleanupTimer = null; - } - /** - * Unrefs all unused subchannels and cancels the cleanup task if all - * subchannels have been unrefed. - */ - unrefUnusedSubchannels() { - let allSubchannelsUnrefed = true; - for (const channelTarget in this.pool) { - const subchannelObjArray = this.pool[channelTarget]; - const refedSubchannels = subchannelObjArray.filter((value) => !value.subchannel.unrefIfOneRef()); - if (refedSubchannels.length > 0) { - allSubchannelsUnrefed = false; - } - this.pool[channelTarget] = refedSubchannels; - } - if (allSubchannelsUnrefed && this.cleanupTimer !== null) { - clearInterval(this.cleanupTimer); - this.cleanupTimer = null; - } - } - /** - * Ensures that the cleanup task is spawned. - */ - ensureCleanupTask() { - var _a, _b; - if (this.cleanupTimer === null) { - this.cleanupTimer = setInterval(() => { - this.unrefUnusedSubchannels(); - }, REF_CHECK_INTERVAL); - (_b = (_a = this.cleanupTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - } - } - /** - * Get a subchannel if one already exists with exactly matching parameters. - * Otherwise, create and save a subchannel with those parameters. - * @param channelTarget - * @param subchannelTarget - * @param channelArguments - * @param channelCredentials - */ - getOrCreateSubchannel(channelTargetUri, subchannelTarget, channelArguments, channelCredentials) { - this.ensureCleanupTask(); - const channelTarget = (0, uri_parser_1.uriToString)(channelTargetUri); - if (channelTarget in this.pool) { - const subchannelObjArray = this.pool[channelTarget]; - for (const subchannelObj of subchannelObjArray) { - if ((0, subchannel_address_1.subchannelAddressEqual)(subchannelTarget, subchannelObj.subchannelAddress) && (0, channel_options_1.channelOptionsEqual)(channelArguments, subchannelObj.channelArguments) && channelCredentials._equals(subchannelObj.channelCredentials)) { - return subchannelObj.subchannel; - } - } - } - const subchannel = new subchannel_1.Subchannel(channelTargetUri, subchannelTarget, channelArguments, channelCredentials, new transport_1.Http2SubchannelConnector(channelTargetUri)); - if (!(channelTarget in this.pool)) { - this.pool[channelTarget] = []; - } - this.pool[channelTarget].push({ - subchannelAddress: subchannelTarget, - channelArguments, - channelCredentials, - subchannel - }); - subchannel.ref(); - return subchannel; - } - }; - exports2.SubchannelPool = SubchannelPool; - var globalSubchannelPool = new SubchannelPool(); - function getSubchannelPool(global2) { - if (global2) { - return globalSubchannelPool; - } else { - return new SubchannelPool(); - } - } - } -}); - -// node_modules/@grpc/grpc-js/build/src/load-balancing-call.js -var require_load_balancing_call = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/load-balancing-call.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.LoadBalancingCall = void 0; - var connectivity_state_1 = require_connectivity_state(); - var constants_1 = require_constants7(); - var deadline_1 = require_deadline(); - var metadata_1 = require_metadata(); - var picker_1 = require_picker(); - var uri_parser_1 = require_uri_parser(); - var logging = require_logging(); - var control_plane_status_1 = require_control_plane_status(); - var http2 = require("http2"); - var TRACER_NAME = "load_balancing_call"; - var LoadBalancingCall = class { - constructor(channel, callConfig, methodName, host, credentials, deadline, callNumber) { - var _a, _b; - this.channel = channel; - this.callConfig = callConfig; - this.methodName = methodName; - this.host = host; - this.credentials = credentials; - this.deadline = deadline; - this.callNumber = callNumber; - this.child = null; - this.readPending = false; - this.pendingMessage = null; - this.pendingHalfClose = false; - this.ended = false; - this.metadata = null; - this.listener = null; - this.onCallEnded = null; - this.childStartTime = null; - const splitPath = this.methodName.split("/"); - let serviceName = ""; - if (splitPath.length >= 2) { - serviceName = splitPath[1]; - } - const hostname = (_b = (_a = (0, uri_parser_1.splitHostPort)(this.host)) === null || _a === void 0 ? void 0 : _a.host) !== null && _b !== void 0 ? _b : "localhost"; - this.serviceUrl = `https://${hostname}/${serviceName}`; - this.startTime = /* @__PURE__ */ new Date(); - } - getDeadlineInfo() { - var _a, _b; - const deadlineInfo = []; - if (this.childStartTime) { - if (this.childStartTime > this.startTime) { - if ((_a = this.metadata) === null || _a === void 0 ? void 0 : _a.getOptions().waitForReady) { - deadlineInfo.push("wait_for_ready"); - } - deadlineInfo.push(`LB pick: ${(0, deadline_1.formatDateDifference)(this.startTime, this.childStartTime)}`); - } - deadlineInfo.push(...this.child.getDeadlineInfo()); - return deadlineInfo; - } else { - if ((_b = this.metadata) === null || _b === void 0 ? void 0 : _b.getOptions().waitForReady) { - deadlineInfo.push("wait_for_ready"); - } - deadlineInfo.push("Waiting for LB pick"); - } - return deadlineInfo; - } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callNumber + "] " + text); - } - outputStatus(status, progress) { - var _a, _b; - if (!this.ended) { - this.ended = true; - this.trace("ended with status: code=" + status.code + ' details="' + status.details + '" start time=' + this.startTime.toISOString()); - const finalStatus = Object.assign(Object.assign({}, status), { progress }); - (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onReceiveStatus(finalStatus); - (_b = this.onCallEnded) === null || _b === void 0 ? void 0 : _b.call(this, finalStatus.code, finalStatus.details, finalStatus.metadata); - } - } - doPick() { - var _a, _b; - if (this.ended) { - return; - } - if (!this.metadata) { - throw new Error("doPick called before start"); - } - this.trace("Pick called"); - const finalMetadata = this.metadata.clone(); - const pickResult = this.channel.doPick(finalMetadata, this.callConfig.pickInformation); - const subchannelString = pickResult.subchannel ? "(" + pickResult.subchannel.getChannelzRef().id + ") " + pickResult.subchannel.getAddress() : "" + pickResult.subchannel; - this.trace("Pick result: " + picker_1.PickResultType[pickResult.pickResultType] + " subchannel: " + subchannelString + " status: " + ((_a = pickResult.status) === null || _a === void 0 ? void 0 : _a.code) + " " + ((_b = pickResult.status) === null || _b === void 0 ? void 0 : _b.details)); - switch (pickResult.pickResultType) { - case picker_1.PickResultType.COMPLETE: - const combinedCallCredentials = this.credentials.compose(pickResult.subchannel.getCallCredentials()); - combinedCallCredentials.generateMetadata({ method_name: this.methodName, service_url: this.serviceUrl }).then((credsMetadata) => { - var _a2; - if (this.ended) { - this.trace("Credentials metadata generation finished after call ended"); - return; - } - finalMetadata.merge(credsMetadata); - if (finalMetadata.get("authorization").length > 1) { - this.outputStatus({ - code: constants_1.Status.INTERNAL, - details: '"authorization" metadata cannot have multiple values', - metadata: new metadata_1.Metadata() - }, "PROCESSED"); - } - if (pickResult.subchannel.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) { - this.trace("Picked subchannel " + subchannelString + " has state " + connectivity_state_1.ConnectivityState[pickResult.subchannel.getConnectivityState()] + " after getting credentials metadata. Retrying pick"); - this.doPick(); - return; - } - if (this.deadline !== Infinity) { - finalMetadata.set("grpc-timeout", (0, deadline_1.getDeadlineTimeoutString)(this.deadline)); - } - try { - this.child = pickResult.subchannel.getRealSubchannel().createCall(finalMetadata, this.host, this.methodName, { - onReceiveMetadata: (metadata) => { - this.trace("Received metadata"); - this.listener.onReceiveMetadata(metadata); - }, - onReceiveMessage: (message) => { - this.trace("Received message"); - this.listener.onReceiveMessage(message); - }, - onReceiveStatus: (status) => { - this.trace("Received status"); - if (status.rstCode === http2.constants.NGHTTP2_REFUSED_STREAM) { - this.outputStatus(status, "REFUSED"); - } else { - this.outputStatus(status, "PROCESSED"); - } - } - }); - this.childStartTime = /* @__PURE__ */ new Date(); - } catch (error3) { - this.trace("Failed to start call on picked subchannel " + subchannelString + " with error " + error3.message); - this.outputStatus({ - code: constants_1.Status.INTERNAL, - details: "Failed to start HTTP/2 stream with error " + error3.message, - metadata: new metadata_1.Metadata() - }, "NOT_STARTED"); - return; - } - (_a2 = pickResult.onCallStarted) === null || _a2 === void 0 ? void 0 : _a2.call(pickResult); - this.onCallEnded = pickResult.onCallEnded; - this.trace("Created child call [" + this.child.getCallNumber() + "]"); - if (this.readPending) { - this.child.startRead(); - } - if (this.pendingMessage) { - this.child.sendMessageWithContext(this.pendingMessage.context, this.pendingMessage.message); - } - if (this.pendingHalfClose) { - this.child.halfClose(); - } - }, (error3) => { - const { code: code2, details: details2 } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(typeof error3.code === "number" ? error3.code : constants_1.Status.UNKNOWN, `Getting metadata from plugin failed with error: ${error3.message}`); - this.outputStatus({ - code: code2, - details: details2, - metadata: new metadata_1.Metadata() - }, "PROCESSED"); - }); - break; - case picker_1.PickResultType.DROP: - const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(pickResult.status.code, pickResult.status.details); - setImmediate(() => { - this.outputStatus({ code, details, metadata: pickResult.status.metadata }, "DROP"); - }); - break; - case picker_1.PickResultType.TRANSIENT_FAILURE: - if (this.metadata.getOptions().waitForReady) { - this.channel.queueCallForPick(this); - } else { - const { code: code2, details: details2 } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(pickResult.status.code, pickResult.status.details); - setImmediate(() => { - this.outputStatus({ code: code2, details: details2, metadata: pickResult.status.metadata }, "PROCESSED"); - }); - } - break; - case picker_1.PickResultType.QUEUE: - this.channel.queueCallForPick(this); - } - } - cancelWithStatus(status, details) { - var _a; - this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"'); - (_a = this.child) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(status, details); - this.outputStatus({ code: status, details, metadata: new metadata_1.Metadata() }, "PROCESSED"); - } - getPeer() { - var _a, _b; - return (_b = (_a = this.child) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : this.channel.getTarget(); - } - start(metadata, listener) { - this.trace("start called"); - this.listener = listener; - this.metadata = metadata; - this.doPick(); - } - sendMessageWithContext(context3, message) { - this.trace("write() called with message of length " + message.length); - if (this.child) { - this.child.sendMessageWithContext(context3, message); - } else { - this.pendingMessage = { context: context3, message }; - } - } - startRead() { - this.trace("startRead called"); - if (this.child) { - this.child.startRead(); - } else { - this.readPending = true; - } - } - halfClose() { - this.trace("halfClose called"); - if (this.child) { - this.child.halfClose(); - } else { - this.pendingHalfClose = true; - } - } - setCredentials(credentials) { - throw new Error("Method not implemented."); - } - getCallNumber() { - return this.callNumber; - } - getAuthContext() { - if (this.child) { - return this.child.getAuthContext(); - } else { - return null; - } - } - }; - exports2.LoadBalancingCall = LoadBalancingCall; - } -}); - -// node_modules/@grpc/grpc-js/build/src/resolving-call.js -var require_resolving_call = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/resolving-call.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ResolvingCall = void 0; - var call_credentials_1 = require_call_credentials(); - var constants_1 = require_constants7(); - var deadline_1 = require_deadline(); - var metadata_1 = require_metadata(); - var logging = require_logging(); - var control_plane_status_1 = require_control_plane_status(); - var TRACER_NAME = "resolving_call"; - var ResolvingCall = class { - constructor(channel, method, options, filterStackFactory, callNumber) { - this.channel = channel; - this.method = method; - this.filterStackFactory = filterStackFactory; - this.callNumber = callNumber; - this.child = null; - this.readPending = false; - this.pendingMessage = null; - this.pendingHalfClose = false; - this.ended = false; - this.readFilterPending = false; - this.writeFilterPending = false; - this.pendingChildStatus = null; - this.metadata = null; - this.listener = null; - this.statusWatchers = []; - this.deadlineTimer = setTimeout(() => { - }, 0); - this.filterStack = null; - this.deadlineStartTime = null; - this.configReceivedTime = null; - this.childStartTime = null; - this.credentials = call_credentials_1.CallCredentials.createEmpty(); - this.deadline = options.deadline; - this.host = options.host; - if (options.parentCall) { - if (options.flags & constants_1.Propagate.CANCELLATION) { - options.parentCall.on("cancelled", () => { - this.cancelWithStatus(constants_1.Status.CANCELLED, "Cancelled by parent call"); - }); - } - if (options.flags & constants_1.Propagate.DEADLINE) { - this.trace("Propagating deadline from parent: " + options.parentCall.getDeadline()); - this.deadline = (0, deadline_1.minDeadline)(this.deadline, options.parentCall.getDeadline()); - } - } - this.trace("Created"); - this.runDeadlineTimer(); - } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callNumber + "] " + text); - } - runDeadlineTimer() { - clearTimeout(this.deadlineTimer); - this.deadlineStartTime = /* @__PURE__ */ new Date(); - this.trace("Deadline: " + (0, deadline_1.deadlineToString)(this.deadline)); - const timeout = (0, deadline_1.getRelativeTimeout)(this.deadline); - if (timeout !== Infinity) { - this.trace("Deadline will be reached in " + timeout + "ms"); - const handleDeadline = () => { - if (!this.deadlineStartTime) { - this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, "Deadline exceeded"); - return; - } - const deadlineInfo = []; - const deadlineEndTime = /* @__PURE__ */ new Date(); - deadlineInfo.push(`Deadline exceeded after ${(0, deadline_1.formatDateDifference)(this.deadlineStartTime, deadlineEndTime)}`); - if (this.configReceivedTime) { - if (this.configReceivedTime > this.deadlineStartTime) { - deadlineInfo.push(`name resolution: ${(0, deadline_1.formatDateDifference)(this.deadlineStartTime, this.configReceivedTime)}`); - } - if (this.childStartTime) { - if (this.childStartTime > this.configReceivedTime) { - deadlineInfo.push(`metadata filters: ${(0, deadline_1.formatDateDifference)(this.configReceivedTime, this.childStartTime)}`); - } - } else { - deadlineInfo.push("waiting for metadata filters"); - } - } else { - deadlineInfo.push("waiting for name resolution"); - } - if (this.child) { - deadlineInfo.push(...this.child.getDeadlineInfo()); - } - this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, deadlineInfo.join(",")); - }; - if (timeout <= 0) { - process.nextTick(handleDeadline); - } else { - this.deadlineTimer = setTimeout(handleDeadline, timeout); - } - } - } - outputStatus(status) { - if (!this.ended) { - this.ended = true; - if (!this.filterStack) { - this.filterStack = this.filterStackFactory.createFilter(); - } - clearTimeout(this.deadlineTimer); - const filteredStatus = this.filterStack.receiveTrailers(status); - this.trace("ended with status: code=" + filteredStatus.code + ' details="' + filteredStatus.details + '"'); - this.statusWatchers.forEach((watcher) => watcher(filteredStatus)); - process.nextTick(() => { - var _a; - (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onReceiveStatus(filteredStatus); - }); - } - } - sendMessageOnChild(context3, message) { - if (!this.child) { - throw new Error("sendMessageonChild called with child not populated"); - } - const child = this.child; - this.writeFilterPending = true; - this.filterStack.sendMessage(Promise.resolve({ message, flags: context3.flags })).then((filteredMessage) => { - this.writeFilterPending = false; - child.sendMessageWithContext(context3, filteredMessage.message); - if (this.pendingHalfClose) { - child.halfClose(); - } - }, (status) => { - this.cancelWithStatus(status.code, status.details); - }); - } - getConfig() { - if (this.ended) { - return; - } - if (!this.metadata || !this.listener) { - throw new Error("getConfig called before start"); - } - const configResult = this.channel.getConfig(this.method, this.metadata); - if (configResult.type === "NONE") { - this.channel.queueCallForConfig(this); - return; - } else if (configResult.type === "ERROR") { - if (this.metadata.getOptions().waitForReady) { - this.channel.queueCallForConfig(this); - } else { - this.outputStatus(configResult.error); - } - return; - } - this.configReceivedTime = /* @__PURE__ */ new Date(); - const config = configResult.config; - if (config.status !== constants_1.Status.OK) { - const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(config.status, "Failed to route call to method " + this.method); - this.outputStatus({ - code, - details, - metadata: new metadata_1.Metadata() - }); - return; - } - if (config.methodConfig.timeout) { - const configDeadline = /* @__PURE__ */ new Date(); - configDeadline.setSeconds(configDeadline.getSeconds() + config.methodConfig.timeout.seconds); - configDeadline.setMilliseconds(configDeadline.getMilliseconds() + config.methodConfig.timeout.nanos / 1e6); - this.deadline = (0, deadline_1.minDeadline)(this.deadline, configDeadline); - this.runDeadlineTimer(); - } - this.filterStackFactory.push(config.dynamicFilterFactories); - this.filterStack = this.filterStackFactory.createFilter(); - this.filterStack.sendMetadata(Promise.resolve(this.metadata)).then((filteredMetadata) => { - this.child = this.channel.createRetryingCall(config, this.method, this.host, this.credentials, this.deadline); - this.trace("Created child [" + this.child.getCallNumber() + "]"); - this.childStartTime = /* @__PURE__ */ new Date(); - this.child.start(filteredMetadata, { - onReceiveMetadata: (metadata) => { - this.trace("Received metadata"); - this.listener.onReceiveMetadata(this.filterStack.receiveMetadata(metadata)); - }, - onReceiveMessage: (message) => { - this.trace("Received message"); - this.readFilterPending = true; - this.filterStack.receiveMessage(message).then((filteredMesssage) => { - this.trace("Finished filtering received message"); - this.readFilterPending = false; - this.listener.onReceiveMessage(filteredMesssage); - if (this.pendingChildStatus) { - this.outputStatus(this.pendingChildStatus); - } - }, (status) => { - this.cancelWithStatus(status.code, status.details); - }); - }, - onReceiveStatus: (status) => { - this.trace("Received status"); - if (this.readFilterPending) { - this.pendingChildStatus = status; - } else { - this.outputStatus(status); - } - } - }); - if (this.readPending) { - this.child.startRead(); - } - if (this.pendingMessage) { - this.sendMessageOnChild(this.pendingMessage.context, this.pendingMessage.message); - } else if (this.pendingHalfClose) { - this.child.halfClose(); - } - }, (status) => { - this.outputStatus(status); - }); - } - reportResolverError(status) { - var _a; - if ((_a = this.metadata) === null || _a === void 0 ? void 0 : _a.getOptions().waitForReady) { - this.channel.queueCallForConfig(this); - } else { - this.outputStatus(status); - } - } - cancelWithStatus(status, details) { - var _a; - this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"'); - (_a = this.child) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(status, details); - this.outputStatus({ - code: status, - details, - metadata: new metadata_1.Metadata() - }); - } - getPeer() { - var _a, _b; - return (_b = (_a = this.child) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : this.channel.getTarget(); - } - start(metadata, listener) { - this.trace("start called"); - this.metadata = metadata.clone(); - this.listener = listener; - this.getConfig(); - } - sendMessageWithContext(context3, message) { - this.trace("write() called with message of length " + message.length); - if (this.child) { - this.sendMessageOnChild(context3, message); - } else { - this.pendingMessage = { context: context3, message }; - } - } - startRead() { - this.trace("startRead called"); - if (this.child) { - this.child.startRead(); - } else { - this.readPending = true; - } - } - halfClose() { - this.trace("halfClose called"); - if (this.child && !this.writeFilterPending) { - this.child.halfClose(); - } else { - this.pendingHalfClose = true; - } - } - setCredentials(credentials) { - this.credentials = credentials; - } - addStatusWatcher(watcher) { - this.statusWatchers.push(watcher); - } - getCallNumber() { - return this.callNumber; - } - getAuthContext() { - if (this.child) { - return this.child.getAuthContext(); - } else { - return null; - } - } - }; - exports2.ResolvingCall = ResolvingCall; - } -}); - -// node_modules/@grpc/grpc-js/build/src/retrying-call.js -var require_retrying_call = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/retrying-call.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RetryingCall = exports2.MessageBufferTracker = exports2.RetryThrottler = void 0; - var constants_1 = require_constants7(); - var deadline_1 = require_deadline(); - var metadata_1 = require_metadata(); - var logging = require_logging(); - var TRACER_NAME = "retrying_call"; - var RetryThrottler = class { - constructor(maxTokens, tokenRatio, previousRetryThrottler) { - this.maxTokens = maxTokens; - this.tokenRatio = tokenRatio; - if (previousRetryThrottler) { - this.tokens = previousRetryThrottler.tokens * (maxTokens / previousRetryThrottler.maxTokens); - } else { - this.tokens = maxTokens; - } - } - addCallSucceeded() { - this.tokens = Math.min(this.tokens + this.tokenRatio, this.maxTokens); - } - addCallFailed() { - this.tokens = Math.max(this.tokens - 1, 0); - } - canRetryCall() { - return this.tokens > this.maxTokens / 2; - } - }; - exports2.RetryThrottler = RetryThrottler; - var MessageBufferTracker = class { - constructor(totalLimit, limitPerCall) { - this.totalLimit = totalLimit; - this.limitPerCall = limitPerCall; - this.totalAllocated = 0; - this.allocatedPerCall = /* @__PURE__ */ new Map(); - } - allocate(size, callId) { - var _a; - const currentPerCall = (_a = this.allocatedPerCall.get(callId)) !== null && _a !== void 0 ? _a : 0; - if (this.limitPerCall - currentPerCall < size || this.totalLimit - this.totalAllocated < size) { - return false; - } - this.allocatedPerCall.set(callId, currentPerCall + size); - this.totalAllocated += size; - return true; - } - free(size, callId) { - var _a; - if (this.totalAllocated < size) { - throw new Error(`Invalid buffer allocation state: call ${callId} freed ${size} > total allocated ${this.totalAllocated}`); - } - this.totalAllocated -= size; - const currentPerCall = (_a = this.allocatedPerCall.get(callId)) !== null && _a !== void 0 ? _a : 0; - if (currentPerCall < size) { - throw new Error(`Invalid buffer allocation state: call ${callId} freed ${size} > allocated for call ${currentPerCall}`); - } - this.allocatedPerCall.set(callId, currentPerCall - size); - } - freeAll(callId) { - var _a; - const currentPerCall = (_a = this.allocatedPerCall.get(callId)) !== null && _a !== void 0 ? _a : 0; - if (this.totalAllocated < currentPerCall) { - throw new Error(`Invalid buffer allocation state: call ${callId} allocated ${currentPerCall} > total allocated ${this.totalAllocated}`); - } - this.totalAllocated -= currentPerCall; - this.allocatedPerCall.delete(callId); - } - }; - exports2.MessageBufferTracker = MessageBufferTracker; - var PREVIONS_RPC_ATTEMPTS_METADATA_KEY = "grpc-previous-rpc-attempts"; - var DEFAULT_MAX_ATTEMPTS_LIMIT = 5; - var RetryingCall = class { - constructor(channel, callConfig, methodName, host, credentials, deadline, callNumber, bufferTracker, retryThrottler) { - var _a; - this.channel = channel; - this.callConfig = callConfig; - this.methodName = methodName; - this.host = host; - this.credentials = credentials; - this.deadline = deadline; - this.callNumber = callNumber; - this.bufferTracker = bufferTracker; - this.retryThrottler = retryThrottler; - this.listener = null; - this.initialMetadata = null; - this.underlyingCalls = []; - this.writeBuffer = []; - this.writeBufferOffset = 0; - this.readStarted = false; - this.transparentRetryUsed = false; - this.attempts = 0; - this.hedgingTimer = null; - this.committedCallIndex = null; - this.initialRetryBackoffSec = 0; - this.nextRetryBackoffSec = 0; - const maxAttemptsLimit = (_a = channel.getOptions()["grpc-node.retry_max_attempts_limit"]) !== null && _a !== void 0 ? _a : DEFAULT_MAX_ATTEMPTS_LIMIT; - if (channel.getOptions()["grpc.enable_retries"] === 0) { - this.state = "NO_RETRY"; - this.maxAttempts = 1; - } else if (callConfig.methodConfig.retryPolicy) { - this.state = "RETRY"; - const retryPolicy = callConfig.methodConfig.retryPolicy; - this.nextRetryBackoffSec = this.initialRetryBackoffSec = Number(retryPolicy.initialBackoff.substring(0, retryPolicy.initialBackoff.length - 1)); - this.maxAttempts = Math.min(retryPolicy.maxAttempts, maxAttemptsLimit); - } else if (callConfig.methodConfig.hedgingPolicy) { - this.state = "HEDGING"; - this.maxAttempts = Math.min(callConfig.methodConfig.hedgingPolicy.maxAttempts, maxAttemptsLimit); - } else { - this.state = "TRANSPARENT_ONLY"; - this.maxAttempts = 1; - } - this.startTime = /* @__PURE__ */ new Date(); - } - getDeadlineInfo() { - if (this.underlyingCalls.length === 0) { - return []; - } - const deadlineInfo = []; - const latestCall = this.underlyingCalls[this.underlyingCalls.length - 1]; - if (this.underlyingCalls.length > 1) { - deadlineInfo.push(`previous attempts: ${this.underlyingCalls.length - 1}`); - } - if (latestCall.startTime > this.startTime) { - deadlineInfo.push(`time to current attempt start: ${(0, deadline_1.formatDateDifference)(this.startTime, latestCall.startTime)}`); - } - deadlineInfo.push(...latestCall.call.getDeadlineInfo()); - return deadlineInfo; - } - getCallNumber() { - return this.callNumber; - } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callNumber + "] " + text); - } - reportStatus(statusObject) { - this.trace("ended with status: code=" + statusObject.code + ' details="' + statusObject.details + '" start time=' + this.startTime.toISOString()); - this.bufferTracker.freeAll(this.callNumber); - this.writeBufferOffset = this.writeBufferOffset + this.writeBuffer.length; - this.writeBuffer = []; - process.nextTick(() => { - var _a; - (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onReceiveStatus({ - code: statusObject.code, - details: statusObject.details, - metadata: statusObject.metadata - }); - }); - } - cancelWithStatus(status, details) { - this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"'); - this.reportStatus({ code: status, details, metadata: new metadata_1.Metadata() }); - for (const { call } of this.underlyingCalls) { - call.cancelWithStatus(status, details); - } - } - getPeer() { - if (this.committedCallIndex !== null) { - return this.underlyingCalls[this.committedCallIndex].call.getPeer(); - } else { - return "unknown"; - } - } - getBufferEntry(messageIndex) { - var _a; - return (_a = this.writeBuffer[messageIndex - this.writeBufferOffset]) !== null && _a !== void 0 ? _a : { - entryType: "FREED", - allocated: false - }; - } - getNextBufferIndex() { - return this.writeBufferOffset + this.writeBuffer.length; - } - clearSentMessages() { - if (this.state !== "COMMITTED") { - return; - } - let earliestNeededMessageIndex; - if (this.underlyingCalls[this.committedCallIndex].state === "COMPLETED") { - earliestNeededMessageIndex = this.getNextBufferIndex(); - } else { - earliestNeededMessageIndex = this.underlyingCalls[this.committedCallIndex].nextMessageToSend; - } - for (let messageIndex = this.writeBufferOffset; messageIndex < earliestNeededMessageIndex; messageIndex++) { - const bufferEntry = this.getBufferEntry(messageIndex); - if (bufferEntry.allocated) { - this.bufferTracker.free(bufferEntry.message.message.length, this.callNumber); - } - } - this.writeBuffer = this.writeBuffer.slice(earliestNeededMessageIndex - this.writeBufferOffset); - this.writeBufferOffset = earliestNeededMessageIndex; - } - commitCall(index) { - var _a, _b; - if (this.state === "COMMITTED") { - return; - } - this.trace("Committing call [" + this.underlyingCalls[index].call.getCallNumber() + "] at index " + index); - this.state = "COMMITTED"; - (_b = (_a = this.callConfig).onCommitted) === null || _b === void 0 ? void 0 : _b.call(_a); - this.committedCallIndex = index; - for (let i = 0; i < this.underlyingCalls.length; i++) { - if (i === index) { - continue; - } - if (this.underlyingCalls[i].state === "COMPLETED") { - continue; - } - this.underlyingCalls[i].state = "COMPLETED"; - this.underlyingCalls[i].call.cancelWithStatus(constants_1.Status.CANCELLED, "Discarded in favor of other hedged attempt"); - } - this.clearSentMessages(); - } - commitCallWithMostMessages() { - if (this.state === "COMMITTED") { - return; - } - let mostMessages = -1; - let callWithMostMessages = -1; - for (const [index, childCall] of this.underlyingCalls.entries()) { - if (childCall.state === "ACTIVE" && childCall.nextMessageToSend > mostMessages) { - mostMessages = childCall.nextMessageToSend; - callWithMostMessages = index; - } - } - if (callWithMostMessages === -1) { - this.state = "TRANSPARENT_ONLY"; - } else { - this.commitCall(callWithMostMessages); - } - } - isStatusCodeInList(list, code) { - return list.some((value) => { - var _a; - return value === code || value.toString().toLowerCase() === ((_a = constants_1.Status[code]) === null || _a === void 0 ? void 0 : _a.toLowerCase()); - }); - } - getNextRetryJitter() { - return Math.random() * (1.2 - 0.8) + 0.8; - } - getNextRetryBackoffMs() { - var _a; - const retryPolicy = (_a = this.callConfig) === null || _a === void 0 ? void 0 : _a.methodConfig.retryPolicy; - if (!retryPolicy) { - return 0; - } - const jitter = this.getNextRetryJitter(); - const nextBackoffMs = jitter * this.nextRetryBackoffSec * 1e3; - const maxBackoffSec = Number(retryPolicy.maxBackoff.substring(0, retryPolicy.maxBackoff.length - 1)); - this.nextRetryBackoffSec = Math.min(this.nextRetryBackoffSec * retryPolicy.backoffMultiplier, maxBackoffSec); - return nextBackoffMs; - } - maybeRetryCall(pushback, callback) { - if (this.state !== "RETRY") { - callback(false); - return; - } - if (this.attempts >= this.maxAttempts) { - callback(false); - return; - } - let retryDelayMs; - if (pushback === null) { - retryDelayMs = this.getNextRetryBackoffMs(); - } else if (pushback < 0) { - this.state = "TRANSPARENT_ONLY"; - callback(false); - return; - } else { - retryDelayMs = pushback; - this.nextRetryBackoffSec = this.initialRetryBackoffSec; - } - setTimeout(() => { - var _a, _b; - if (this.state !== "RETRY") { - callback(false); - return; - } - if ((_b = (_a = this.retryThrottler) === null || _a === void 0 ? void 0 : _a.canRetryCall()) !== null && _b !== void 0 ? _b : true) { - callback(true); - this.attempts += 1; - this.startNewAttempt(); - } else { - this.trace("Retry attempt denied by throttling policy"); - callback(false); - } - }, retryDelayMs); - } - countActiveCalls() { - let count = 0; - for (const call of this.underlyingCalls) { - if ((call === null || call === void 0 ? void 0 : call.state) === "ACTIVE") { - count += 1; - } - } - return count; - } - handleProcessedStatus(status, callIndex, pushback) { - var _a, _b, _c; - switch (this.state) { - case "COMMITTED": - case "NO_RETRY": - case "TRANSPARENT_ONLY": - this.commitCall(callIndex); - this.reportStatus(status); - break; - case "HEDGING": - if (this.isStatusCodeInList((_a = this.callConfig.methodConfig.hedgingPolicy.nonFatalStatusCodes) !== null && _a !== void 0 ? _a : [], status.code)) { - (_b = this.retryThrottler) === null || _b === void 0 ? void 0 : _b.addCallFailed(); - let delayMs; - if (pushback === null) { - delayMs = 0; - } else if (pushback < 0) { - this.state = "TRANSPARENT_ONLY"; - this.commitCall(callIndex); - this.reportStatus(status); - return; - } else { - delayMs = pushback; - } - setTimeout(() => { - this.maybeStartHedgingAttempt(); - if (this.countActiveCalls() === 0) { - this.commitCall(callIndex); - this.reportStatus(status); - } - }, delayMs); - } else { - this.commitCall(callIndex); - this.reportStatus(status); - } - break; - case "RETRY": - if (this.isStatusCodeInList(this.callConfig.methodConfig.retryPolicy.retryableStatusCodes, status.code)) { - (_c = this.retryThrottler) === null || _c === void 0 ? void 0 : _c.addCallFailed(); - this.maybeRetryCall(pushback, (retried) => { - if (!retried) { - this.commitCall(callIndex); - this.reportStatus(status); - } - }); - } else { - this.commitCall(callIndex); - this.reportStatus(status); - } - break; - } - } - getPushback(metadata) { - const mdValue = metadata.get("grpc-retry-pushback-ms"); - if (mdValue.length === 0) { - return null; - } - try { - return parseInt(mdValue[0]); - } catch (e) { - return -1; - } - } - handleChildStatus(status, callIndex) { - var _a; - if (this.underlyingCalls[callIndex].state === "COMPLETED") { - return; - } - this.trace("state=" + this.state + " handling status with progress " + status.progress + " from child [" + this.underlyingCalls[callIndex].call.getCallNumber() + "] in state " + this.underlyingCalls[callIndex].state); - this.underlyingCalls[callIndex].state = "COMPLETED"; - if (status.code === constants_1.Status.OK) { - (_a = this.retryThrottler) === null || _a === void 0 ? void 0 : _a.addCallSucceeded(); - this.commitCall(callIndex); - this.reportStatus(status); - return; - } - if (this.state === "NO_RETRY") { - this.commitCall(callIndex); - this.reportStatus(status); - return; - } - if (this.state === "COMMITTED") { - this.reportStatus(status); - return; - } - const pushback = this.getPushback(status.metadata); - switch (status.progress) { - case "NOT_STARTED": - this.startNewAttempt(); - break; - case "REFUSED": - if (this.transparentRetryUsed) { - this.handleProcessedStatus(status, callIndex, pushback); - } else { - this.transparentRetryUsed = true; - this.startNewAttempt(); - } - break; - case "DROP": - this.commitCall(callIndex); - this.reportStatus(status); - break; - case "PROCESSED": - this.handleProcessedStatus(status, callIndex, pushback); - break; - } - } - maybeStartHedgingAttempt() { - if (this.state !== "HEDGING") { - return; - } - if (!this.callConfig.methodConfig.hedgingPolicy) { - return; - } - if (this.attempts >= this.maxAttempts) { - return; - } - this.attempts += 1; - this.startNewAttempt(); - this.maybeStartHedgingTimer(); - } - maybeStartHedgingTimer() { - var _a, _b, _c; - if (this.hedgingTimer) { - clearTimeout(this.hedgingTimer); - } - if (this.state !== "HEDGING") { - return; - } - if (!this.callConfig.methodConfig.hedgingPolicy) { - return; - } - const hedgingPolicy = this.callConfig.methodConfig.hedgingPolicy; - if (this.attempts >= this.maxAttempts) { - return; - } - const hedgingDelayString = (_a = hedgingPolicy.hedgingDelay) !== null && _a !== void 0 ? _a : "0s"; - const hedgingDelaySec = Number(hedgingDelayString.substring(0, hedgingDelayString.length - 1)); - this.hedgingTimer = setTimeout(() => { - this.maybeStartHedgingAttempt(); - }, hedgingDelaySec * 1e3); - (_c = (_b = this.hedgingTimer).unref) === null || _c === void 0 ? void 0 : _c.call(_b); - } - startNewAttempt() { - const child = this.channel.createLoadBalancingCall(this.callConfig, this.methodName, this.host, this.credentials, this.deadline); - this.trace("Created child call [" + child.getCallNumber() + "] for attempt " + this.attempts); - const index = this.underlyingCalls.length; - this.underlyingCalls.push({ - state: "ACTIVE", - call: child, - nextMessageToSend: 0, - startTime: /* @__PURE__ */ new Date() - }); - const previousAttempts = this.attempts - 1; - const initialMetadata = this.initialMetadata.clone(); - if (previousAttempts > 0) { - initialMetadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`); - } - let receivedMetadata = false; - child.start(initialMetadata, { - onReceiveMetadata: (metadata) => { - this.trace("Received metadata from child [" + child.getCallNumber() + "]"); - this.commitCall(index); - receivedMetadata = true; - if (previousAttempts > 0) { - metadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`); - } - if (this.underlyingCalls[index].state === "ACTIVE") { - this.listener.onReceiveMetadata(metadata); - } - }, - onReceiveMessage: (message) => { - this.trace("Received message from child [" + child.getCallNumber() + "]"); - this.commitCall(index); - if (this.underlyingCalls[index].state === "ACTIVE") { - this.listener.onReceiveMessage(message); - } - }, - onReceiveStatus: (status) => { - this.trace("Received status from child [" + child.getCallNumber() + "]"); - if (!receivedMetadata && previousAttempts > 0) { - status.metadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`); - } - this.handleChildStatus(status, index); - } - }); - this.sendNextChildMessage(index); - if (this.readStarted) { - child.startRead(); - } - } - start(metadata, listener) { - this.trace("start called"); - this.listener = listener; - this.initialMetadata = metadata; - this.attempts += 1; - this.startNewAttempt(); - this.maybeStartHedgingTimer(); - } - handleChildWriteCompleted(childIndex, messageIndex) { - var _a, _b; - (_b = (_a = this.getBufferEntry(messageIndex)).callback) === null || _b === void 0 ? void 0 : _b.call(_a); - this.clearSentMessages(); - const childCall = this.underlyingCalls[childIndex]; - childCall.nextMessageToSend += 1; - this.sendNextChildMessage(childIndex); - } - sendNextChildMessage(childIndex) { - const childCall = this.underlyingCalls[childIndex]; - if (childCall.state === "COMPLETED") { - return; - } - const messageIndex = childCall.nextMessageToSend; - if (this.getBufferEntry(messageIndex)) { - const bufferEntry = this.getBufferEntry(messageIndex); - switch (bufferEntry.entryType) { - case "MESSAGE": - childCall.call.sendMessageWithContext({ - callback: (error3) => { - this.handleChildWriteCompleted(childIndex, messageIndex); - } - }, bufferEntry.message.message); - const nextEntry = this.getBufferEntry(messageIndex + 1); - if (nextEntry.entryType === "HALF_CLOSE") { - this.trace("Sending halfClose immediately after message to child [" + childCall.call.getCallNumber() + "] - optimizing for unary/final message"); - childCall.nextMessageToSend += 1; - childCall.call.halfClose(); - } - break; - case "HALF_CLOSE": - childCall.nextMessageToSend += 1; - childCall.call.halfClose(); - break; - case "FREED": - break; - } - } - } - sendMessageWithContext(context3, message) { - this.trace("write() called with message of length " + message.length); - const writeObj = { - message, - flags: context3.flags - }; - const messageIndex = this.getNextBufferIndex(); - const bufferEntry = { - entryType: "MESSAGE", - message: writeObj, - allocated: this.bufferTracker.allocate(message.length, this.callNumber) - }; - this.writeBuffer.push(bufferEntry); - if (bufferEntry.allocated) { - process.nextTick(() => { - var _a; - (_a = context3.callback) === null || _a === void 0 ? void 0 : _a.call(context3); - }); - for (const [callIndex, call] of this.underlyingCalls.entries()) { - if (call.state === "ACTIVE" && call.nextMessageToSend === messageIndex) { - call.call.sendMessageWithContext({ - callback: (error3) => { - this.handleChildWriteCompleted(callIndex, messageIndex); - } - }, message); - } - } - } else { - this.commitCallWithMostMessages(); - if (this.committedCallIndex === null) { - return; - } - const call = this.underlyingCalls[this.committedCallIndex]; - bufferEntry.callback = context3.callback; - if (call.state === "ACTIVE" && call.nextMessageToSend === messageIndex) { - call.call.sendMessageWithContext({ - callback: (error3) => { - this.handleChildWriteCompleted(this.committedCallIndex, messageIndex); - } - }, message); - } - } - } - startRead() { - this.trace("startRead called"); - this.readStarted = true; - for (const underlyingCall of this.underlyingCalls) { - if ((underlyingCall === null || underlyingCall === void 0 ? void 0 : underlyingCall.state) === "ACTIVE") { - underlyingCall.call.startRead(); - } - } - } - halfClose() { - this.trace("halfClose called"); - const halfCloseIndex = this.getNextBufferIndex(); - this.writeBuffer.push({ - entryType: "HALF_CLOSE", - allocated: false - }); - for (const call of this.underlyingCalls) { - if ((call === null || call === void 0 ? void 0 : call.state) === "ACTIVE") { - if (call.nextMessageToSend === halfCloseIndex || call.nextMessageToSend === halfCloseIndex - 1) { - this.trace("Sending halfClose immediately to child [" + call.call.getCallNumber() + "] - all messages already sent"); - call.nextMessageToSend += 1; - call.call.halfClose(); - } - } - } - } - setCredentials(newCredentials) { - throw new Error("Method not implemented."); - } - getMethod() { - return this.methodName; - } - getHost() { - return this.host; - } - getAuthContext() { - if (this.committedCallIndex !== null) { - return this.underlyingCalls[this.committedCallIndex].call.getAuthContext(); - } else { - return null; - } - } - }; - exports2.RetryingCall = RetryingCall; - } -}); - -// node_modules/@grpc/grpc-js/build/src/subchannel-interface.js -var require_subchannel_interface = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/subchannel-interface.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BaseSubchannelWrapper = void 0; - var BaseSubchannelWrapper = class { - constructor(child) { - this.child = child; - this.healthy = true; - this.healthListeners = /* @__PURE__ */ new Set(); - this.refcount = 0; - this.dataWatchers = /* @__PURE__ */ new Set(); - child.addHealthStateWatcher((childHealthy) => { - if (this.healthy) { - this.updateHealthListeners(); - } - }); - } - updateHealthListeners() { - for (const listener of this.healthListeners) { - listener(this.isHealthy()); - } - } - getConnectivityState() { - return this.child.getConnectivityState(); - } - addConnectivityStateListener(listener) { - this.child.addConnectivityStateListener(listener); - } - removeConnectivityStateListener(listener) { - this.child.removeConnectivityStateListener(listener); - } - startConnecting() { - this.child.startConnecting(); - } - getAddress() { - return this.child.getAddress(); - } - throttleKeepalive(newKeepaliveTime) { - this.child.throttleKeepalive(newKeepaliveTime); - } - ref() { - this.child.ref(); - this.refcount += 1; - } - unref() { - this.child.unref(); - this.refcount -= 1; - if (this.refcount === 0) { - this.destroy(); - } - } - destroy() { - for (const watcher of this.dataWatchers) { - watcher.destroy(); - } - } - getChannelzRef() { - return this.child.getChannelzRef(); - } - isHealthy() { - return this.healthy && this.child.isHealthy(); - } - addHealthStateWatcher(listener) { - this.healthListeners.add(listener); - } - removeHealthStateWatcher(listener) { - this.healthListeners.delete(listener); - } - addDataWatcher(dataWatcher) { - dataWatcher.setSubchannel(this.getRealSubchannel()); - this.dataWatchers.add(dataWatcher); - } - setHealthy(healthy) { - if (healthy !== this.healthy) { - this.healthy = healthy; - if (this.child.isHealthy()) { - this.updateHealthListeners(); - } - } - } - getRealSubchannel() { - return this.child.getRealSubchannel(); - } - realSubchannelEquals(other) { - return this.getRealSubchannel() === other.getRealSubchannel(); - } - getCallCredentials() { - return this.child.getCallCredentials(); - } - getChannel() { - return this.child.getChannel(); - } - }; - exports2.BaseSubchannelWrapper = BaseSubchannelWrapper; - } -}); - -// node_modules/@grpc/grpc-js/build/src/internal-channel.js -var require_internal_channel = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/internal-channel.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.InternalChannel = exports2.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = void 0; - var channel_credentials_1 = require_channel_credentials(); - var resolving_load_balancer_1 = require_resolving_load_balancer(); - var subchannel_pool_1 = require_subchannel_pool(); - var picker_1 = require_picker(); - var metadata_1 = require_metadata(); - var constants_1 = require_constants7(); - var filter_stack_1 = require_filter_stack(); - var compression_filter_1 = require_compression_filter(); - var resolver_1 = require_resolver(); - var logging_1 = require_logging(); - var http_proxy_1 = require_http_proxy(); - var uri_parser_1 = require_uri_parser(); - var connectivity_state_1 = require_connectivity_state(); - var channelz_1 = require_channelz(); - var load_balancing_call_1 = require_load_balancing_call(); - var deadline_1 = require_deadline(); - var resolving_call_1 = require_resolving_call(); - var call_number_1 = require_call_number(); - var control_plane_status_1 = require_control_plane_status(); - var retrying_call_1 = require_retrying_call(); - var subchannel_interface_1 = require_subchannel_interface(); - var MAX_TIMEOUT_TIME = 2147483647; - var MIN_IDLE_TIMEOUT_MS = 1e3; - var DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1e3; - var RETRY_THROTTLER_MAP = /* @__PURE__ */ new Map(); - var DEFAULT_RETRY_BUFFER_SIZE_BYTES = 1 << 24; - var DEFAULT_PER_RPC_RETRY_BUFFER_SIZE_BYTES = 1 << 20; - var ChannelSubchannelWrapper = class extends subchannel_interface_1.BaseSubchannelWrapper { - constructor(childSubchannel, channel) { - super(childSubchannel); - this.channel = channel; - this.refCount = 0; - this.subchannelStateListener = (subchannel, previousState, newState, keepaliveTime) => { - channel.throttleKeepalive(keepaliveTime); - }; - } - ref() { - if (this.refCount === 0) { - this.child.addConnectivityStateListener(this.subchannelStateListener); - this.channel.addWrappedSubchannel(this); - } - this.child.ref(); - this.refCount += 1; - } - unref() { - this.child.unref(); - this.refCount -= 1; - if (this.refCount <= 0) { - this.child.removeConnectivityStateListener(this.subchannelStateListener); - this.channel.removeWrappedSubchannel(this); - } - } - }; - var ShutdownPicker = class { - pick(pickArgs) { - return { - pickResultType: picker_1.PickResultType.DROP, - status: { - code: constants_1.Status.UNAVAILABLE, - details: "Channel closed before call started", - metadata: new metadata_1.Metadata() - }, - subchannel: null, - onCallStarted: null, - onCallEnded: null - }; - } - }; - exports2.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = "grpc.internal.no_subchannel"; - var ChannelzInfoTracker = class { - constructor(target) { - this.target = target; - this.trace = new channelz_1.ChannelzTrace(); - this.callTracker = new channelz_1.ChannelzCallTracker(); - this.childrenTracker = new channelz_1.ChannelzChildrenTracker(); - this.state = connectivity_state_1.ConnectivityState.IDLE; - } - getChannelzInfoCallback() { - return () => { - return { - target: this.target, - state: this.state, - trace: this.trace, - callTracker: this.callTracker, - children: this.childrenTracker.getChildLists() - }; - }; - } - }; - var InternalChannel = class { - constructor(target, credentials, options) { - var _a, _b, _c, _d, _e, _f; - this.credentials = credentials; - this.options = options; - this.connectivityState = connectivity_state_1.ConnectivityState.IDLE; - this.currentPicker = new picker_1.UnavailablePicker(); - this.configSelectionQueue = []; - this.pickQueue = []; - this.connectivityStateWatchers = []; - this.callRefTimer = null; - this.configSelector = null; - this.currentResolutionError = null; - this.wrappedSubchannels = /* @__PURE__ */ new Set(); - this.callCount = 0; - this.idleTimer = null; - this.channelzEnabled = true; - this.randomChannelId = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER); - if (typeof target !== "string") { - throw new TypeError("Channel target must be a string"); - } - if (!(credentials instanceof channel_credentials_1.ChannelCredentials)) { - throw new TypeError("Channel credentials must be a ChannelCredentials object"); - } - if (options) { - if (typeof options !== "object") { - throw new TypeError("Channel options must be an object"); - } - } - this.channelzInfoTracker = new ChannelzInfoTracker(target); - const originalTargetUri = (0, uri_parser_1.parseUri)(target); - if (originalTargetUri === null) { - throw new Error(`Could not parse target name "${target}"`); - } - const defaultSchemeMapResult = (0, resolver_1.mapUriDefaultScheme)(originalTargetUri); - if (defaultSchemeMapResult === null) { - throw new Error(`Could not find a default scheme for target name "${target}"`); - } - if (this.options["grpc.enable_channelz"] === 0) { - this.channelzEnabled = false; - } - this.channelzRef = (0, channelz_1.registerChannelzChannel)(target, this.channelzInfoTracker.getChannelzInfoCallback(), this.channelzEnabled); - if (this.channelzEnabled) { - this.channelzInfoTracker.trace.addTrace("CT_INFO", "Channel created"); - } - if (this.options["grpc.default_authority"]) { - this.defaultAuthority = this.options["grpc.default_authority"]; - } else { - this.defaultAuthority = (0, resolver_1.getDefaultAuthority)(defaultSchemeMapResult); - } - const proxyMapResult = (0, http_proxy_1.mapProxyName)(defaultSchemeMapResult, options); - this.target = proxyMapResult.target; - this.options = Object.assign({}, this.options, proxyMapResult.extraOptions); - this.subchannelPool = (0, subchannel_pool_1.getSubchannelPool)(((_a = this.options["grpc.use_local_subchannel_pool"]) !== null && _a !== void 0 ? _a : 0) === 0); - this.retryBufferTracker = new retrying_call_1.MessageBufferTracker((_b = this.options["grpc.retry_buffer_size"]) !== null && _b !== void 0 ? _b : DEFAULT_RETRY_BUFFER_SIZE_BYTES, (_c = this.options["grpc.per_rpc_retry_buffer_size"]) !== null && _c !== void 0 ? _c : DEFAULT_PER_RPC_RETRY_BUFFER_SIZE_BYTES); - this.keepaliveTime = (_d = this.options["grpc.keepalive_time_ms"]) !== null && _d !== void 0 ? _d : -1; - this.idleTimeoutMs = Math.max((_e = this.options["grpc.client_idle_timeout_ms"]) !== null && _e !== void 0 ? _e : DEFAULT_IDLE_TIMEOUT_MS, MIN_IDLE_TIMEOUT_MS); - const channelControlHelper = { - createSubchannel: (subchannelAddress, subchannelArgs) => { - const finalSubchannelArgs = {}; - for (const [key, value] of Object.entries(subchannelArgs)) { - if (!key.startsWith(exports2.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX)) { - finalSubchannelArgs[key] = value; - } - } - const subchannel = this.subchannelPool.getOrCreateSubchannel(this.target, subchannelAddress, finalSubchannelArgs, this.credentials); - subchannel.throttleKeepalive(this.keepaliveTime); - if (this.channelzEnabled) { - this.channelzInfoTracker.trace.addTrace("CT_INFO", "Created subchannel or used existing subchannel", subchannel.getChannelzRef()); - } - const wrappedSubchannel = new ChannelSubchannelWrapper(subchannel, this); - return wrappedSubchannel; - }, - updateState: (connectivityState, picker) => { - this.currentPicker = picker; - const queueCopy = this.pickQueue.slice(); - this.pickQueue = []; - if (queueCopy.length > 0) { - this.callRefTimerUnref(); - } - for (const call of queueCopy) { - call.doPick(); - } - this.updateState(connectivityState); - }, - requestReresolution: () => { - throw new Error("Resolving load balancer should never call requestReresolution"); - }, - addChannelzChild: (child) => { - if (this.channelzEnabled) { - this.channelzInfoTracker.childrenTracker.refChild(child); - } - }, - removeChannelzChild: (child) => { - if (this.channelzEnabled) { - this.channelzInfoTracker.childrenTracker.unrefChild(child); - } - } - }; - this.resolvingLoadBalancer = new resolving_load_balancer_1.ResolvingLoadBalancer(this.target, channelControlHelper, this.options, (serviceConfig, configSelector) => { - var _a2; - if (serviceConfig.retryThrottling) { - RETRY_THROTTLER_MAP.set(this.getTarget(), new retrying_call_1.RetryThrottler(serviceConfig.retryThrottling.maxTokens, serviceConfig.retryThrottling.tokenRatio, RETRY_THROTTLER_MAP.get(this.getTarget()))); - } else { - RETRY_THROTTLER_MAP.delete(this.getTarget()); - } - if (this.channelzEnabled) { - this.channelzInfoTracker.trace.addTrace("CT_INFO", "Address resolution succeeded"); - } - (_a2 = this.configSelector) === null || _a2 === void 0 ? void 0 : _a2.unref(); - this.configSelector = configSelector; - this.currentResolutionError = null; - process.nextTick(() => { - const localQueue = this.configSelectionQueue; - this.configSelectionQueue = []; - if (localQueue.length > 0) { - this.callRefTimerUnref(); - } - for (const call of localQueue) { - call.getConfig(); - } - }); - }, (status) => { - if (this.channelzEnabled) { - this.channelzInfoTracker.trace.addTrace("CT_WARNING", "Address resolution failed with code " + status.code + ' and details "' + status.details + '"'); - } - if (this.configSelectionQueue.length > 0) { - this.trace("Name resolution failed with calls queued for config selection"); - } - if (this.configSelector === null) { - this.currentResolutionError = Object.assign(Object.assign({}, (0, control_plane_status_1.restrictControlPlaneStatusCode)(status.code, status.details)), { metadata: status.metadata }); - } - const localQueue = this.configSelectionQueue; - this.configSelectionQueue = []; - if (localQueue.length > 0) { - this.callRefTimerUnref(); - } - for (const call of localQueue) { - call.reportResolverError(status); - } - }); - this.filterStackFactory = new filter_stack_1.FilterStackFactory([ - new compression_filter_1.CompressionFilterFactory(this, this.options) - ]); - this.trace("Channel constructed with options " + JSON.stringify(options, void 0, 2)); - const error3 = new Error(); - if ((0, logging_1.isTracerEnabled)("channel_stacktrace")) { - (0, logging_1.trace)(constants_1.LogVerbosity.DEBUG, "channel_stacktrace", "(" + this.channelzRef.id + ") Channel constructed \n" + ((_f = error3.stack) === null || _f === void 0 ? void 0 : _f.substring(error3.stack.indexOf("\n") + 1))); - } - this.lastActivityTimestamp = /* @__PURE__ */ new Date(); - } - trace(text, verbosityOverride) { - (0, logging_1.trace)(verbosityOverride !== null && verbosityOverride !== void 0 ? verbosityOverride : constants_1.LogVerbosity.DEBUG, "channel", "(" + this.channelzRef.id + ") " + (0, uri_parser_1.uriToString)(this.target) + " " + text); - } - callRefTimerRef() { - var _a, _b, _c, _d; - if (!this.callRefTimer) { - this.callRefTimer = setInterval(() => { - }, MAX_TIMEOUT_TIME); - } - if (!((_b = (_a = this.callRefTimer).hasRef) === null || _b === void 0 ? void 0 : _b.call(_a))) { - this.trace("callRefTimer.ref | configSelectionQueue.length=" + this.configSelectionQueue.length + " pickQueue.length=" + this.pickQueue.length); - (_d = (_c = this.callRefTimer).ref) === null || _d === void 0 ? void 0 : _d.call(_c); - } - } - callRefTimerUnref() { - var _a, _b, _c; - if (!((_a = this.callRefTimer) === null || _a === void 0 ? void 0 : _a.hasRef) || this.callRefTimer.hasRef()) { - this.trace("callRefTimer.unref | configSelectionQueue.length=" + this.configSelectionQueue.length + " pickQueue.length=" + this.pickQueue.length); - (_c = (_b = this.callRefTimer) === null || _b === void 0 ? void 0 : _b.unref) === null || _c === void 0 ? void 0 : _c.call(_b); - } - } - removeConnectivityStateWatcher(watcherObject) { - const watcherIndex = this.connectivityStateWatchers.findIndex((value) => value === watcherObject); - if (watcherIndex >= 0) { - this.connectivityStateWatchers.splice(watcherIndex, 1); - } - } - updateState(newState) { - (0, logging_1.trace)(constants_1.LogVerbosity.DEBUG, "connectivity_state", "(" + this.channelzRef.id + ") " + (0, uri_parser_1.uriToString)(this.target) + " " + connectivity_state_1.ConnectivityState[this.connectivityState] + " -> " + connectivity_state_1.ConnectivityState[newState]); - if (this.channelzEnabled) { - this.channelzInfoTracker.trace.addTrace("CT_INFO", "Connectivity state change to " + connectivity_state_1.ConnectivityState[newState]); - } - this.connectivityState = newState; - this.channelzInfoTracker.state = newState; - const watchersCopy = this.connectivityStateWatchers.slice(); - for (const watcherObject of watchersCopy) { - if (newState !== watcherObject.currentState) { - if (watcherObject.timer) { - clearTimeout(watcherObject.timer); - } - this.removeConnectivityStateWatcher(watcherObject); - watcherObject.callback(); - } - } - if (newState !== connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { - this.currentResolutionError = null; - } - } - throttleKeepalive(newKeepaliveTime) { - if (newKeepaliveTime > this.keepaliveTime) { - this.keepaliveTime = newKeepaliveTime; - for (const wrappedSubchannel of this.wrappedSubchannels) { - wrappedSubchannel.throttleKeepalive(newKeepaliveTime); - } - } - } - addWrappedSubchannel(wrappedSubchannel) { - this.wrappedSubchannels.add(wrappedSubchannel); - } - removeWrappedSubchannel(wrappedSubchannel) { - this.wrappedSubchannels.delete(wrappedSubchannel); - } - doPick(metadata, extraPickInfo) { - return this.currentPicker.pick({ - metadata, - extraPickInfo - }); - } - queueCallForPick(call) { - this.pickQueue.push(call); - this.callRefTimerRef(); - } - getConfig(method, metadata) { - if (this.connectivityState !== connectivity_state_1.ConnectivityState.SHUTDOWN) { - this.resolvingLoadBalancer.exitIdle(); - } - if (this.configSelector) { - return { - type: "SUCCESS", - config: this.configSelector.invoke(method, metadata, this.randomChannelId) - }; - } else { - if (this.currentResolutionError) { - return { - type: "ERROR", - error: this.currentResolutionError - }; - } else { - return { - type: "NONE" - }; - } - } - } - queueCallForConfig(call) { - this.configSelectionQueue.push(call); - this.callRefTimerRef(); - } - enterIdle() { - this.resolvingLoadBalancer.destroy(); - this.updateState(connectivity_state_1.ConnectivityState.IDLE); - this.currentPicker = new picker_1.QueuePicker(this.resolvingLoadBalancer); - if (this.idleTimer) { - clearTimeout(this.idleTimer); - this.idleTimer = null; - } - if (this.callRefTimer) { - clearInterval(this.callRefTimer); - this.callRefTimer = null; - } - } - startIdleTimeout(timeoutMs) { - var _a, _b; - this.idleTimer = setTimeout(() => { - if (this.callCount > 0) { - this.startIdleTimeout(this.idleTimeoutMs); - return; - } - const now = /* @__PURE__ */ new Date(); - const timeSinceLastActivity = now.valueOf() - this.lastActivityTimestamp.valueOf(); - if (timeSinceLastActivity >= this.idleTimeoutMs) { - this.trace("Idle timer triggered after " + this.idleTimeoutMs + "ms of inactivity"); - this.enterIdle(); - } else { - this.startIdleTimeout(this.idleTimeoutMs - timeSinceLastActivity); - } - }, timeoutMs); - (_b = (_a = this.idleTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - } - maybeStartIdleTimer() { - if (this.connectivityState !== connectivity_state_1.ConnectivityState.SHUTDOWN && !this.idleTimer) { - this.startIdleTimeout(this.idleTimeoutMs); - } - } - onCallStart() { - if (this.channelzEnabled) { - this.channelzInfoTracker.callTracker.addCallStarted(); - } - this.callCount += 1; - } - onCallEnd(status) { - if (this.channelzEnabled) { - if (status.code === constants_1.Status.OK) { - this.channelzInfoTracker.callTracker.addCallSucceeded(); - } else { - this.channelzInfoTracker.callTracker.addCallFailed(); - } - } - this.callCount -= 1; - this.lastActivityTimestamp = /* @__PURE__ */ new Date(); - this.maybeStartIdleTimer(); - } - createLoadBalancingCall(callConfig, method, host, credentials, deadline) { - const callNumber = (0, call_number_1.getNextCallNumber)(); - this.trace("createLoadBalancingCall [" + callNumber + '] method="' + method + '"'); - return new load_balancing_call_1.LoadBalancingCall(this, callConfig, method, host, credentials, deadline, callNumber); - } - createRetryingCall(callConfig, method, host, credentials, deadline) { - const callNumber = (0, call_number_1.getNextCallNumber)(); - this.trace("createRetryingCall [" + callNumber + '] method="' + method + '"'); - return new retrying_call_1.RetryingCall(this, callConfig, method, host, credentials, deadline, callNumber, this.retryBufferTracker, RETRY_THROTTLER_MAP.get(this.getTarget())); - } - createResolvingCall(method, deadline, host, parentCall, propagateFlags) { - const callNumber = (0, call_number_1.getNextCallNumber)(); - this.trace("createResolvingCall [" + callNumber + '] method="' + method + '", deadline=' + (0, deadline_1.deadlineToString)(deadline)); - const finalOptions = { - deadline, - flags: propagateFlags !== null && propagateFlags !== void 0 ? propagateFlags : constants_1.Propagate.DEFAULTS, - host: host !== null && host !== void 0 ? host : this.defaultAuthority, - parentCall - }; - const call = new resolving_call_1.ResolvingCall(this, method, finalOptions, this.filterStackFactory.clone(), callNumber); - this.onCallStart(); - call.addStatusWatcher((status) => { - this.onCallEnd(status); - }); - return call; - } - close() { - var _a; - this.resolvingLoadBalancer.destroy(); - this.updateState(connectivity_state_1.ConnectivityState.SHUTDOWN); - this.currentPicker = new ShutdownPicker(); - for (const call of this.configSelectionQueue) { - call.cancelWithStatus(constants_1.Status.UNAVAILABLE, "Channel closed before call started"); - } - this.configSelectionQueue = []; - for (const call of this.pickQueue) { - call.cancelWithStatus(constants_1.Status.UNAVAILABLE, "Channel closed before call started"); - } - this.pickQueue = []; - if (this.callRefTimer) { - clearInterval(this.callRefTimer); - } - if (this.idleTimer) { - clearTimeout(this.idleTimer); - } - if (this.channelzEnabled) { - (0, channelz_1.unregisterChannelzRef)(this.channelzRef); - } - this.subchannelPool.unrefUnusedSubchannels(); - (_a = this.configSelector) === null || _a === void 0 ? void 0 : _a.unref(); - this.configSelector = null; - } - getTarget() { - return (0, uri_parser_1.uriToString)(this.target); - } - getConnectivityState(tryToConnect) { - const connectivityState = this.connectivityState; - if (tryToConnect) { - this.resolvingLoadBalancer.exitIdle(); - this.lastActivityTimestamp = /* @__PURE__ */ new Date(); - this.maybeStartIdleTimer(); - } - return connectivityState; - } - watchConnectivityState(currentState, deadline, callback) { - if (this.connectivityState === connectivity_state_1.ConnectivityState.SHUTDOWN) { - throw new Error("Channel has been shut down"); - } - let timer = null; - if (deadline !== Infinity) { - const deadlineDate = deadline instanceof Date ? deadline : new Date(deadline); - const now = /* @__PURE__ */ new Date(); - if (deadline === -Infinity || deadlineDate <= now) { - process.nextTick(callback, new Error("Deadline passed without connectivity state change")); - return; - } - timer = setTimeout(() => { - this.removeConnectivityStateWatcher(watcherObject); - callback(new Error("Deadline passed without connectivity state change")); - }, deadlineDate.getTime() - now.getTime()); - } - const watcherObject = { - currentState, - callback, - timer - }; - this.connectivityStateWatchers.push(watcherObject); - } - /** - * Get the channelz reference object for this channel. The returned value is - * garbage if channelz is disabled for this channel. - * @returns - */ - getChannelzRef() { - return this.channelzRef; - } - createCall(method, deadline, host, parentCall, propagateFlags) { - if (typeof method !== "string") { - throw new TypeError("Channel#createCall: method must be a string"); - } - if (!(typeof deadline === "number" || deadline instanceof Date)) { - throw new TypeError("Channel#createCall: deadline must be a number or Date"); - } - if (this.connectivityState === connectivity_state_1.ConnectivityState.SHUTDOWN) { - throw new Error("Channel has been shut down"); - } - return this.createResolvingCall(method, deadline, host, parentCall, propagateFlags); - } - getOptions() { - return this.options; - } - }; - exports2.InternalChannel = InternalChannel; - } -}); - -// node_modules/@grpc/grpc-js/build/src/channel.js -var require_channel = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/channel.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ChannelImplementation = void 0; - var channel_credentials_1 = require_channel_credentials(); - var internal_channel_1 = require_internal_channel(); - var ChannelImplementation = class { - constructor(target, credentials, options) { - if (typeof target !== "string") { - throw new TypeError("Channel target must be a string"); - } - if (!(credentials instanceof channel_credentials_1.ChannelCredentials)) { - throw new TypeError("Channel credentials must be a ChannelCredentials object"); - } - if (options) { - if (typeof options !== "object") { - throw new TypeError("Channel options must be an object"); - } - } - this.internalChannel = new internal_channel_1.InternalChannel(target, credentials, options); - } - close() { - this.internalChannel.close(); - } - getTarget() { - return this.internalChannel.getTarget(); - } - getConnectivityState(tryToConnect) { - return this.internalChannel.getConnectivityState(tryToConnect); - } - watchConnectivityState(currentState, deadline, callback) { - this.internalChannel.watchConnectivityState(currentState, deadline, callback); - } - /** - * Get the channelz reference object for this channel. The returned value is - * garbage if channelz is disabled for this channel. - * @returns - */ - getChannelzRef() { - return this.internalChannel.getChannelzRef(); - } - createCall(method, deadline, host, parentCall, propagateFlags) { - if (typeof method !== "string") { - throw new TypeError("Channel#createCall: method must be a string"); - } - if (!(typeof deadline === "number" || deadline instanceof Date)) { - throw new TypeError("Channel#createCall: deadline must be a number or Date"); - } - return this.internalChannel.createCall(method, deadline, host, parentCall, propagateFlags); - } - }; - exports2.ChannelImplementation = ChannelImplementation; - } -}); - -// node_modules/@grpc/grpc-js/build/src/server-call.js -var require_server_call = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/server-call.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ServerDuplexStreamImpl = exports2.ServerWritableStreamImpl = exports2.ServerReadableStreamImpl = exports2.ServerUnaryCallImpl = void 0; - exports2.serverErrorToStatus = serverErrorToStatus; - var events_1 = require("events"); - var stream_1 = require("stream"); - var constants_1 = require_constants7(); - var metadata_1 = require_metadata(); - function serverErrorToStatus(error3, overrideTrailers) { - var _a; - const status = { - code: constants_1.Status.UNKNOWN, - details: "message" in error3 ? error3.message : "Unknown Error", - metadata: (_a = overrideTrailers !== null && overrideTrailers !== void 0 ? overrideTrailers : error3.metadata) !== null && _a !== void 0 ? _a : null - }; - if ("code" in error3 && typeof error3.code === "number" && Number.isInteger(error3.code)) { - status.code = error3.code; - if ("details" in error3 && typeof error3.details === "string") { - status.details = error3.details; - } - } - return status; - } - var ServerUnaryCallImpl = class extends events_1.EventEmitter { - constructor(path, call, metadata, request2) { - super(); - this.path = path; - this.call = call; - this.metadata = metadata; - this.request = request2; - this.cancelled = false; - } - getPeer() { - return this.call.getPeer(); - } - sendMetadata(responseMetadata) { - this.call.sendMetadata(responseMetadata); - } - getDeadline() { - return this.call.getDeadline(); - } - getPath() { - return this.path; - } - getHost() { - return this.call.getHost(); - } - getAuthContext() { - return this.call.getAuthContext(); - } - getMetricsRecorder() { - return this.call.getMetricsRecorder(); - } - }; - exports2.ServerUnaryCallImpl = ServerUnaryCallImpl; - var ServerReadableStreamImpl = class extends stream_1.Readable { - constructor(path, call, metadata) { - super({ objectMode: true }); - this.path = path; - this.call = call; - this.metadata = metadata; - this.cancelled = false; - } - _read(size) { - this.call.startRead(); - } - getPeer() { - return this.call.getPeer(); - } - sendMetadata(responseMetadata) { - this.call.sendMetadata(responseMetadata); - } - getDeadline() { - return this.call.getDeadline(); - } - getPath() { - return this.path; - } - getHost() { - return this.call.getHost(); - } - getAuthContext() { - return this.call.getAuthContext(); - } - getMetricsRecorder() { - return this.call.getMetricsRecorder(); - } - }; - exports2.ServerReadableStreamImpl = ServerReadableStreamImpl; - var ServerWritableStreamImpl = class extends stream_1.Writable { - constructor(path, call, metadata, request2) { - super({ objectMode: true }); - this.path = path; - this.call = call; - this.metadata = metadata; - this.request = request2; - this.pendingStatus = { - code: constants_1.Status.OK, - details: "OK" - }; - this.cancelled = false; - this.trailingMetadata = new metadata_1.Metadata(); - this.on("error", (err) => { - this.pendingStatus = serverErrorToStatus(err); - this.end(); - }); - } - getPeer() { - return this.call.getPeer(); - } - sendMetadata(responseMetadata) { - this.call.sendMetadata(responseMetadata); - } - getDeadline() { - return this.call.getDeadline(); - } - getPath() { - return this.path; - } - getHost() { - return this.call.getHost(); - } - getAuthContext() { - return this.call.getAuthContext(); - } - getMetricsRecorder() { - return this.call.getMetricsRecorder(); - } - _write(chunk, encoding, callback) { - this.call.sendMessage(chunk, callback); - } - _final(callback) { - var _a; - callback(null); - this.call.sendStatus(Object.assign(Object.assign({}, this.pendingStatus), { metadata: (_a = this.pendingStatus.metadata) !== null && _a !== void 0 ? _a : this.trailingMetadata })); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - end(metadata) { - if (metadata) { - this.trailingMetadata = metadata; - } - return super.end(); - } - }; - exports2.ServerWritableStreamImpl = ServerWritableStreamImpl; - var ServerDuplexStreamImpl = class extends stream_1.Duplex { - constructor(path, call, metadata) { - super({ objectMode: true }); - this.path = path; - this.call = call; - this.metadata = metadata; - this.pendingStatus = { - code: constants_1.Status.OK, - details: "OK" - }; - this.cancelled = false; - this.trailingMetadata = new metadata_1.Metadata(); - this.on("error", (err) => { - this.pendingStatus = serverErrorToStatus(err); - this.end(); - }); - } - getPeer() { - return this.call.getPeer(); - } - sendMetadata(responseMetadata) { - this.call.sendMetadata(responseMetadata); - } - getDeadline() { - return this.call.getDeadline(); - } - getPath() { - return this.path; - } - getHost() { - return this.call.getHost(); - } - getAuthContext() { - return this.call.getAuthContext(); - } - getMetricsRecorder() { - return this.call.getMetricsRecorder(); - } - _read(size) { - this.call.startRead(); - } - _write(chunk, encoding, callback) { - this.call.sendMessage(chunk, callback); - } - _final(callback) { - var _a; - callback(null); - this.call.sendStatus(Object.assign(Object.assign({}, this.pendingStatus), { metadata: (_a = this.pendingStatus.metadata) !== null && _a !== void 0 ? _a : this.trailingMetadata })); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - end(metadata) { - if (metadata) { - this.trailingMetadata = metadata; - } - return super.end(); - } - }; - exports2.ServerDuplexStreamImpl = ServerDuplexStreamImpl; - } -}); - -// node_modules/@grpc/grpc-js/build/src/server-credentials.js -var require_server_credentials = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/server-credentials.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ServerCredentials = void 0; - exports2.createCertificateProviderServerCredentials = createCertificateProviderServerCredentials; - exports2.createServerCredentialsWithInterceptors = createServerCredentialsWithInterceptors; - var tls_helpers_1 = require_tls_helpers(); - var ServerCredentials = class { - constructor(serverConstructorOptions, contextOptions) { - this.serverConstructorOptions = serverConstructorOptions; - this.watchers = /* @__PURE__ */ new Set(); - this.latestContextOptions = null; - this.latestContextOptions = contextOptions !== null && contextOptions !== void 0 ? contextOptions : null; - } - _addWatcher(watcher) { - this.watchers.add(watcher); - } - _removeWatcher(watcher) { - this.watchers.delete(watcher); - } - getWatcherCount() { - return this.watchers.size; - } - updateSecureContextOptions(options) { - this.latestContextOptions = options; - for (const watcher of this.watchers) { - watcher(this.latestContextOptions); - } - } - _isSecure() { - return this.serverConstructorOptions !== null; - } - _getSecureContextOptions() { - return this.latestContextOptions; - } - _getConstructorOptions() { - return this.serverConstructorOptions; - } - _getInterceptors() { - return []; - } - static createInsecure() { - return new InsecureServerCredentials(); - } - static createSsl(rootCerts, keyCertPairs, checkClientCertificate = false) { - var _a; - if (rootCerts !== null && !Buffer.isBuffer(rootCerts)) { - throw new TypeError("rootCerts must be null or a Buffer"); - } - if (!Array.isArray(keyCertPairs)) { - throw new TypeError("keyCertPairs must be an array"); - } - if (typeof checkClientCertificate !== "boolean") { - throw new TypeError("checkClientCertificate must be a boolean"); - } - const cert = []; - const key = []; - for (let i = 0; i < keyCertPairs.length; i++) { - const pair = keyCertPairs[i]; - if (pair === null || typeof pair !== "object") { - throw new TypeError(`keyCertPair[${i}] must be an object`); - } - if (!Buffer.isBuffer(pair.private_key)) { - throw new TypeError(`keyCertPair[${i}].private_key must be a Buffer`); - } - if (!Buffer.isBuffer(pair.cert_chain)) { - throw new TypeError(`keyCertPair[${i}].cert_chain must be a Buffer`); - } - cert.push(pair.cert_chain); - key.push(pair.private_key); - } - return new SecureServerCredentials({ - requestCert: checkClientCertificate, - ciphers: tls_helpers_1.CIPHER_SUITES - }, { - ca: (_a = rootCerts !== null && rootCerts !== void 0 ? rootCerts : (0, tls_helpers_1.getDefaultRootsData)()) !== null && _a !== void 0 ? _a : void 0, - cert, - key - }); - } - }; - exports2.ServerCredentials = ServerCredentials; - var InsecureServerCredentials = class _InsecureServerCredentials extends ServerCredentials { - constructor() { - super(null); - } - _getSettings() { - return null; - } - _equals(other) { - return other instanceof _InsecureServerCredentials; - } - }; - var SecureServerCredentials = class _SecureServerCredentials extends ServerCredentials { - constructor(constructorOptions, contextOptions) { - super(constructorOptions, contextOptions); - this.options = Object.assign(Object.assign({}, constructorOptions), contextOptions); - } - /** - * Checks equality by checking the options that are actually set by - * createSsl. - * @param other - * @returns - */ - _equals(other) { - if (this === other) { - return true; - } - if (!(other instanceof _SecureServerCredentials)) { - return false; - } - if (Buffer.isBuffer(this.options.ca) && Buffer.isBuffer(other.options.ca)) { - if (!this.options.ca.equals(other.options.ca)) { - return false; - } - } else { - if (this.options.ca !== other.options.ca) { - return false; - } - } - if (Array.isArray(this.options.cert) && Array.isArray(other.options.cert)) { - if (this.options.cert.length !== other.options.cert.length) { - return false; - } - for (let i = 0; i < this.options.cert.length; i++) { - const thisCert = this.options.cert[i]; - const otherCert = other.options.cert[i]; - if (Buffer.isBuffer(thisCert) && Buffer.isBuffer(otherCert)) { - if (!thisCert.equals(otherCert)) { - return false; - } - } else { - if (thisCert !== otherCert) { - return false; - } - } - } - } else { - if (this.options.cert !== other.options.cert) { - return false; - } - } - if (Array.isArray(this.options.key) && Array.isArray(other.options.key)) { - if (this.options.key.length !== other.options.key.length) { - return false; - } - for (let i = 0; i < this.options.key.length; i++) { - const thisKey = this.options.key[i]; - const otherKey = other.options.key[i]; - if (Buffer.isBuffer(thisKey) && Buffer.isBuffer(otherKey)) { - if (!thisKey.equals(otherKey)) { - return false; - } - } else { - if (thisKey !== otherKey) { - return false; - } - } - } - } else { - if (this.options.key !== other.options.key) { - return false; - } - } - if (this.options.requestCert !== other.options.requestCert) { - return false; - } - return true; - } - }; - var CertificateProviderServerCredentials = class _CertificateProviderServerCredentials extends ServerCredentials { - constructor(identityCertificateProvider, caCertificateProvider, requireClientCertificate) { - super({ - requestCert: caCertificateProvider !== null, - rejectUnauthorized: requireClientCertificate, - ciphers: tls_helpers_1.CIPHER_SUITES - }); - this.identityCertificateProvider = identityCertificateProvider; - this.caCertificateProvider = caCertificateProvider; - this.requireClientCertificate = requireClientCertificate; - this.latestCaUpdate = null; - this.latestIdentityUpdate = null; - this.caCertificateUpdateListener = this.handleCaCertificateUpdate.bind(this); - this.identityCertificateUpdateListener = this.handleIdentityCertitificateUpdate.bind(this); - } - _addWatcher(watcher) { - var _a; - if (this.getWatcherCount() === 0) { - (_a = this.caCertificateProvider) === null || _a === void 0 ? void 0 : _a.addCaCertificateListener(this.caCertificateUpdateListener); - this.identityCertificateProvider.addIdentityCertificateListener(this.identityCertificateUpdateListener); - } - super._addWatcher(watcher); - } - _removeWatcher(watcher) { - var _a; - super._removeWatcher(watcher); - if (this.getWatcherCount() === 0) { - (_a = this.caCertificateProvider) === null || _a === void 0 ? void 0 : _a.removeCaCertificateListener(this.caCertificateUpdateListener); - this.identityCertificateProvider.removeIdentityCertificateListener(this.identityCertificateUpdateListener); - } - } - _equals(other) { - if (this === other) { - return true; - } - if (!(other instanceof _CertificateProviderServerCredentials)) { - return false; - } - return this.caCertificateProvider === other.caCertificateProvider && this.identityCertificateProvider === other.identityCertificateProvider && this.requireClientCertificate === other.requireClientCertificate; - } - calculateSecureContextOptions() { - var _a; - if (this.latestIdentityUpdate === null) { - return null; - } - if (this.caCertificateProvider !== null && this.latestCaUpdate === null) { - return null; - } - return { - ca: (_a = this.latestCaUpdate) === null || _a === void 0 ? void 0 : _a.caCertificate, - cert: [this.latestIdentityUpdate.certificate], - key: [this.latestIdentityUpdate.privateKey] - }; - } - finalizeUpdate() { - const secureContextOptions = this.calculateSecureContextOptions(); - this.updateSecureContextOptions(secureContextOptions); - } - handleCaCertificateUpdate(update) { - this.latestCaUpdate = update; - this.finalizeUpdate(); - } - handleIdentityCertitificateUpdate(update) { - this.latestIdentityUpdate = update; - this.finalizeUpdate(); - } - }; - function createCertificateProviderServerCredentials(caCertificateProvider, identityCertificateProvider, requireClientCertificate) { - return new CertificateProviderServerCredentials(caCertificateProvider, identityCertificateProvider, requireClientCertificate); - } - var InterceptorServerCredentials = class _InterceptorServerCredentials extends ServerCredentials { - constructor(childCredentials, interceptors) { - super({}); - this.childCredentials = childCredentials; - this.interceptors = interceptors; - } - _isSecure() { - return this.childCredentials._isSecure(); - } - _equals(other) { - if (!(other instanceof _InterceptorServerCredentials)) { - return false; - } - if (!this.childCredentials._equals(other.childCredentials)) { - return false; - } - if (this.interceptors.length !== other.interceptors.length) { - return false; - } - for (let i = 0; i < this.interceptors.length; i++) { - if (this.interceptors[i] !== other.interceptors[i]) { - return false; - } - } - return true; - } - _getInterceptors() { - return this.interceptors; - } - _addWatcher(watcher) { - this.childCredentials._addWatcher(watcher); - } - _removeWatcher(watcher) { - this.childCredentials._removeWatcher(watcher); - } - _getConstructorOptions() { - return this.childCredentials._getConstructorOptions(); - } - _getSecureContextOptions() { - return this.childCredentials._getSecureContextOptions(); - } - }; - function createServerCredentialsWithInterceptors(credentials, interceptors) { - return new InterceptorServerCredentials(credentials, interceptors); - } - } -}); - -// node_modules/@grpc/grpc-js/build/src/duration.js -var require_duration = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/duration.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.durationMessageToDuration = durationMessageToDuration; - exports2.msToDuration = msToDuration; - exports2.durationToMs = durationToMs; - exports2.isDuration = isDuration; - exports2.isDurationMessage = isDurationMessage; - exports2.parseDuration = parseDuration; - exports2.durationToString = durationToString; - function durationMessageToDuration(message) { - return { - seconds: Number.parseInt(message.seconds), - nanos: message.nanos - }; - } - function msToDuration(millis) { - return { - seconds: millis / 1e3 | 0, - nanos: millis % 1e3 * 1e6 | 0 - }; - } - function durationToMs(duration) { - return duration.seconds * 1e3 + duration.nanos / 1e6 | 0; - } - function isDuration(value) { - return typeof value.seconds === "number" && typeof value.nanos === "number"; - } - function isDurationMessage(value) { - return typeof value.seconds === "string" && typeof value.nanos === "number"; - } - var durationRegex = /^(\d+)(?:\.(\d+))?s$/; - function parseDuration(value) { - const match = value.match(durationRegex); - if (!match) { - return null; - } - return { - seconds: Number.parseInt(match[1], 10), - nanos: match[2] ? Number.parseInt(match[2].padEnd(9, "0"), 10) : 0 - }; - } - function durationToString(duration) { - if (duration.nanos === 0) { - return `${duration.seconds}s`; - } - let scaleFactor; - if (duration.nanos % 1e6 === 0) { - scaleFactor = 1e6; - } else if (duration.nanos % 1e3 === 0) { - scaleFactor = 1e3; - } else { - scaleFactor = 1; - } - return `${duration.seconds}.${duration.nanos / scaleFactor}s`; - } - } -}); - -// node_modules/@grpc/grpc-js/build/src/orca.js -var require_orca = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/orca.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.OrcaOobMetricsSubchannelWrapper = exports2.GRPC_METRICS_HEADER = exports2.ServerMetricRecorder = exports2.PerRequestMetricRecorder = void 0; - exports2.createOrcaClient = createOrcaClient; - exports2.createMetricsReader = createMetricsReader; - var make_client_1 = require_make_client(); - var duration_1 = require_duration(); - var channel_credentials_1 = require_channel_credentials(); - var subchannel_interface_1 = require_subchannel_interface(); - var constants_1 = require_constants7(); - var backoff_timeout_1 = require_backoff_timeout(); - var connectivity_state_1 = require_connectivity_state(); - var loadedOrcaProto = null; - function loadOrcaProto() { - if (loadedOrcaProto) { - return loadedOrcaProto; - } - const loaderLoadSync = require_src3().loadSync; - const loadedProto = loaderLoadSync("xds/service/orca/v3/orca.proto", { - keepCase: true, - longs: String, - enums: String, - defaults: true, - oneofs: true, - includeDirs: [ - `${__dirname}/../../proto/xds`, - `${__dirname}/../../proto/protoc-gen-validate` - ] - }); - return (0, make_client_1.loadPackageDefinition)(loadedProto); - } - var PerRequestMetricRecorder = class { - constructor() { - this.message = {}; - } - /** - * Records a request cost metric measurement for the call. - * @param name - * @param value - */ - recordRequestCostMetric(name, value) { - if (!this.message.request_cost) { - this.message.request_cost = {}; - } - this.message.request_cost[name] = value; - } - /** - * Records a request cost metric measurement for the call. - * @param name - * @param value - */ - recordUtilizationMetric(name, value) { - if (!this.message.utilization) { - this.message.utilization = {}; - } - this.message.utilization[name] = value; - } - /** - * Records an opaque named metric measurement for the call. - * @param name - * @param value - */ - recordNamedMetric(name, value) { - if (!this.message.named_metrics) { - this.message.named_metrics = {}; - } - this.message.named_metrics[name] = value; - } - /** - * Records the CPU utilization metric measurement for the call. - * @param value - */ - recordCPUUtilizationMetric(value) { - this.message.cpu_utilization = value; - } - /** - * Records the memory utilization metric measurement for the call. - * @param value - */ - recordMemoryUtilizationMetric(value) { - this.message.mem_utilization = value; - } - /** - * Records the memory utilization metric measurement for the call. - * @param value - */ - recordApplicationUtilizationMetric(value) { - this.message.application_utilization = value; - } - /** - * Records the queries per second measurement. - * @param value - */ - recordQpsMetric(value) { - this.message.rps_fractional = value; - } - /** - * Records the errors per second measurement. - * @param value - */ - recordEpsMetric(value) { - this.message.eps = value; - } - serialize() { - const orcaProto = loadOrcaProto(); - return orcaProto.xds.data.orca.v3.OrcaLoadReport.serialize(this.message); - } - }; - exports2.PerRequestMetricRecorder = PerRequestMetricRecorder; - var DEFAULT_REPORT_INTERVAL_MS = 3e4; - var ServerMetricRecorder = class { - constructor() { - this.message = {}; - this.serviceImplementation = { - StreamCoreMetrics: (call) => { - const reportInterval = call.request.report_interval ? (0, duration_1.durationToMs)((0, duration_1.durationMessageToDuration)(call.request.report_interval)) : DEFAULT_REPORT_INTERVAL_MS; - const reportTimer = setInterval(() => { - call.write(this.message); - }, reportInterval); - call.on("cancelled", () => { - clearInterval(reportTimer); - }); - } - }; - } - putUtilizationMetric(name, value) { - if (!this.message.utilization) { - this.message.utilization = {}; - } - this.message.utilization[name] = value; - } - setAllUtilizationMetrics(metrics) { - this.message.utilization = Object.assign({}, metrics); - } - deleteUtilizationMetric(name) { - var _a; - (_a = this.message.utilization) === null || _a === void 0 ? true : delete _a[name]; - } - setCpuUtilizationMetric(value) { - this.message.cpu_utilization = value; - } - deleteCpuUtilizationMetric() { - delete this.message.cpu_utilization; - } - setApplicationUtilizationMetric(value) { - this.message.application_utilization = value; - } - deleteApplicationUtilizationMetric() { - delete this.message.application_utilization; - } - setQpsMetric(value) { - this.message.rps_fractional = value; - } - deleteQpsMetric() { - delete this.message.rps_fractional; - } - setEpsMetric(value) { - this.message.eps = value; - } - deleteEpsMetric() { - delete this.message.eps; - } - addToServer(server) { - const serviceDefinition = loadOrcaProto().xds.service.orca.v3.OpenRcaService.service; - server.addService(serviceDefinition, this.serviceImplementation); - } - }; - exports2.ServerMetricRecorder = ServerMetricRecorder; - function createOrcaClient(channel) { - const ClientClass = loadOrcaProto().xds.service.orca.v3.OpenRcaService; - return new ClientClass("unused", channel_credentials_1.ChannelCredentials.createInsecure(), { channelOverride: channel }); - } - exports2.GRPC_METRICS_HEADER = "endpoint-load-metrics-bin"; - var PARSED_LOAD_REPORT_KEY = "grpc_orca_load_report"; - function createMetricsReader(listener, previousOnCallEnded) { - return (code, details, metadata) => { - let parsedLoadReport = metadata.getOpaque(PARSED_LOAD_REPORT_KEY); - if (parsedLoadReport) { - listener(parsedLoadReport); - } else { - const serializedLoadReport = metadata.get(exports2.GRPC_METRICS_HEADER); - if (serializedLoadReport.length > 0) { - const orcaProto = loadOrcaProto(); - parsedLoadReport = orcaProto.xds.data.orca.v3.OrcaLoadReport.deserialize(serializedLoadReport[0]); - listener(parsedLoadReport); - metadata.setOpaque(PARSED_LOAD_REPORT_KEY, parsedLoadReport); - } - } - if (previousOnCallEnded) { - previousOnCallEnded(code, details, metadata); - } - }; - } - var DATA_PRODUCER_KEY = "orca_oob_metrics"; - var OobMetricsDataWatcher = class { - constructor(metricsListener, intervalMs) { - this.metricsListener = metricsListener; - this.intervalMs = intervalMs; - this.dataProducer = null; - } - setSubchannel(subchannel) { - const producer = subchannel.getOrCreateDataProducer(DATA_PRODUCER_KEY, createOobMetricsDataProducer); - this.dataProducer = producer; - producer.addDataWatcher(this); - } - destroy() { - var _a; - (_a = this.dataProducer) === null || _a === void 0 ? void 0 : _a.removeDataWatcher(this); - } - getInterval() { - return this.intervalMs; - } - onMetricsUpdate(metrics) { - this.metricsListener(metrics); - } - }; - var OobMetricsDataProducer = class { - constructor(subchannel) { - this.subchannel = subchannel; - this.dataWatchers = /* @__PURE__ */ new Set(); - this.orcaSupported = true; - this.metricsCall = null; - this.currentInterval = Infinity; - this.backoffTimer = new backoff_timeout_1.BackoffTimeout(() => this.updateMetricsSubscription()); - this.subchannelStateListener = () => this.updateMetricsSubscription(); - const channel = subchannel.getChannel(); - this.client = createOrcaClient(channel); - subchannel.addConnectivityStateListener(this.subchannelStateListener); - } - addDataWatcher(dataWatcher) { - this.dataWatchers.add(dataWatcher); - this.updateMetricsSubscription(); - } - removeDataWatcher(dataWatcher) { - var _a; - this.dataWatchers.delete(dataWatcher); - if (this.dataWatchers.size === 0) { - this.subchannel.removeDataProducer(DATA_PRODUCER_KEY); - (_a = this.metricsCall) === null || _a === void 0 ? void 0 : _a.cancel(); - this.metricsCall = null; - this.client.close(); - this.subchannel.removeConnectivityStateListener(this.subchannelStateListener); - } else { - this.updateMetricsSubscription(); - } - } - updateMetricsSubscription() { - var _a; - if (this.dataWatchers.size === 0 || !this.orcaSupported || this.subchannel.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) { - return; - } - const newInterval = Math.min(...Array.from(this.dataWatchers).map((watcher) => watcher.getInterval())); - if (!this.metricsCall || newInterval !== this.currentInterval) { - (_a = this.metricsCall) === null || _a === void 0 ? void 0 : _a.cancel(); - this.currentInterval = newInterval; - const metricsCall = this.client.streamCoreMetrics({ report_interval: (0, duration_1.msToDuration)(newInterval) }); - this.metricsCall = metricsCall; - metricsCall.on("data", (report) => { - this.dataWatchers.forEach((watcher) => { - watcher.onMetricsUpdate(report); - }); - }); - metricsCall.on("error", (error3) => { - this.metricsCall = null; - if (error3.code === constants_1.Status.UNIMPLEMENTED) { - this.orcaSupported = false; - return; - } - if (error3.code === constants_1.Status.CANCELLED) { - return; - } - this.backoffTimer.runOnce(); - }); - } - } - }; - var OrcaOobMetricsSubchannelWrapper = class extends subchannel_interface_1.BaseSubchannelWrapper { - constructor(child, metricsListener, intervalMs) { - super(child); - this.addDataWatcher(new OobMetricsDataWatcher(metricsListener, intervalMs)); - } - getWrappedSubchannel() { - return this.child; - } - }; - exports2.OrcaOobMetricsSubchannelWrapper = OrcaOobMetricsSubchannelWrapper; - function createOobMetricsDataProducer(subchannel) { - return new OobMetricsDataProducer(subchannel); - } - } -}); - -// node_modules/@grpc/grpc-js/build/src/server-interceptors.js -var require_server_interceptors = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/server-interceptors.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BaseServerInterceptingCall = exports2.ServerInterceptingCall = exports2.ResponderBuilder = exports2.ServerListenerBuilder = void 0; - exports2.isInterceptingServerListener = isInterceptingServerListener; - exports2.getServerInterceptingCall = getServerInterceptingCall; - var metadata_1 = require_metadata(); - var constants_1 = require_constants7(); - var http2 = require("http2"); - var error_1 = require_error(); - var zlib = require("zlib"); - var stream_decoder_1 = require_stream_decoder(); - var logging = require_logging(); - var tls_1 = require("tls"); - var orca_1 = require_orca(); - var TRACER_NAME = "server_call"; - function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); - } - var ServerListenerBuilder = class { - constructor() { - this.metadata = void 0; - this.message = void 0; - this.halfClose = void 0; - this.cancel = void 0; - } - withOnReceiveMetadata(onReceiveMetadata) { - this.metadata = onReceiveMetadata; - return this; - } - withOnReceiveMessage(onReceiveMessage) { - this.message = onReceiveMessage; - return this; - } - withOnReceiveHalfClose(onReceiveHalfClose) { - this.halfClose = onReceiveHalfClose; - return this; - } - withOnCancel(onCancel) { - this.cancel = onCancel; - return this; - } - build() { - return { - onReceiveMetadata: this.metadata, - onReceiveMessage: this.message, - onReceiveHalfClose: this.halfClose, - onCancel: this.cancel - }; - } - }; - exports2.ServerListenerBuilder = ServerListenerBuilder; - function isInterceptingServerListener(listener) { - return listener.onReceiveMetadata !== void 0 && listener.onReceiveMetadata.length === 1; - } - var InterceptingServerListenerImpl = class { - constructor(listener, nextListener) { - this.listener = listener; - this.nextListener = nextListener; - this.cancelled = false; - this.processingMetadata = false; - this.hasPendingMessage = false; - this.pendingMessage = null; - this.processingMessage = false; - this.hasPendingHalfClose = false; - } - processPendingMessage() { - if (this.hasPendingMessage) { - this.nextListener.onReceiveMessage(this.pendingMessage); - this.pendingMessage = null; - this.hasPendingMessage = false; - } - } - processPendingHalfClose() { - if (this.hasPendingHalfClose) { - this.nextListener.onReceiveHalfClose(); - this.hasPendingHalfClose = false; - } - } - onReceiveMetadata(metadata) { - if (this.cancelled) { - return; - } - this.processingMetadata = true; - this.listener.onReceiveMetadata(metadata, (interceptedMetadata) => { - this.processingMetadata = false; - if (this.cancelled) { - return; - } - this.nextListener.onReceiveMetadata(interceptedMetadata); - this.processPendingMessage(); - this.processPendingHalfClose(); - }); - } - onReceiveMessage(message) { - if (this.cancelled) { - return; - } - this.processingMessage = true; - this.listener.onReceiveMessage(message, (msg) => { - this.processingMessage = false; - if (this.cancelled) { - return; - } - if (this.processingMetadata) { - this.pendingMessage = msg; - this.hasPendingMessage = true; - } else { - this.nextListener.onReceiveMessage(msg); - this.processPendingHalfClose(); - } - }); - } - onReceiveHalfClose() { - if (this.cancelled) { - return; - } - this.listener.onReceiveHalfClose(() => { - if (this.cancelled) { - return; - } - if (this.processingMetadata || this.processingMessage) { - this.hasPendingHalfClose = true; - } else { - this.nextListener.onReceiveHalfClose(); - } - }); - } - onCancel() { - this.cancelled = true; - this.listener.onCancel(); - this.nextListener.onCancel(); - } - }; - var ResponderBuilder = class { - constructor() { - this.start = void 0; - this.metadata = void 0; - this.message = void 0; - this.status = void 0; - } - withStart(start) { - this.start = start; - return this; - } - withSendMetadata(sendMetadata) { - this.metadata = sendMetadata; - return this; - } - withSendMessage(sendMessage) { - this.message = sendMessage; - return this; - } - withSendStatus(sendStatus) { - this.status = sendStatus; - return this; - } - build() { - return { - start: this.start, - sendMetadata: this.metadata, - sendMessage: this.message, - sendStatus: this.status - }; - } - }; - exports2.ResponderBuilder = ResponderBuilder; - var defaultServerListener = { - onReceiveMetadata: (metadata, next) => { - next(metadata); - }, - onReceiveMessage: (message, next) => { - next(message); - }, - onReceiveHalfClose: (next) => { - next(); - }, - onCancel: () => { - } - }; - var defaultResponder = { - start: (next) => { - next(); - }, - sendMetadata: (metadata, next) => { - next(metadata); - }, - sendMessage: (message, next) => { - next(message); - }, - sendStatus: (status, next) => { - next(status); - } - }; - var ServerInterceptingCall = class { - constructor(nextCall, responder) { - var _a, _b, _c, _d; - this.nextCall = nextCall; - this.processingMetadata = false; - this.sentMetadata = false; - this.processingMessage = false; - this.pendingMessage = null; - this.pendingMessageCallback = null; - this.pendingStatus = null; - this.responder = { - start: (_a = responder === null || responder === void 0 ? void 0 : responder.start) !== null && _a !== void 0 ? _a : defaultResponder.start, - sendMetadata: (_b = responder === null || responder === void 0 ? void 0 : responder.sendMetadata) !== null && _b !== void 0 ? _b : defaultResponder.sendMetadata, - sendMessage: (_c = responder === null || responder === void 0 ? void 0 : responder.sendMessage) !== null && _c !== void 0 ? _c : defaultResponder.sendMessage, - sendStatus: (_d = responder === null || responder === void 0 ? void 0 : responder.sendStatus) !== null && _d !== void 0 ? _d : defaultResponder.sendStatus - }; - } - processPendingMessage() { - if (this.pendingMessageCallback) { - this.nextCall.sendMessage(this.pendingMessage, this.pendingMessageCallback); - this.pendingMessage = null; - this.pendingMessageCallback = null; - } - } - processPendingStatus() { - if (this.pendingStatus) { - this.nextCall.sendStatus(this.pendingStatus); - this.pendingStatus = null; - } - } - start(listener) { - this.responder.start((interceptedListener) => { - var _a, _b, _c, _d; - const fullInterceptedListener = { - onReceiveMetadata: (_a = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onReceiveMetadata) !== null && _a !== void 0 ? _a : defaultServerListener.onReceiveMetadata, - onReceiveMessage: (_b = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onReceiveMessage) !== null && _b !== void 0 ? _b : defaultServerListener.onReceiveMessage, - onReceiveHalfClose: (_c = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onReceiveHalfClose) !== null && _c !== void 0 ? _c : defaultServerListener.onReceiveHalfClose, - onCancel: (_d = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onCancel) !== null && _d !== void 0 ? _d : defaultServerListener.onCancel - }; - const finalInterceptingListener = new InterceptingServerListenerImpl(fullInterceptedListener, listener); - this.nextCall.start(finalInterceptingListener); - }); - } - sendMetadata(metadata) { - this.processingMetadata = true; - this.sentMetadata = true; - this.responder.sendMetadata(metadata, (interceptedMetadata) => { - this.processingMetadata = false; - this.nextCall.sendMetadata(interceptedMetadata); - this.processPendingMessage(); - this.processPendingStatus(); - }); - } - sendMessage(message, callback) { - this.processingMessage = true; - if (!this.sentMetadata) { - this.sendMetadata(new metadata_1.Metadata()); - } - this.responder.sendMessage(message, (interceptedMessage) => { - this.processingMessage = false; - if (this.processingMetadata) { - this.pendingMessage = interceptedMessage; - this.pendingMessageCallback = callback; - } else { - this.nextCall.sendMessage(interceptedMessage, callback); - } - }); - } - sendStatus(status) { - this.responder.sendStatus(status, (interceptedStatus) => { - if (this.processingMetadata || this.processingMessage) { - this.pendingStatus = interceptedStatus; - } else { - this.nextCall.sendStatus(interceptedStatus); - } - }); - } - startRead() { - this.nextCall.startRead(); - } - getPeer() { - return this.nextCall.getPeer(); - } - getDeadline() { - return this.nextCall.getDeadline(); - } - getHost() { - return this.nextCall.getHost(); - } - getAuthContext() { - return this.nextCall.getAuthContext(); - } - getConnectionInfo() { - return this.nextCall.getConnectionInfo(); - } - getMetricsRecorder() { - return this.nextCall.getMetricsRecorder(); - } - }; - exports2.ServerInterceptingCall = ServerInterceptingCall; - var GRPC_ACCEPT_ENCODING_HEADER = "grpc-accept-encoding"; - var GRPC_ENCODING_HEADER = "grpc-encoding"; - var GRPC_MESSAGE_HEADER = "grpc-message"; - var GRPC_STATUS_HEADER = "grpc-status"; - var GRPC_TIMEOUT_HEADER = "grpc-timeout"; - var DEADLINE_REGEX = /(\d{1,8})\s*([HMSmun])/; - var deadlineUnitsToMs = { - H: 36e5, - M: 6e4, - S: 1e3, - m: 1, - u: 1e-3, - n: 1e-6 - }; - var defaultCompressionHeaders = { - // TODO(cjihrig): Remove these encoding headers from the default response - // once compression is integrated. - [GRPC_ACCEPT_ENCODING_HEADER]: "identity,deflate,gzip", - [GRPC_ENCODING_HEADER]: "identity" - }; - var defaultResponseHeaders = { - [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_OK, - [http2.constants.HTTP2_HEADER_CONTENT_TYPE]: "application/grpc+proto" - }; - var defaultResponseOptions = { - waitForTrailers: true - }; - var BaseServerInterceptingCall = class { - constructor(stream2, headers, callEventTracker, handler2, options) { - var _a, _b; - this.stream = stream2; - this.callEventTracker = callEventTracker; - this.handler = handler2; - this.listener = null; - this.deadlineTimer = null; - this.deadline = Infinity; - this.maxSendMessageSize = constants_1.DEFAULT_MAX_SEND_MESSAGE_LENGTH; - this.maxReceiveMessageSize = constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH; - this.cancelled = false; - this.metadataSent = false; - this.wantTrailers = false; - this.cancelNotified = false; - this.incomingEncoding = "identity"; - this.readQueue = []; - this.isReadPending = false; - this.receivedHalfClose = false; - this.streamEnded = false; - this.metricsRecorder = new orca_1.PerRequestMetricRecorder(); - this.stream.once("close", () => { - var _a2; - trace("Request to method " + ((_a2 = this.handler) === null || _a2 === void 0 ? void 0 : _a2.path) + " stream closed with rstCode " + this.stream.rstCode); - if (this.callEventTracker && !this.streamEnded) { - this.streamEnded = true; - this.callEventTracker.onStreamEnd(false); - this.callEventTracker.onCallEnd({ - code: constants_1.Status.CANCELLED, - details: "Stream closed before sending status", - metadata: null - }); - } - this.notifyOnCancel(); - }); - this.stream.on("data", (data) => { - this.handleDataFrame(data); - }); - this.stream.pause(); - this.stream.on("end", () => { - this.handleEndEvent(); - }); - if ("grpc.max_send_message_length" in options) { - this.maxSendMessageSize = options["grpc.max_send_message_length"]; - } - if ("grpc.max_receive_message_length" in options) { - this.maxReceiveMessageSize = options["grpc.max_receive_message_length"]; - } - this.host = (_a = headers[":authority"]) !== null && _a !== void 0 ? _a : headers.host; - this.decoder = new stream_decoder_1.StreamDecoder(this.maxReceiveMessageSize); - const metadata = metadata_1.Metadata.fromHttp2Headers(headers); - if (logging.isTracerEnabled(TRACER_NAME)) { - trace("Request to " + this.handler.path + " received headers " + JSON.stringify(metadata.toJSON())); - } - const timeoutHeader = metadata.get(GRPC_TIMEOUT_HEADER); - if (timeoutHeader.length > 0) { - this.handleTimeoutHeader(timeoutHeader[0]); - } - const encodingHeader = metadata.get(GRPC_ENCODING_HEADER); - if (encodingHeader.length > 0) { - this.incomingEncoding = encodingHeader[0]; - } - metadata.remove(GRPC_TIMEOUT_HEADER); - metadata.remove(GRPC_ENCODING_HEADER); - metadata.remove(GRPC_ACCEPT_ENCODING_HEADER); - metadata.remove(http2.constants.HTTP2_HEADER_ACCEPT_ENCODING); - metadata.remove(http2.constants.HTTP2_HEADER_TE); - metadata.remove(http2.constants.HTTP2_HEADER_CONTENT_TYPE); - this.metadata = metadata; - const socket = (_b = stream2.session) === null || _b === void 0 ? void 0 : _b.socket; - this.connectionInfo = { - localAddress: socket === null || socket === void 0 ? void 0 : socket.localAddress, - localPort: socket === null || socket === void 0 ? void 0 : socket.localPort, - remoteAddress: socket === null || socket === void 0 ? void 0 : socket.remoteAddress, - remotePort: socket === null || socket === void 0 ? void 0 : socket.remotePort - }; - this.shouldSendMetrics = !!options["grpc.server_call_metric_recording"]; - } - handleTimeoutHeader(timeoutHeader) { - const match = timeoutHeader.toString().match(DEADLINE_REGEX); - if (match === null) { - const status = { - code: constants_1.Status.INTERNAL, - details: `Invalid ${GRPC_TIMEOUT_HEADER} value "${timeoutHeader}"`, - metadata: null - }; - process.nextTick(() => { - this.sendStatus(status); - }); - return; - } - const timeout = +match[1] * deadlineUnitsToMs[match[2]] | 0; - const now = /* @__PURE__ */ new Date(); - this.deadline = now.setMilliseconds(now.getMilliseconds() + timeout); - this.deadlineTimer = setTimeout(() => { - const status = { - code: constants_1.Status.DEADLINE_EXCEEDED, - details: "Deadline exceeded", - metadata: null - }; - this.sendStatus(status); - }, timeout); - } - checkCancelled() { - if (!this.cancelled && (this.stream.destroyed || this.stream.closed)) { - this.notifyOnCancel(); - this.cancelled = true; - } - return this.cancelled; - } - notifyOnCancel() { - if (this.cancelNotified) { - return; - } - this.cancelNotified = true; - this.cancelled = true; - process.nextTick(() => { - var _a; - (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onCancel(); - }); - if (this.deadlineTimer) { - clearTimeout(this.deadlineTimer); - } - this.stream.resume(); - } - /** - * A server handler can start sending messages without explicitly sending - * metadata. In that case, we need to send headers before sending any - * messages. This function does that if necessary. - */ - maybeSendMetadata() { - if (!this.metadataSent) { - this.sendMetadata(new metadata_1.Metadata()); - } - } - /** - * Serialize a message to a length-delimited byte string. - * @param value - * @returns - */ - serializeMessage(value) { - const messageBuffer = this.handler.serialize(value); - const byteLength = messageBuffer.byteLength; - const output = Buffer.allocUnsafe(byteLength + 5); - output.writeUInt8(0, 0); - output.writeUInt32BE(byteLength, 1); - messageBuffer.copy(output, 5); - return output; - } - decompressMessage(message, encoding) { - const messageContents = message.subarray(5); - if (encoding === "identity") { - return messageContents; - } else if (encoding === "deflate" || encoding === "gzip") { - let decompresser; - if (encoding === "deflate") { - decompresser = zlib.createInflate(); - } else { - decompresser = zlib.createGunzip(); - } - return new Promise((resolve, reject) => { - let totalLength = 0; - const messageParts = []; - decompresser.on("error", (error3) => { - reject({ - code: constants_1.Status.INTERNAL, - details: "Failed to decompress message" - }); - }); - decompresser.on("data", (chunk) => { - messageParts.push(chunk); - totalLength += chunk.byteLength; - if (this.maxReceiveMessageSize !== -1 && totalLength > this.maxReceiveMessageSize) { - decompresser.destroy(); - reject({ - code: constants_1.Status.RESOURCE_EXHAUSTED, - details: `Received message that decompresses to a size larger than ${this.maxReceiveMessageSize}` - }); - } - }); - decompresser.on("end", () => { - resolve(Buffer.concat(messageParts)); - }); - decompresser.write(messageContents); - decompresser.end(); - }); - } else { - return Promise.reject({ - code: constants_1.Status.UNIMPLEMENTED, - details: `Received message compressed with unsupported encoding "${encoding}"` - }); - } - } - async decompressAndMaybePush(queueEntry) { - if (queueEntry.type !== "COMPRESSED") { - throw new Error(`Invalid queue entry type: ${queueEntry.type}`); - } - const compressed = queueEntry.compressedMessage.readUInt8(0) === 1; - const compressedMessageEncoding = compressed ? this.incomingEncoding : "identity"; - let decompressedMessage; - try { - decompressedMessage = await this.decompressMessage(queueEntry.compressedMessage, compressedMessageEncoding); - } catch (err) { - this.sendStatus(err); - return; - } - try { - queueEntry.parsedMessage = this.handler.deserialize(decompressedMessage); - } catch (err) { - this.sendStatus({ - code: constants_1.Status.INTERNAL, - details: `Error deserializing request: ${err.message}` - }); - return; - } - queueEntry.type = "READABLE"; - this.maybePushNextMessage(); - } - maybePushNextMessage() { - if (this.listener && this.isReadPending && this.readQueue.length > 0 && this.readQueue[0].type !== "COMPRESSED") { - this.isReadPending = false; - const nextQueueEntry = this.readQueue.shift(); - if (nextQueueEntry.type === "READABLE") { - this.listener.onReceiveMessage(nextQueueEntry.parsedMessage); - } else { - this.listener.onReceiveHalfClose(); - } - } - } - handleDataFrame(data) { - var _a; - if (this.checkCancelled()) { - return; - } - trace("Request to " + this.handler.path + " received data frame of size " + data.length); - let rawMessages; - try { - rawMessages = this.decoder.write(data); - } catch (e) { - this.sendStatus({ code: constants_1.Status.RESOURCE_EXHAUSTED, details: e.message }); - return; - } - for (const messageBytes of rawMessages) { - this.stream.pause(); - const queueEntry = { - type: "COMPRESSED", - compressedMessage: messageBytes, - parsedMessage: null - }; - this.readQueue.push(queueEntry); - this.decompressAndMaybePush(queueEntry); - (_a = this.callEventTracker) === null || _a === void 0 ? void 0 : _a.addMessageReceived(); - } - } - handleEndEvent() { - this.readQueue.push({ - type: "HALF_CLOSE", - compressedMessage: null, - parsedMessage: null - }); - this.receivedHalfClose = true; - this.maybePushNextMessage(); - } - start(listener) { - trace("Request to " + this.handler.path + " start called"); - if (this.checkCancelled()) { - return; - } - this.listener = listener; - listener.onReceiveMetadata(this.metadata); - } - sendMetadata(metadata) { - if (this.checkCancelled()) { - return; - } - if (this.metadataSent) { - return; - } - this.metadataSent = true; - const custom = metadata ? metadata.toHttp2Headers() : null; - const headers = Object.assign(Object.assign(Object.assign({}, defaultResponseHeaders), defaultCompressionHeaders), custom); - this.stream.respond(headers, defaultResponseOptions); - } - sendMessage(message, callback) { - if (this.checkCancelled()) { - return; - } - let response; - try { - response = this.serializeMessage(message); - } catch (e) { - this.sendStatus({ - code: constants_1.Status.INTERNAL, - details: `Error serializing response: ${(0, error_1.getErrorMessage)(e)}`, - metadata: null - }); - return; - } - if (this.maxSendMessageSize !== -1 && response.length - 5 > this.maxSendMessageSize) { - this.sendStatus({ - code: constants_1.Status.RESOURCE_EXHAUSTED, - details: `Sent message larger than max (${response.length} vs. ${this.maxSendMessageSize})`, - metadata: null - }); - return; - } - this.maybeSendMetadata(); - trace("Request to " + this.handler.path + " sent data frame of size " + response.length); - this.stream.write(response, (error3) => { - var _a; - if (error3) { - this.sendStatus({ - code: constants_1.Status.INTERNAL, - details: `Error writing message: ${(0, error_1.getErrorMessage)(error3)}`, - metadata: null - }); - return; - } - (_a = this.callEventTracker) === null || _a === void 0 ? void 0 : _a.addMessageSent(); - callback(); - }); - } - sendStatus(status) { - var _a, _b, _c; - if (this.checkCancelled()) { - return; - } - trace("Request to method " + ((_a = this.handler) === null || _a === void 0 ? void 0 : _a.path) + " ended with status code: " + constants_1.Status[status.code] + " details: " + status.details); - const statusMetadata = (_c = (_b = status.metadata) === null || _b === void 0 ? void 0 : _b.clone()) !== null && _c !== void 0 ? _c : new metadata_1.Metadata(); - if (this.shouldSendMetrics) { - statusMetadata.set(orca_1.GRPC_METRICS_HEADER, this.metricsRecorder.serialize()); - } - if (this.metadataSent) { - if (!this.wantTrailers) { - this.wantTrailers = true; - this.stream.once("wantTrailers", () => { - if (this.callEventTracker && !this.streamEnded) { - this.streamEnded = true; - this.callEventTracker.onStreamEnd(true); - this.callEventTracker.onCallEnd(status); - } - const trailersToSend = Object.assign({ [GRPC_STATUS_HEADER]: status.code, [GRPC_MESSAGE_HEADER]: encodeURI(status.details) }, statusMetadata.toHttp2Headers()); - this.stream.sendTrailers(trailersToSend); - this.notifyOnCancel(); - }); - this.stream.end(); - } else { - this.notifyOnCancel(); - } - } else { - if (this.callEventTracker && !this.streamEnded) { - this.streamEnded = true; - this.callEventTracker.onStreamEnd(true); - this.callEventTracker.onCallEnd(status); - } - const trailersToSend = Object.assign(Object.assign({ [GRPC_STATUS_HEADER]: status.code, [GRPC_MESSAGE_HEADER]: encodeURI(status.details) }, defaultResponseHeaders), statusMetadata.toHttp2Headers()); - this.stream.respond(trailersToSend, { endStream: true }); - this.notifyOnCancel(); - } - } - startRead() { - trace("Request to " + this.handler.path + " startRead called"); - if (this.checkCancelled()) { - return; - } - this.isReadPending = true; - if (this.readQueue.length === 0) { - if (!this.receivedHalfClose) { - this.stream.resume(); - } - } else { - this.maybePushNextMessage(); - } - } - getPeer() { - var _a; - const socket = (_a = this.stream.session) === null || _a === void 0 ? void 0 : _a.socket; - if (socket === null || socket === void 0 ? void 0 : socket.remoteAddress) { - if (socket.remotePort) { - return `${socket.remoteAddress}:${socket.remotePort}`; - } else { - return socket.remoteAddress; - } - } else { - return "unknown"; - } - } - getDeadline() { - return this.deadline; - } - getHost() { - return this.host; - } - getAuthContext() { - var _a; - if (((_a = this.stream.session) === null || _a === void 0 ? void 0 : _a.socket) instanceof tls_1.TLSSocket) { - const peerCertificate = this.stream.session.socket.getPeerCertificate(); - return { - transportSecurityType: "ssl", - sslPeerCertificate: peerCertificate.raw ? peerCertificate : void 0 - }; - } else { - return {}; - } - } - getConnectionInfo() { - return this.connectionInfo; - } - getMetricsRecorder() { - return this.metricsRecorder; - } - }; - exports2.BaseServerInterceptingCall = BaseServerInterceptingCall; - function getServerInterceptingCall(interceptors, stream2, headers, callEventTracker, handler2, options) { - const methodDefinition = { - path: handler2.path, - requestStream: handler2.type === "clientStream" || handler2.type === "bidi", - responseStream: handler2.type === "serverStream" || handler2.type === "bidi", - requestDeserialize: handler2.deserialize, - responseSerialize: handler2.serialize - }; - const baseCall = new BaseServerInterceptingCall(stream2, headers, callEventTracker, handler2, options); - return interceptors.reduce((call, interceptor) => { - return interceptor(methodDefinition, call); - }, baseCall); - } - } -}); - -// node_modules/@grpc/grpc-js/build/src/server.js -var require_server2 = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/server.js"(exports2) { - "use strict"; - var __runInitializers = exports2 && exports2.__runInitializers || function(thisArg, initializers, value) { - var useValue = arguments.length > 2; - for (var i = 0; i < initializers.length; i++) { - value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); - } - return useValue ? value : void 0; - }; - var __esDecorate = exports2 && exports2.__esDecorate || function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { - function accept(f) { - if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); - return f; - } - var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; - var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; - var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); - var _, done = false; - for (var i = decorators.length - 1; i >= 0; i--) { - var context3 = {}; - for (var p in contextIn) context3[p] = p === "access" ? {} : contextIn[p]; - for (var p in contextIn.access) context3.access[p] = contextIn.access[p]; - context3.addInitializer = function(f) { - if (done) throw new TypeError("Cannot add initializers after decoration has completed"); - extraInitializers.push(accept(f || null)); - }; - var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context3); - if (kind === "accessor") { - if (result === void 0) continue; - if (result === null || typeof result !== "object") throw new TypeError("Object expected"); - if (_ = accept(result.get)) descriptor.get = _; - if (_ = accept(result.set)) descriptor.set = _; - if (_ = accept(result.init)) initializers.unshift(_); - } else if (_ = accept(result)) { - if (kind === "field") initializers.unshift(_); - else descriptor[key] = _; - } - } - if (target) Object.defineProperty(target, contextIn.name, descriptor); - done = true; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Server = void 0; - var http2 = require("http2"); - var util = require("util"); - var constants_1 = require_constants7(); - var server_call_1 = require_server_call(); - var server_credentials_1 = require_server_credentials(); - var resolver_1 = require_resolver(); - var logging = require_logging(); - var subchannel_address_1 = require_subchannel_address(); - var uri_parser_1 = require_uri_parser(); - var channelz_1 = require_channelz(); - var server_interceptors_1 = require_server_interceptors(); - var UNLIMITED_CONNECTION_AGE_MS = ~(1 << 31); - var KEEPALIVE_MAX_TIME_MS = ~(1 << 31); - var KEEPALIVE_TIMEOUT_MS = 2e4; - var MAX_CONNECTION_IDLE_MS = ~(1 << 31); - var { HTTP2_HEADER_PATH } = http2.constants; - var TRACER_NAME = "server"; - var kMaxAge = Buffer.from("max_age"); - function serverCallTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, "server_call", text); - } - function noop3() { - } - function deprecate(message) { - return function(target, context3) { - return util.deprecate(target, message); - }; - } - function getUnimplementedStatusResponse(methodName) { - return { - code: constants_1.Status.UNIMPLEMENTED, - details: `The server does not implement the method ${methodName}` - }; - } - function getDefaultHandler(handlerType, methodName) { - const unimplementedStatusResponse = getUnimplementedStatusResponse(methodName); - switch (handlerType) { - case "unary": - return (call, callback) => { - callback(unimplementedStatusResponse, null); - }; - case "clientStream": - return (call, callback) => { - callback(unimplementedStatusResponse, null); - }; - case "serverStream": - return (call) => { - call.emit("error", unimplementedStatusResponse); - }; - case "bidi": - return (call) => { - call.emit("error", unimplementedStatusResponse); - }; - default: - throw new Error(`Invalid handlerType ${handlerType}`); - } - } - var Server = (() => { - var _a; - let _instanceExtraInitializers = []; - let _start_decorators; - return _a = class Server { - constructor(options) { - var _b, _c, _d, _e, _f, _g; - this.boundPorts = (__runInitializers(this, _instanceExtraInitializers), /* @__PURE__ */ new Map()); - this.http2Servers = /* @__PURE__ */ new Map(); - this.sessionIdleTimeouts = /* @__PURE__ */ new Map(); - this.handlers = /* @__PURE__ */ new Map(); - this.sessions = /* @__PURE__ */ new Map(); - this.started = false; - this.shutdown = false; - this.serverAddressString = "null"; - this.channelzEnabled = true; - this.options = options !== null && options !== void 0 ? options : {}; - if (this.options["grpc.enable_channelz"] === 0) { - this.channelzEnabled = false; - this.channelzTrace = new channelz_1.ChannelzTraceStub(); - this.callTracker = new channelz_1.ChannelzCallTrackerStub(); - this.listenerChildrenTracker = new channelz_1.ChannelzChildrenTrackerStub(); - this.sessionChildrenTracker = new channelz_1.ChannelzChildrenTrackerStub(); - } else { - this.channelzTrace = new channelz_1.ChannelzTrace(); - this.callTracker = new channelz_1.ChannelzCallTracker(); - this.listenerChildrenTracker = new channelz_1.ChannelzChildrenTracker(); - this.sessionChildrenTracker = new channelz_1.ChannelzChildrenTracker(); - } - this.channelzRef = (0, channelz_1.registerChannelzServer)("server", () => this.getChannelzInfo(), this.channelzEnabled); - this.channelzTrace.addTrace("CT_INFO", "Server created"); - this.maxConnectionAgeMs = (_b = this.options["grpc.max_connection_age_ms"]) !== null && _b !== void 0 ? _b : UNLIMITED_CONNECTION_AGE_MS; - this.maxConnectionAgeGraceMs = (_c = this.options["grpc.max_connection_age_grace_ms"]) !== null && _c !== void 0 ? _c : UNLIMITED_CONNECTION_AGE_MS; - this.keepaliveTimeMs = (_d = this.options["grpc.keepalive_time_ms"]) !== null && _d !== void 0 ? _d : KEEPALIVE_MAX_TIME_MS; - this.keepaliveTimeoutMs = (_e = this.options["grpc.keepalive_timeout_ms"]) !== null && _e !== void 0 ? _e : KEEPALIVE_TIMEOUT_MS; - this.sessionIdleTimeout = (_f = this.options["grpc.max_connection_idle_ms"]) !== null && _f !== void 0 ? _f : MAX_CONNECTION_IDLE_MS; - this.commonServerOptions = { - maxSendHeaderBlockLength: Number.MAX_SAFE_INTEGER - }; - if ("grpc-node.max_session_memory" in this.options) { - this.commonServerOptions.maxSessionMemory = this.options["grpc-node.max_session_memory"]; - } else { - this.commonServerOptions.maxSessionMemory = Number.MAX_SAFE_INTEGER; - } - if ("grpc.max_concurrent_streams" in this.options) { - this.commonServerOptions.settings = { - maxConcurrentStreams: this.options["grpc.max_concurrent_streams"] - }; - } - this.interceptors = (_g = this.options.interceptors) !== null && _g !== void 0 ? _g : []; - this.trace("Server constructed"); - } - getChannelzInfo() { - return { - trace: this.channelzTrace, - callTracker: this.callTracker, - listenerChildren: this.listenerChildrenTracker.getChildLists(), - sessionChildren: this.sessionChildrenTracker.getChildLists() - }; - } - getChannelzSessionInfo(session) { - var _b, _c, _d; - const sessionInfo = this.sessions.get(session); - const sessionSocket = session.socket; - const remoteAddress = sessionSocket.remoteAddress ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.remoteAddress, sessionSocket.remotePort) : null; - const localAddress = sessionSocket.localAddress ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.localAddress, sessionSocket.localPort) : null; - let tlsInfo; - if (session.encrypted) { - const tlsSocket = sessionSocket; - const cipherInfo = tlsSocket.getCipher(); - const certificate = tlsSocket.getCertificate(); - const peerCertificate = tlsSocket.getPeerCertificate(); - tlsInfo = { - cipherSuiteStandardName: (_b = cipherInfo.standardName) !== null && _b !== void 0 ? _b : null, - cipherSuiteOtherName: cipherInfo.standardName ? null : cipherInfo.name, - localCertificate: certificate && "raw" in certificate ? certificate.raw : null, - remoteCertificate: peerCertificate && "raw" in peerCertificate ? peerCertificate.raw : null - }; - } else { - tlsInfo = null; - } - const socketInfo = { - remoteAddress, - localAddress, - security: tlsInfo, - remoteName: null, - streamsStarted: sessionInfo.streamTracker.callsStarted, - streamsSucceeded: sessionInfo.streamTracker.callsSucceeded, - streamsFailed: sessionInfo.streamTracker.callsFailed, - messagesSent: sessionInfo.messagesSent, - messagesReceived: sessionInfo.messagesReceived, - keepAlivesSent: sessionInfo.keepAlivesSent, - lastLocalStreamCreatedTimestamp: null, - lastRemoteStreamCreatedTimestamp: sessionInfo.streamTracker.lastCallStartedTimestamp, - lastMessageSentTimestamp: sessionInfo.lastMessageSentTimestamp, - lastMessageReceivedTimestamp: sessionInfo.lastMessageReceivedTimestamp, - localFlowControlWindow: (_c = session.state.localWindowSize) !== null && _c !== void 0 ? _c : null, - remoteFlowControlWindow: (_d = session.state.remoteWindowSize) !== null && _d !== void 0 ? _d : null - }; - return socketInfo; - } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "(" + this.channelzRef.id + ") " + text); - } - keepaliveTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, "keepalive", "(" + this.channelzRef.id + ") " + text); - } - addProtoService() { - throw new Error("Not implemented. Use addService() instead"); - } - addService(service, implementation) { - if (service === null || typeof service !== "object" || implementation === null || typeof implementation !== "object") { - throw new Error("addService() requires two objects as arguments"); - } - const serviceKeys = Object.keys(service); - if (serviceKeys.length === 0) { - throw new Error("Cannot add an empty service to a server"); - } - serviceKeys.forEach((name) => { - const attrs = service[name]; - let methodType; - if (attrs.requestStream) { - if (attrs.responseStream) { - methodType = "bidi"; - } else { - methodType = "clientStream"; - } - } else { - if (attrs.responseStream) { - methodType = "serverStream"; - } else { - methodType = "unary"; - } - } - let implFn = implementation[name]; - let impl; - if (implFn === void 0 && typeof attrs.originalName === "string") { - implFn = implementation[attrs.originalName]; - } - if (implFn !== void 0) { - impl = implFn.bind(implementation); - } else { - impl = getDefaultHandler(methodType, name); - } - const success = this.register(attrs.path, impl, attrs.responseSerialize, attrs.requestDeserialize, methodType); - if (success === false) { - throw new Error(`Method handler for ${attrs.path} already provided.`); - } - }); - } - removeService(service) { - if (service === null || typeof service !== "object") { - throw new Error("removeService() requires object as argument"); - } - const serviceKeys = Object.keys(service); - serviceKeys.forEach((name) => { - const attrs = service[name]; - this.unregister(attrs.path); - }); - } - bind(port, creds) { - throw new Error("Not implemented. Use bindAsync() instead"); - } - /** - * This API is experimental, so API stability is not guaranteed across minor versions. - * @param boundAddress - * @returns - */ - experimentalRegisterListenerToChannelz(boundAddress) { - return (0, channelz_1.registerChannelzSocket)((0, subchannel_address_1.subchannelAddressToString)(boundAddress), () => { - return { - localAddress: boundAddress, - remoteAddress: null, - security: null, - remoteName: null, - streamsStarted: 0, - streamsSucceeded: 0, - streamsFailed: 0, - messagesSent: 0, - messagesReceived: 0, - keepAlivesSent: 0, - lastLocalStreamCreatedTimestamp: null, - lastRemoteStreamCreatedTimestamp: null, - lastMessageSentTimestamp: null, - lastMessageReceivedTimestamp: null, - localFlowControlWindow: null, - remoteFlowControlWindow: null - }; - }, this.channelzEnabled); - } - experimentalUnregisterListenerFromChannelz(channelzRef) { - (0, channelz_1.unregisterChannelzRef)(channelzRef); - } - createHttp2Server(credentials) { - let http2Server; - if (credentials._isSecure()) { - const constructorOptions = credentials._getConstructorOptions(); - const contextOptions = credentials._getSecureContextOptions(); - const secureServerOptions = Object.assign(Object.assign(Object.assign(Object.assign({}, this.commonServerOptions), constructorOptions), contextOptions), { enableTrace: this.options["grpc-node.tls_enable_trace"] === 1 }); - let areCredentialsValid = contextOptions !== null; - this.trace("Initial credentials valid: " + areCredentialsValid); - http2Server = http2.createSecureServer(secureServerOptions); - http2Server.prependListener("connection", (socket) => { - if (!areCredentialsValid) { - this.trace("Dropped connection from " + JSON.stringify(socket.address()) + " due to unloaded credentials"); - socket.destroy(); - } - }); - http2Server.on("secureConnection", (socket) => { - socket.on("error", (e) => { - this.trace("An incoming TLS connection closed with error: " + e.message); - }); - }); - const credsWatcher = (options) => { - if (options) { - const secureServer = http2Server; - try { - secureServer.setSecureContext(options); - } catch (e) { - logging.log(constants_1.LogVerbosity.ERROR, "Failed to set secure context with error " + e.message); - options = null; - } - } - areCredentialsValid = options !== null; - this.trace("Post-update credentials valid: " + areCredentialsValid); - }; - credentials._addWatcher(credsWatcher); - http2Server.on("close", () => { - credentials._removeWatcher(credsWatcher); - }); - } else { - http2Server = http2.createServer(this.commonServerOptions); - } - http2Server.setTimeout(0, noop3); - this._setupHandlers(http2Server, credentials._getInterceptors()); - return http2Server; - } - bindOneAddress(address, boundPortObject) { - this.trace("Attempting to bind " + (0, subchannel_address_1.subchannelAddressToString)(address)); - const http2Server = this.createHttp2Server(boundPortObject.credentials); - return new Promise((resolve, reject) => { - const onError = (err) => { - this.trace("Failed to bind " + (0, subchannel_address_1.subchannelAddressToString)(address) + " with error " + err.message); - resolve({ - port: "port" in address ? address.port : 1, - error: err.message - }); - }; - http2Server.once("error", onError); - http2Server.listen(address, () => { - const boundAddress = http2Server.address(); - let boundSubchannelAddress; - if (typeof boundAddress === "string") { - boundSubchannelAddress = { - path: boundAddress - }; - } else { - boundSubchannelAddress = { - host: boundAddress.address, - port: boundAddress.port - }; - } - const channelzRef = this.experimentalRegisterListenerToChannelz(boundSubchannelAddress); - this.listenerChildrenTracker.refChild(channelzRef); - this.http2Servers.set(http2Server, { - channelzRef, - sessions: /* @__PURE__ */ new Set(), - ownsChannelzRef: true - }); - boundPortObject.listeningServers.add(http2Server); - this.trace("Successfully bound " + (0, subchannel_address_1.subchannelAddressToString)(boundSubchannelAddress)); - resolve({ - port: "port" in boundSubchannelAddress ? boundSubchannelAddress.port : 1 - }); - http2Server.removeListener("error", onError); - }); - }); - } - async bindManyPorts(addressList, boundPortObject) { - if (addressList.length === 0) { - return { - count: 0, - port: 0, - errors: [] - }; - } - if ((0, subchannel_address_1.isTcpSubchannelAddress)(addressList[0]) && addressList[0].port === 0) { - const firstAddressResult = await this.bindOneAddress(addressList[0], boundPortObject); - if (firstAddressResult.error) { - const restAddressResult = await this.bindManyPorts(addressList.slice(1), boundPortObject); - return Object.assign(Object.assign({}, restAddressResult), { errors: [firstAddressResult.error, ...restAddressResult.errors] }); - } else { - const restAddresses = addressList.slice(1).map((address) => (0, subchannel_address_1.isTcpSubchannelAddress)(address) ? { host: address.host, port: firstAddressResult.port } : address); - const restAddressResult = await Promise.all(restAddresses.map((address) => this.bindOneAddress(address, boundPortObject))); - const allResults = [firstAddressResult, ...restAddressResult]; - return { - count: allResults.filter((result) => result.error === void 0).length, - port: firstAddressResult.port, - errors: allResults.filter((result) => result.error).map((result) => result.error) - }; - } - } else { - const allResults = await Promise.all(addressList.map((address) => this.bindOneAddress(address, boundPortObject))); - return { - count: allResults.filter((result) => result.error === void 0).length, - port: allResults[0].port, - errors: allResults.filter((result) => result.error).map((result) => result.error) - }; - } - } - async bindAddressList(addressList, boundPortObject) { - const bindResult = await this.bindManyPorts(addressList, boundPortObject); - if (bindResult.count > 0) { - if (bindResult.count < addressList.length) { - logging.log(constants_1.LogVerbosity.INFO, `WARNING Only ${bindResult.count} addresses added out of total ${addressList.length} resolved`); - } - return bindResult.port; - } else { - const errorString = `No address added out of total ${addressList.length} resolved`; - logging.log(constants_1.LogVerbosity.ERROR, errorString); - throw new Error(`${errorString} errors: [${bindResult.errors.join(",")}]`); - } - } - resolvePort(port) { - return new Promise((resolve, reject) => { - let seenResolution = false; - const resolverListener = (endpointList, attributes, serviceConfig, resolutionNote) => { - if (seenResolution) { - return true; - } - seenResolution = true; - if (!endpointList.ok) { - reject(new Error(endpointList.error.details)); - return true; - } - const addressList = [].concat(...endpointList.value.map((endpoint2) => endpoint2.addresses)); - if (addressList.length === 0) { - reject(new Error(`No addresses resolved for port ${port}`)); - return true; - } - resolve(addressList); - return true; - }; - const resolver = (0, resolver_1.createResolver)(port, resolverListener, this.options); - resolver.updateResolution(); - }); - } - async bindPort(port, boundPortObject) { - const addressList = await this.resolvePort(port); - if (boundPortObject.cancelled) { - this.completeUnbind(boundPortObject); - throw new Error("bindAsync operation cancelled by unbind call"); - } - const portNumber = await this.bindAddressList(addressList, boundPortObject); - if (boundPortObject.cancelled) { - this.completeUnbind(boundPortObject); - throw new Error("bindAsync operation cancelled by unbind call"); - } - return portNumber; - } - normalizePort(port) { - const initialPortUri = (0, uri_parser_1.parseUri)(port); - if (initialPortUri === null) { - throw new Error(`Could not parse port "${port}"`); - } - const portUri = (0, resolver_1.mapUriDefaultScheme)(initialPortUri); - if (portUri === null) { - throw new Error(`Could not get a default scheme for port "${port}"`); - } - return portUri; - } - bindAsync(port, creds, callback) { - if (this.shutdown) { - throw new Error("bindAsync called after shutdown"); - } - if (typeof port !== "string") { - throw new TypeError("port must be a string"); - } - if (creds === null || !(creds instanceof server_credentials_1.ServerCredentials)) { - throw new TypeError("creds must be a ServerCredentials object"); - } - if (typeof callback !== "function") { - throw new TypeError("callback must be a function"); - } - this.trace("bindAsync port=" + port); - const portUri = this.normalizePort(port); - const deferredCallback = (error3, port2) => { - process.nextTick(() => callback(error3, port2)); - }; - let boundPortObject = this.boundPorts.get((0, uri_parser_1.uriToString)(portUri)); - if (boundPortObject) { - if (!creds._equals(boundPortObject.credentials)) { - deferredCallback(new Error(`${port} already bound with incompatible credentials`), 0); - return; - } - boundPortObject.cancelled = false; - if (boundPortObject.completionPromise) { - boundPortObject.completionPromise.then((portNum) => callback(null, portNum), (error3) => callback(error3, 0)); - } else { - deferredCallback(null, boundPortObject.portNumber); - } - return; - } - boundPortObject = { - mapKey: (0, uri_parser_1.uriToString)(portUri), - originalUri: portUri, - completionPromise: null, - cancelled: false, - portNumber: 0, - credentials: creds, - listeningServers: /* @__PURE__ */ new Set() - }; - const splitPort = (0, uri_parser_1.splitHostPort)(portUri.path); - const completionPromise = this.bindPort(portUri, boundPortObject); - boundPortObject.completionPromise = completionPromise; - if ((splitPort === null || splitPort === void 0 ? void 0 : splitPort.port) === 0) { - completionPromise.then((portNum) => { - const finalUri = { - scheme: portUri.scheme, - authority: portUri.authority, - path: (0, uri_parser_1.combineHostPort)({ host: splitPort.host, port: portNum }) - }; - boundPortObject.mapKey = (0, uri_parser_1.uriToString)(finalUri); - boundPortObject.completionPromise = null; - boundPortObject.portNumber = portNum; - this.boundPorts.set(boundPortObject.mapKey, boundPortObject); - callback(null, portNum); - }, (error3) => { - callback(error3, 0); - }); - } else { - this.boundPorts.set(boundPortObject.mapKey, boundPortObject); - completionPromise.then((portNum) => { - boundPortObject.completionPromise = null; - boundPortObject.portNumber = portNum; - callback(null, portNum); - }, (error3) => { - callback(error3, 0); - }); - } - } - registerInjectorToChannelz() { - return (0, channelz_1.registerChannelzSocket)("injector", () => { - return { - localAddress: null, - remoteAddress: null, - security: null, - remoteName: null, - streamsStarted: 0, - streamsSucceeded: 0, - streamsFailed: 0, - messagesSent: 0, - messagesReceived: 0, - keepAlivesSent: 0, - lastLocalStreamCreatedTimestamp: null, - lastRemoteStreamCreatedTimestamp: null, - lastMessageSentTimestamp: null, - lastMessageReceivedTimestamp: null, - localFlowControlWindow: null, - remoteFlowControlWindow: null - }; - }, this.channelzEnabled); - } - /** - * This API is experimental, so API stability is not guaranteed across minor versions. - * @param credentials - * @param channelzRef - * @returns - */ - experimentalCreateConnectionInjectorWithChannelzRef(credentials, channelzRef, ownsChannelzRef = false) { - if (credentials === null || !(credentials instanceof server_credentials_1.ServerCredentials)) { - throw new TypeError("creds must be a ServerCredentials object"); - } - if (this.channelzEnabled) { - this.listenerChildrenTracker.refChild(channelzRef); - } - const server = this.createHttp2Server(credentials); - const sessionsSet = /* @__PURE__ */ new Set(); - this.http2Servers.set(server, { - channelzRef, - sessions: sessionsSet, - ownsChannelzRef - }); - return { - injectConnection: (connection) => { - server.emit("connection", connection); - }, - drain: (graceTimeMs) => { - var _b, _c; - for (const session of sessionsSet) { - this.closeSession(session); - } - (_c = (_b = setTimeout(() => { - for (const session of sessionsSet) { - session.destroy(http2.constants.NGHTTP2_CANCEL); - } - }, graceTimeMs)).unref) === null || _c === void 0 ? void 0 : _c.call(_b); - }, - destroy: () => { - this.closeServer(server); - for (const session of sessionsSet) { - this.closeSession(session); - } - } - }; - } - createConnectionInjector(credentials) { - if (credentials === null || !(credentials instanceof server_credentials_1.ServerCredentials)) { - throw new TypeError("creds must be a ServerCredentials object"); - } - const channelzRef = this.registerInjectorToChannelz(); - return this.experimentalCreateConnectionInjectorWithChannelzRef(credentials, channelzRef, true); - } - closeServer(server, callback) { - this.trace("Closing server with address " + JSON.stringify(server.address())); - const serverInfo = this.http2Servers.get(server); - server.close(() => { - if (serverInfo && serverInfo.ownsChannelzRef) { - this.listenerChildrenTracker.unrefChild(serverInfo.channelzRef); - (0, channelz_1.unregisterChannelzRef)(serverInfo.channelzRef); - } - this.http2Servers.delete(server); - callback === null || callback === void 0 ? void 0 : callback(); - }); - } - closeSession(session, callback) { - var _b; - this.trace("Closing session initiated by " + ((_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress)); - const sessionInfo = this.sessions.get(session); - const closeCallback = () => { - if (sessionInfo) { - this.sessionChildrenTracker.unrefChild(sessionInfo.ref); - (0, channelz_1.unregisterChannelzRef)(sessionInfo.ref); - } - callback === null || callback === void 0 ? void 0 : callback(); - }; - if (session.closed) { - queueMicrotask(closeCallback); - } else { - session.close(closeCallback); - } - } - completeUnbind(boundPortObject) { - for (const server of boundPortObject.listeningServers) { - const serverInfo = this.http2Servers.get(server); - this.closeServer(server, () => { - boundPortObject.listeningServers.delete(server); - }); - if (serverInfo) { - for (const session of serverInfo.sessions) { - this.closeSession(session); - } - } - } - this.boundPorts.delete(boundPortObject.mapKey); - } - /** - * Unbind a previously bound port, or cancel an in-progress bindAsync - * operation. If port 0 was bound, only the actual bound port can be - * unbound. For example, if bindAsync was called with "localhost:0" and the - * bound port result was 54321, it can be unbound as "localhost:54321". - * @param port - */ - unbind(port) { - this.trace("unbind port=" + port); - const portUri = this.normalizePort(port); - const splitPort = (0, uri_parser_1.splitHostPort)(portUri.path); - if ((splitPort === null || splitPort === void 0 ? void 0 : splitPort.port) === 0) { - throw new Error("Cannot unbind port 0"); - } - const boundPortObject = this.boundPorts.get((0, uri_parser_1.uriToString)(portUri)); - if (boundPortObject) { - this.trace("unbinding " + boundPortObject.mapKey + " originally bound as " + (0, uri_parser_1.uriToString)(boundPortObject.originalUri)); - if (boundPortObject.completionPromise) { - boundPortObject.cancelled = true; - } else { - this.completeUnbind(boundPortObject); - } - } - } - /** - * Gracefully close all connections associated with a previously bound port. - * After the grace time, forcefully close all remaining open connections. - * - * If port 0 was bound, only the actual bound port can be - * drained. For example, if bindAsync was called with "localhost:0" and the - * bound port result was 54321, it can be drained as "localhost:54321". - * @param port - * @param graceTimeMs - * @returns - */ - drain(port, graceTimeMs) { - var _b, _c; - this.trace("drain port=" + port + " graceTimeMs=" + graceTimeMs); - const portUri = this.normalizePort(port); - const splitPort = (0, uri_parser_1.splitHostPort)(portUri.path); - if ((splitPort === null || splitPort === void 0 ? void 0 : splitPort.port) === 0) { - throw new Error("Cannot drain port 0"); - } - const boundPortObject = this.boundPorts.get((0, uri_parser_1.uriToString)(portUri)); - if (!boundPortObject) { - return; - } - const allSessions = /* @__PURE__ */ new Set(); - for (const http2Server of boundPortObject.listeningServers) { - const serverEntry = this.http2Servers.get(http2Server); - if (serverEntry) { - for (const session of serverEntry.sessions) { - allSessions.add(session); - this.closeSession(session, () => { - allSessions.delete(session); - }); - } - } - } - (_c = (_b = setTimeout(() => { - for (const session of allSessions) { - session.destroy(http2.constants.NGHTTP2_CANCEL); - } - }, graceTimeMs)).unref) === null || _c === void 0 ? void 0 : _c.call(_b); - } - forceShutdown() { - for (const boundPortObject of this.boundPorts.values()) { - boundPortObject.cancelled = true; - } - this.boundPorts.clear(); - for (const server of this.http2Servers.keys()) { - this.closeServer(server); - } - this.sessions.forEach((channelzInfo, session) => { - this.closeSession(session); - session.destroy(http2.constants.NGHTTP2_CANCEL); - }); - this.sessions.clear(); - (0, channelz_1.unregisterChannelzRef)(this.channelzRef); - this.shutdown = true; - } - register(name, handler2, serialize, deserialize, type) { - if (this.handlers.has(name)) { - return false; - } - this.handlers.set(name, { - func: handler2, - serialize, - deserialize, - type, - path: name - }); - return true; - } - unregister(name) { - return this.handlers.delete(name); - } - /** - * @deprecated No longer needed as of version 1.10.x - */ - start() { - if (this.http2Servers.size === 0 || [...this.http2Servers.keys()].every((server) => !server.listening)) { - throw new Error("server must be bound in order to start"); - } - if (this.started === true) { - throw new Error("server is already started"); - } - this.started = true; - } - tryShutdown(callback) { - var _b; - const wrappedCallback = (error3) => { - (0, channelz_1.unregisterChannelzRef)(this.channelzRef); - callback(error3); - }; - let pendingChecks = 0; - function maybeCallback() { - pendingChecks--; - if (pendingChecks === 0) { - wrappedCallback(); - } - } - this.shutdown = true; - for (const [serverKey, server] of this.http2Servers.entries()) { - pendingChecks++; - const serverString = server.channelzRef.name; - this.trace("Waiting for server " + serverString + " to close"); - this.closeServer(serverKey, () => { - this.trace("Server " + serverString + " finished closing"); - maybeCallback(); - }); - for (const session of server.sessions.keys()) { - pendingChecks++; - const sessionString = (_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress; - this.trace("Waiting for session " + sessionString + " to close"); - this.closeSession(session, () => { - this.trace("Session " + sessionString + " finished closing"); - maybeCallback(); - }); - } - } - if (pendingChecks === 0) { - wrappedCallback(); - } - } - addHttp2Port() { - throw new Error("Not yet implemented"); - } - /** - * Get the channelz reference object for this server. The returned value is - * garbage if channelz is disabled for this server. - * @returns - */ - getChannelzRef() { - return this.channelzRef; - } - _verifyContentType(stream2, headers) { - const contentType = headers[http2.constants.HTTP2_HEADER_CONTENT_TYPE]; - if (typeof contentType !== "string" || !contentType.startsWith("application/grpc")) { - stream2.respond({ - [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE - }, { endStream: true }); - return false; - } - return true; - } - _retrieveHandler(path) { - serverCallTrace("Received call to method " + path + " at address " + this.serverAddressString); - const handler2 = this.handlers.get(path); - if (handler2 === void 0) { - serverCallTrace("No handler registered for method " + path + ". Sending UNIMPLEMENTED status."); - return null; - } - return handler2; - } - _respondWithError(err, stream2, channelzSessionInfo = null) { - var _b, _c; - const trailersToSend = Object.assign({ "grpc-status": (_b = err.code) !== null && _b !== void 0 ? _b : constants_1.Status.INTERNAL, "grpc-message": err.details, [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_OK, [http2.constants.HTTP2_HEADER_CONTENT_TYPE]: "application/grpc+proto" }, (_c = err.metadata) === null || _c === void 0 ? void 0 : _c.toHttp2Headers()); - stream2.respond(trailersToSend, { endStream: true }); - this.callTracker.addCallFailed(); - channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed(); - } - _channelzHandler(extraInterceptors, stream2, headers) { - stream2.once("error", (err) => { - }); - this.onStreamOpened(stream2); - const channelzSessionInfo = this.sessions.get(stream2.session); - this.callTracker.addCallStarted(); - channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallStarted(); - if (!this._verifyContentType(stream2, headers)) { - this.callTracker.addCallFailed(); - channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed(); - return; - } - const path = headers[HTTP2_HEADER_PATH]; - const handler2 = this._retrieveHandler(path); - if (!handler2) { - this._respondWithError(getUnimplementedStatusResponse(path), stream2, channelzSessionInfo); - return; - } - const callEventTracker = { - addMessageSent: () => { - if (channelzSessionInfo) { - channelzSessionInfo.messagesSent += 1; - channelzSessionInfo.lastMessageSentTimestamp = /* @__PURE__ */ new Date(); - } - }, - addMessageReceived: () => { - if (channelzSessionInfo) { - channelzSessionInfo.messagesReceived += 1; - channelzSessionInfo.lastMessageReceivedTimestamp = /* @__PURE__ */ new Date(); - } - }, - onCallEnd: (status) => { - if (status.code === constants_1.Status.OK) { - this.callTracker.addCallSucceeded(); - } else { - this.callTracker.addCallFailed(); - } - }, - onStreamEnd: (success) => { - if (channelzSessionInfo) { - if (success) { - channelzSessionInfo.streamTracker.addCallSucceeded(); - } else { - channelzSessionInfo.streamTracker.addCallFailed(); - } - } - } - }; - const call = (0, server_interceptors_1.getServerInterceptingCall)([...extraInterceptors, ...this.interceptors], stream2, headers, callEventTracker, handler2, this.options); - if (!this._runHandlerForCall(call, handler2)) { - this.callTracker.addCallFailed(); - channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed(); - call.sendStatus({ - code: constants_1.Status.INTERNAL, - details: `Unknown handler type: ${handler2.type}` - }); - } - } - _streamHandler(extraInterceptors, stream2, headers) { - stream2.once("error", (err) => { - }); - this.onStreamOpened(stream2); - if (this._verifyContentType(stream2, headers) !== true) { - return; - } - const path = headers[HTTP2_HEADER_PATH]; - const handler2 = this._retrieveHandler(path); - if (!handler2) { - this._respondWithError(getUnimplementedStatusResponse(path), stream2, null); - return; - } - const call = (0, server_interceptors_1.getServerInterceptingCall)([...extraInterceptors, ...this.interceptors], stream2, headers, null, handler2, this.options); - if (!this._runHandlerForCall(call, handler2)) { - call.sendStatus({ - code: constants_1.Status.INTERNAL, - details: `Unknown handler type: ${handler2.type}` - }); - } - } - _runHandlerForCall(call, handler2) { - const { type } = handler2; - if (type === "unary") { - handleUnary(call, handler2); - } else if (type === "clientStream") { - handleClientStreaming(call, handler2); - } else if (type === "serverStream") { - handleServerStreaming(call, handler2); - } else if (type === "bidi") { - handleBidiStreaming(call, handler2); - } else { - return false; - } - return true; - } - _setupHandlers(http2Server, extraInterceptors) { - if (http2Server === null) { - return; - } - const serverAddress = http2Server.address(); - let serverAddressString = "null"; - if (serverAddress) { - if (typeof serverAddress === "string") { - serverAddressString = serverAddress; - } else { - serverAddressString = serverAddress.address + ":" + serverAddress.port; - } - } - this.serverAddressString = serverAddressString; - const handler2 = this.channelzEnabled ? this._channelzHandler : this._streamHandler; - const sessionHandler = this.channelzEnabled ? this._channelzSessionHandler(http2Server) : this._sessionHandler(http2Server); - http2Server.on("stream", handler2.bind(this, extraInterceptors)); - http2Server.on("session", sessionHandler); - } - _sessionHandler(http2Server) { - return (session) => { - var _b, _c; - (_b = this.http2Servers.get(http2Server)) === null || _b === void 0 ? void 0 : _b.sessions.add(session); - let connectionAgeTimer = null; - let connectionAgeGraceTimer = null; - let keepaliveTimer = null; - let sessionClosedByServer = false; - const idleTimeoutObj = this.enableIdleTimeout(session); - if (this.maxConnectionAgeMs !== UNLIMITED_CONNECTION_AGE_MS) { - const jitterMagnitude = this.maxConnectionAgeMs / 10; - const jitter = Math.random() * jitterMagnitude * 2 - jitterMagnitude; - connectionAgeTimer = setTimeout(() => { - var _b2, _c2; - sessionClosedByServer = true; - this.trace("Connection dropped by max connection age: " + ((_b2 = session.socket) === null || _b2 === void 0 ? void 0 : _b2.remoteAddress)); - try { - session.goaway(http2.constants.NGHTTP2_NO_ERROR, ~(1 << 31), kMaxAge); - } catch (e) { - session.destroy(); - return; - } - session.close(); - if (this.maxConnectionAgeGraceMs !== UNLIMITED_CONNECTION_AGE_MS) { - connectionAgeGraceTimer = setTimeout(() => { - session.destroy(); - }, this.maxConnectionAgeGraceMs); - (_c2 = connectionAgeGraceTimer.unref) === null || _c2 === void 0 ? void 0 : _c2.call(connectionAgeGraceTimer); - } - }, this.maxConnectionAgeMs + jitter); - (_c = connectionAgeTimer.unref) === null || _c === void 0 ? void 0 : _c.call(connectionAgeTimer); - } - const clearKeepaliveTimeout = () => { - if (keepaliveTimer) { - clearTimeout(keepaliveTimer); - keepaliveTimer = null; - } - }; - const canSendPing = () => { - return !session.destroyed && this.keepaliveTimeMs < KEEPALIVE_MAX_TIME_MS && this.keepaliveTimeMs > 0; - }; - let sendPing; - const maybeStartKeepalivePingTimer = () => { - var _b2; - if (!canSendPing()) { - return; - } - this.keepaliveTrace("Starting keepalive timer for " + this.keepaliveTimeMs + "ms"); - keepaliveTimer = setTimeout(() => { - clearKeepaliveTimeout(); - sendPing(); - }, this.keepaliveTimeMs); - (_b2 = keepaliveTimer.unref) === null || _b2 === void 0 ? void 0 : _b2.call(keepaliveTimer); - }; - sendPing = () => { - var _b2; - if (!canSendPing()) { - return; - } - this.keepaliveTrace("Sending ping with timeout " + this.keepaliveTimeoutMs + "ms"); - let pingSendError = ""; - try { - const pingSentSuccessfully = session.ping((err, duration, payload) => { - clearKeepaliveTimeout(); - if (err) { - this.keepaliveTrace("Ping failed with error: " + err.message); - sessionClosedByServer = true; - session.destroy(); - } else { - this.keepaliveTrace("Received ping response"); - maybeStartKeepalivePingTimer(); - } - }); - if (!pingSentSuccessfully) { - pingSendError = "Ping returned false"; - } - } catch (e) { - pingSendError = (e instanceof Error ? e.message : "") || "Unknown error"; - } - if (pingSendError) { - this.keepaliveTrace("Ping send failed: " + pingSendError); - this.trace("Connection dropped due to ping send error: " + pingSendError); - sessionClosedByServer = true; - session.destroy(); - return; - } - keepaliveTimer = setTimeout(() => { - clearKeepaliveTimeout(); - this.keepaliveTrace("Ping timeout passed without response"); - this.trace("Connection dropped by keepalive timeout"); - sessionClosedByServer = true; - session.destroy(); - }, this.keepaliveTimeoutMs); - (_b2 = keepaliveTimer.unref) === null || _b2 === void 0 ? void 0 : _b2.call(keepaliveTimer); - }; - maybeStartKeepalivePingTimer(); - session.on("close", () => { - var _b2, _c2; - if (!sessionClosedByServer) { - this.trace(`Connection dropped by client ${(_b2 = session.socket) === null || _b2 === void 0 ? void 0 : _b2.remoteAddress}`); - } - if (connectionAgeTimer) { - clearTimeout(connectionAgeTimer); - } - if (connectionAgeGraceTimer) { - clearTimeout(connectionAgeGraceTimer); - } - clearKeepaliveTimeout(); - if (idleTimeoutObj !== null) { - clearTimeout(idleTimeoutObj.timeout); - this.sessionIdleTimeouts.delete(session); - } - (_c2 = this.http2Servers.get(http2Server)) === null || _c2 === void 0 ? void 0 : _c2.sessions.delete(session); - }); - }; - } - _channelzSessionHandler(http2Server) { - return (session) => { - var _b, _c, _d, _e; - const channelzRef = (0, channelz_1.registerChannelzSocket)((_c = (_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress) !== null && _c !== void 0 ? _c : "unknown", this.getChannelzSessionInfo.bind(this, session), this.channelzEnabled); - const channelzSessionInfo = { - ref: channelzRef, - streamTracker: new channelz_1.ChannelzCallTracker(), - messagesSent: 0, - messagesReceived: 0, - keepAlivesSent: 0, - lastMessageSentTimestamp: null, - lastMessageReceivedTimestamp: null - }; - (_d = this.http2Servers.get(http2Server)) === null || _d === void 0 ? void 0 : _d.sessions.add(session); - this.sessions.set(session, channelzSessionInfo); - const clientAddress = `${session.socket.remoteAddress}:${session.socket.remotePort}`; - this.channelzTrace.addTrace("CT_INFO", "Connection established by client " + clientAddress); - this.trace("Connection established by client " + clientAddress); - this.sessionChildrenTracker.refChild(channelzRef); - let connectionAgeTimer = null; - let connectionAgeGraceTimer = null; - let keepaliveTimeout = null; - let sessionClosedByServer = false; - const idleTimeoutObj = this.enableIdleTimeout(session); - if (this.maxConnectionAgeMs !== UNLIMITED_CONNECTION_AGE_MS) { - const jitterMagnitude = this.maxConnectionAgeMs / 10; - const jitter = Math.random() * jitterMagnitude * 2 - jitterMagnitude; - connectionAgeTimer = setTimeout(() => { - var _b2; - sessionClosedByServer = true; - this.channelzTrace.addTrace("CT_INFO", "Connection dropped by max connection age from " + clientAddress); - try { - session.goaway(http2.constants.NGHTTP2_NO_ERROR, ~(1 << 31), kMaxAge); - } catch (e) { - session.destroy(); - return; - } - session.close(); - if (this.maxConnectionAgeGraceMs !== UNLIMITED_CONNECTION_AGE_MS) { - connectionAgeGraceTimer = setTimeout(() => { - session.destroy(); - }, this.maxConnectionAgeGraceMs); - (_b2 = connectionAgeGraceTimer.unref) === null || _b2 === void 0 ? void 0 : _b2.call(connectionAgeGraceTimer); - } - }, this.maxConnectionAgeMs + jitter); - (_e = connectionAgeTimer.unref) === null || _e === void 0 ? void 0 : _e.call(connectionAgeTimer); - } - const clearKeepaliveTimeout = () => { - if (keepaliveTimeout) { - clearTimeout(keepaliveTimeout); - keepaliveTimeout = null; - } - }; - const canSendPing = () => { - return !session.destroyed && this.keepaliveTimeMs < KEEPALIVE_MAX_TIME_MS && this.keepaliveTimeMs > 0; - }; - let sendPing; - const maybeStartKeepalivePingTimer = () => { - var _b2; - if (!canSendPing()) { - return; - } - this.keepaliveTrace("Starting keepalive timer for " + this.keepaliveTimeMs + "ms"); - keepaliveTimeout = setTimeout(() => { - clearKeepaliveTimeout(); - sendPing(); - }, this.keepaliveTimeMs); - (_b2 = keepaliveTimeout.unref) === null || _b2 === void 0 ? void 0 : _b2.call(keepaliveTimeout); - }; - sendPing = () => { - var _b2; - if (!canSendPing()) { - return; - } - this.keepaliveTrace("Sending ping with timeout " + this.keepaliveTimeoutMs + "ms"); - let pingSendError = ""; - try { - const pingSentSuccessfully = session.ping((err, duration, payload) => { - clearKeepaliveTimeout(); - if (err) { - this.keepaliveTrace("Ping failed with error: " + err.message); - this.channelzTrace.addTrace("CT_INFO", "Connection dropped due to error of a ping frame " + err.message + " return in " + duration); - sessionClosedByServer = true; - session.destroy(); - } else { - this.keepaliveTrace("Received ping response"); - maybeStartKeepalivePingTimer(); - } - }); - if (!pingSentSuccessfully) { - pingSendError = "Ping returned false"; - } - } catch (e) { - pingSendError = (e instanceof Error ? e.message : "") || "Unknown error"; - } - if (pingSendError) { - this.keepaliveTrace("Ping send failed: " + pingSendError); - this.channelzTrace.addTrace("CT_INFO", "Connection dropped due to ping send error: " + pingSendError); - sessionClosedByServer = true; - session.destroy(); - return; - } - channelzSessionInfo.keepAlivesSent += 1; - keepaliveTimeout = setTimeout(() => { - clearKeepaliveTimeout(); - this.keepaliveTrace("Ping timeout passed without response"); - this.channelzTrace.addTrace("CT_INFO", "Connection dropped by keepalive timeout from " + clientAddress); - sessionClosedByServer = true; - session.destroy(); - }, this.keepaliveTimeoutMs); - (_b2 = keepaliveTimeout.unref) === null || _b2 === void 0 ? void 0 : _b2.call(keepaliveTimeout); - }; - maybeStartKeepalivePingTimer(); - session.on("close", () => { - var _b2; - if (!sessionClosedByServer) { - this.channelzTrace.addTrace("CT_INFO", "Connection dropped by client " + clientAddress); - } - this.sessionChildrenTracker.unrefChild(channelzRef); - (0, channelz_1.unregisterChannelzRef)(channelzRef); - if (connectionAgeTimer) { - clearTimeout(connectionAgeTimer); - } - if (connectionAgeGraceTimer) { - clearTimeout(connectionAgeGraceTimer); - } - clearKeepaliveTimeout(); - if (idleTimeoutObj !== null) { - clearTimeout(idleTimeoutObj.timeout); - this.sessionIdleTimeouts.delete(session); - } - (_b2 = this.http2Servers.get(http2Server)) === null || _b2 === void 0 ? void 0 : _b2.sessions.delete(session); - this.sessions.delete(session); - }); - }; - } - enableIdleTimeout(session) { - var _b, _c; - if (this.sessionIdleTimeout >= MAX_CONNECTION_IDLE_MS) { - return null; - } - const idleTimeoutObj = { - activeStreams: 0, - lastIdle: Date.now(), - onClose: this.onStreamClose.bind(this, session), - timeout: setTimeout(this.onIdleTimeout, this.sessionIdleTimeout, this, session) - }; - (_c = (_b = idleTimeoutObj.timeout).unref) === null || _c === void 0 ? void 0 : _c.call(_b); - this.sessionIdleTimeouts.set(session, idleTimeoutObj); - const { socket } = session; - this.trace("Enable idle timeout for " + socket.remoteAddress + ":" + socket.remotePort); - return idleTimeoutObj; - } - onIdleTimeout(ctx, session) { - const { socket } = session; - const sessionInfo = ctx.sessionIdleTimeouts.get(session); - if (sessionInfo !== void 0 && sessionInfo.activeStreams === 0) { - if (Date.now() - sessionInfo.lastIdle >= ctx.sessionIdleTimeout) { - ctx.trace("Session idle timeout triggered for " + (socket === null || socket === void 0 ? void 0 : socket.remoteAddress) + ":" + (socket === null || socket === void 0 ? void 0 : socket.remotePort) + " last idle at " + sessionInfo.lastIdle); - ctx.closeSession(session); - } else { - sessionInfo.timeout.refresh(); - } - } - } - onStreamOpened(stream2) { - const session = stream2.session; - const idleTimeoutObj = this.sessionIdleTimeouts.get(session); - if (idleTimeoutObj) { - idleTimeoutObj.activeStreams += 1; - stream2.once("close", idleTimeoutObj.onClose); - } - } - onStreamClose(session) { - var _b, _c; - const idleTimeoutObj = this.sessionIdleTimeouts.get(session); - if (idleTimeoutObj) { - idleTimeoutObj.activeStreams -= 1; - if (idleTimeoutObj.activeStreams === 0) { - idleTimeoutObj.lastIdle = Date.now(); - idleTimeoutObj.timeout.refresh(); - this.trace("Session onStreamClose" + ((_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress) + ":" + ((_c = session.socket) === null || _c === void 0 ? void 0 : _c.remotePort) + " at " + idleTimeoutObj.lastIdle); - } - } - } - }, (() => { - const _metadata = typeof Symbol === "function" && Symbol.metadata ? /* @__PURE__ */ Object.create(null) : void 0; - _start_decorators = [deprecate("Calling start() is no longer necessary. It can be safely omitted.")]; - __esDecorate(_a, null, _start_decorators, { kind: "method", name: "start", static: false, private: false, access: { has: (obj) => "start" in obj, get: (obj) => obj.start }, metadata: _metadata }, null, _instanceExtraInitializers); - if (_metadata) Object.defineProperty(_a, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); - })(), _a; - })(); - exports2.Server = Server; - async function handleUnary(call, handler2) { - let stream2; - function respond(err, value, trailer, flags) { - if (err) { - call.sendStatus((0, server_call_1.serverErrorToStatus)(err, trailer)); - return; - } - call.sendMessage(value, () => { - call.sendStatus({ - code: constants_1.Status.OK, - details: "OK", - metadata: trailer !== null && trailer !== void 0 ? trailer : null - }); - }); - } - let requestMetadata; - let requestMessage = null; - call.start({ - onReceiveMetadata(metadata) { - requestMetadata = metadata; - call.startRead(); - }, - onReceiveMessage(message) { - if (requestMessage) { - call.sendStatus({ - code: constants_1.Status.UNIMPLEMENTED, - details: `Received a second request message for server streaming method ${handler2.path}`, - metadata: null - }); - return; - } - requestMessage = message; - call.startRead(); - }, - onReceiveHalfClose() { - if (!requestMessage) { - call.sendStatus({ - code: constants_1.Status.UNIMPLEMENTED, - details: `Received no request message for server streaming method ${handler2.path}`, - metadata: null - }); - return; - } - stream2 = new server_call_1.ServerWritableStreamImpl(handler2.path, call, requestMetadata, requestMessage); - try { - handler2.func(stream2, respond); - } catch (err) { - call.sendStatus({ - code: constants_1.Status.UNKNOWN, - details: `Server method handler threw error ${err.message}`, - metadata: null - }); - } - }, - onCancel() { - if (stream2) { - stream2.cancelled = true; - stream2.emit("cancelled", "cancelled"); - } - } - }); - } - function handleClientStreaming(call, handler2) { - let stream2; - function respond(err, value, trailer, flags) { - if (err) { - call.sendStatus((0, server_call_1.serverErrorToStatus)(err, trailer)); - return; - } - call.sendMessage(value, () => { - call.sendStatus({ - code: constants_1.Status.OK, - details: "OK", - metadata: trailer !== null && trailer !== void 0 ? trailer : null - }); - }); - } - call.start({ - onReceiveMetadata(metadata) { - stream2 = new server_call_1.ServerDuplexStreamImpl(handler2.path, call, metadata); - try { - handler2.func(stream2, respond); - } catch (err) { - call.sendStatus({ - code: constants_1.Status.UNKNOWN, - details: `Server method handler threw error ${err.message}`, - metadata: null - }); - } - }, - onReceiveMessage(message) { - stream2.push(message); - }, - onReceiveHalfClose() { - stream2.push(null); - }, - onCancel() { - if (stream2) { - stream2.cancelled = true; - stream2.emit("cancelled", "cancelled"); - stream2.destroy(); - } - } - }); - } - function handleServerStreaming(call, handler2) { - let stream2; - let requestMetadata; - let requestMessage = null; - call.start({ - onReceiveMetadata(metadata) { - requestMetadata = metadata; - call.startRead(); - }, - onReceiveMessage(message) { - if (requestMessage) { - call.sendStatus({ - code: constants_1.Status.UNIMPLEMENTED, - details: `Received a second request message for server streaming method ${handler2.path}`, - metadata: null - }); - return; - } - requestMessage = message; - call.startRead(); - }, - onReceiveHalfClose() { - if (!requestMessage) { - call.sendStatus({ - code: constants_1.Status.UNIMPLEMENTED, - details: `Received no request message for server streaming method ${handler2.path}`, - metadata: null - }); - return; - } - stream2 = new server_call_1.ServerWritableStreamImpl(handler2.path, call, requestMetadata, requestMessage); - try { - handler2.func(stream2); - } catch (err) { - call.sendStatus({ - code: constants_1.Status.UNKNOWN, - details: `Server method handler threw error ${err.message}`, - metadata: null - }); - } - }, - onCancel() { - if (stream2) { - stream2.cancelled = true; - stream2.emit("cancelled", "cancelled"); - stream2.destroy(); - } - } - }); - } - function handleBidiStreaming(call, handler2) { - let stream2; - call.start({ - onReceiveMetadata(metadata) { - stream2 = new server_call_1.ServerDuplexStreamImpl(handler2.path, call, metadata); - try { - handler2.func(stream2); - } catch (err) { - call.sendStatus({ - code: constants_1.Status.UNKNOWN, - details: `Server method handler threw error ${err.message}`, - metadata: null - }); - } - }, - onReceiveMessage(message) { - stream2.push(message); - }, - onReceiveHalfClose() { - stream2.push(null); - }, - onCancel() { - if (stream2) { - stream2.cancelled = true; - stream2.emit("cancelled", "cancelled"); - stream2.destroy(); - } - } - }); - } - } -}); - -// node_modules/@grpc/grpc-js/build/src/status-builder.js -var require_status_builder = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/status-builder.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.StatusBuilder = void 0; - var StatusBuilder = class { - constructor() { - this.code = null; - this.details = null; - this.metadata = null; - } - /** - * Adds a status code to the builder. - */ - withCode(code) { - this.code = code; - return this; - } - /** - * Adds details to the builder. - */ - withDetails(details) { - this.details = details; - return this; - } - /** - * Adds metadata to the builder. - */ - withMetadata(metadata) { - this.metadata = metadata; - return this; - } - /** - * Builds the status object. - */ - build() { - const status = {}; - if (this.code !== null) { - status.code = this.code; - } - if (this.details !== null) { - status.details = this.details; - } - if (this.metadata !== null) { - status.metadata = this.metadata; - } - return status; - } - }; - exports2.StatusBuilder = StatusBuilder; - } -}); - -// node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.js -var require_load_balancer_pick_first = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.LeafLoadBalancer = exports2.PickFirstLoadBalancer = exports2.PickFirstLoadBalancingConfig = void 0; - exports2.shuffled = shuffled; - exports2.setup = setup; - var load_balancer_1 = require_load_balancer(); - var connectivity_state_1 = require_connectivity_state(); - var picker_1 = require_picker(); - var subchannel_address_1 = require_subchannel_address(); - var logging = require_logging(); - var constants_1 = require_constants7(); - var subchannel_address_2 = require_subchannel_address(); - var net_1 = require("net"); - var call_interface_1 = require_call_interface(); - var TRACER_NAME = "pick_first"; - function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); - } - var TYPE_NAME = "pick_first"; - var CONNECTION_DELAY_INTERVAL_MS = 250; - var PickFirstLoadBalancingConfig = class _PickFirstLoadBalancingConfig { - constructor(shuffleAddressList) { - this.shuffleAddressList = shuffleAddressList; - } - getLoadBalancerName() { - return TYPE_NAME; - } - toJsonObject() { - return { - [TYPE_NAME]: { - shuffleAddressList: this.shuffleAddressList - } - }; - } - getShuffleAddressList() { - return this.shuffleAddressList; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - static createFromJson(obj) { - if ("shuffleAddressList" in obj && !(typeof obj.shuffleAddressList === "boolean")) { - throw new Error("pick_first config field shuffleAddressList must be a boolean if provided"); - } - return new _PickFirstLoadBalancingConfig(obj.shuffleAddressList === true); - } - }; - exports2.PickFirstLoadBalancingConfig = PickFirstLoadBalancingConfig; - var PickFirstPicker = class { - constructor(subchannel) { - this.subchannel = subchannel; - } - pick(pickArgs) { - return { - pickResultType: picker_1.PickResultType.COMPLETE, - subchannel: this.subchannel, - status: null, - onCallStarted: null, - onCallEnded: null - }; - } - }; - function shuffled(list) { - const result = list.slice(); - for (let i = result.length - 1; i > 1; i--) { - const j = Math.floor(Math.random() * (i + 1)); - const temp = result[i]; - result[i] = result[j]; - result[j] = temp; - } - return result; - } - function interleaveAddressFamilies(addressList) { - if (addressList.length === 0) { - return []; - } - const result = []; - const ipv6Addresses = []; - const ipv4Addresses = []; - const ipv6First = (0, subchannel_address_2.isTcpSubchannelAddress)(addressList[0]) && (0, net_1.isIPv6)(addressList[0].host); - for (const address of addressList) { - if ((0, subchannel_address_2.isTcpSubchannelAddress)(address) && (0, net_1.isIPv6)(address.host)) { - ipv6Addresses.push(address); - } else { - ipv4Addresses.push(address); - } - } - const firstList = ipv6First ? ipv6Addresses : ipv4Addresses; - const secondList = ipv6First ? ipv4Addresses : ipv6Addresses; - for (let i = 0; i < Math.max(firstList.length, secondList.length); i++) { - if (i < firstList.length) { - result.push(firstList[i]); - } - if (i < secondList.length) { - result.push(secondList[i]); - } - } - return result; - } - var REPORT_HEALTH_STATUS_OPTION_NAME = "grpc-node.internal.pick-first.report_health_status"; - var PickFirstLoadBalancer = class { - /** - * Load balancer that attempts to connect to each backend in the address list - * in order, and picks the first one that connects, using it for every - * request. - * @param channelControlHelper `ChannelControlHelper` instance provided by - * this load balancer's owner. - */ - constructor(channelControlHelper) { - this.channelControlHelper = channelControlHelper; - this.children = []; - this.currentState = connectivity_state_1.ConnectivityState.IDLE; - this.currentSubchannelIndex = 0; - this.currentPick = null; - this.subchannelStateListener = (subchannel, previousState, newState, keepaliveTime, errorMessage) => { - this.onSubchannelStateUpdate(subchannel, previousState, newState, errorMessage); - }; - this.pickedSubchannelHealthListener = () => this.calculateAndReportNewState(); - this.stickyTransientFailureMode = false; - this.reportHealthStatus = false; - this.lastError = null; - this.latestAddressList = null; - this.latestOptions = {}; - this.latestResolutionNote = ""; - this.connectionDelayTimeout = setTimeout(() => { - }, 0); - clearTimeout(this.connectionDelayTimeout); - } - allChildrenHaveReportedTF() { - return this.children.every((child) => child.hasReportedTransientFailure); - } - resetChildrenReportedTF() { - this.children.every((child) => child.hasReportedTransientFailure = false); - } - calculateAndReportNewState() { - var _a; - if (this.currentPick) { - if (this.reportHealthStatus && !this.currentPick.isHealthy()) { - const errorMessage = `Picked subchannel ${this.currentPick.getAddress()} is unhealthy`; - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ - details: errorMessage - }), errorMessage); - } else { - this.updateState(connectivity_state_1.ConnectivityState.READY, new PickFirstPicker(this.currentPick), null); - } - } else if (((_a = this.latestAddressList) === null || _a === void 0 ? void 0 : _a.length) === 0) { - const errorMessage = `No connection established. Last error: ${this.lastError}. Resolution note: ${this.latestResolutionNote}`; - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ - details: errorMessage - }), errorMessage); - } else if (this.children.length === 0) { - this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null); - } else { - if (this.stickyTransientFailureMode) { - const errorMessage = `No connection established. Last error: ${this.lastError}. Resolution note: ${this.latestResolutionNote}`; - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ - details: errorMessage - }), errorMessage); - } else { - this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this), null); - } - } - } - requestReresolution() { - this.channelControlHelper.requestReresolution(); - } - maybeEnterStickyTransientFailureMode() { - if (!this.allChildrenHaveReportedTF()) { - return; - } - this.requestReresolution(); - this.resetChildrenReportedTF(); - if (this.stickyTransientFailureMode) { - this.calculateAndReportNewState(); - return; - } - this.stickyTransientFailureMode = true; - for (const { subchannel } of this.children) { - subchannel.startConnecting(); - } - this.calculateAndReportNewState(); - } - removeCurrentPick() { - if (this.currentPick !== null) { - this.currentPick.removeConnectivityStateListener(this.subchannelStateListener); - this.channelControlHelper.removeChannelzChild(this.currentPick.getChannelzRef()); - this.currentPick.removeHealthStateWatcher(this.pickedSubchannelHealthListener); - this.currentPick.unref(); - this.currentPick = null; - } - } - onSubchannelStateUpdate(subchannel, previousState, newState, errorMessage) { - var _a; - if ((_a = this.currentPick) === null || _a === void 0 ? void 0 : _a.realSubchannelEquals(subchannel)) { - if (newState !== connectivity_state_1.ConnectivityState.READY) { - this.removeCurrentPick(); - this.calculateAndReportNewState(); - } - return; - } - for (const [index, child] of this.children.entries()) { - if (subchannel.realSubchannelEquals(child.subchannel)) { - if (newState === connectivity_state_1.ConnectivityState.READY) { - this.pickSubchannel(child.subchannel); - } - if (newState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { - child.hasReportedTransientFailure = true; - if (errorMessage) { - this.lastError = errorMessage; - } - this.maybeEnterStickyTransientFailureMode(); - if (index === this.currentSubchannelIndex) { - this.startNextSubchannelConnecting(index + 1); - } - } - child.subchannel.startConnecting(); - return; - } - } - } - startNextSubchannelConnecting(startIndex) { - clearTimeout(this.connectionDelayTimeout); - for (const [index, child] of this.children.entries()) { - if (index >= startIndex) { - const subchannelState = child.subchannel.getConnectivityState(); - if (subchannelState === connectivity_state_1.ConnectivityState.IDLE || subchannelState === connectivity_state_1.ConnectivityState.CONNECTING) { - this.startConnecting(index); - return; - } - } - } - this.maybeEnterStickyTransientFailureMode(); - } - /** - * Have a single subchannel in the `subchannels` list start connecting. - * @param subchannelIndex The index into the `subchannels` list. - */ - startConnecting(subchannelIndex) { - var _a, _b; - clearTimeout(this.connectionDelayTimeout); - this.currentSubchannelIndex = subchannelIndex; - if (this.children[subchannelIndex].subchannel.getConnectivityState() === connectivity_state_1.ConnectivityState.IDLE) { - trace("Start connecting to subchannel with address " + this.children[subchannelIndex].subchannel.getAddress()); - process.nextTick(() => { - var _a2; - (_a2 = this.children[subchannelIndex]) === null || _a2 === void 0 ? void 0 : _a2.subchannel.startConnecting(); - }); - } - this.connectionDelayTimeout = setTimeout(() => { - this.startNextSubchannelConnecting(subchannelIndex + 1); - }, CONNECTION_DELAY_INTERVAL_MS); - (_b = (_a = this.connectionDelayTimeout).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - } - /** - * Declare that the specified subchannel should be used to make requests. - * This functions the same independent of whether subchannel is a member of - * this.children and whether it is equal to this.currentPick. - * Prerequisite: subchannel.getConnectivityState() === READY. - * @param subchannel - */ - pickSubchannel(subchannel) { - trace("Pick subchannel with address " + subchannel.getAddress()); - this.stickyTransientFailureMode = false; - subchannel.ref(); - this.channelControlHelper.addChannelzChild(subchannel.getChannelzRef()); - this.removeCurrentPick(); - this.resetSubchannelList(); - subchannel.addConnectivityStateListener(this.subchannelStateListener); - subchannel.addHealthStateWatcher(this.pickedSubchannelHealthListener); - this.currentPick = subchannel; - clearTimeout(this.connectionDelayTimeout); - this.calculateAndReportNewState(); - } - updateState(newState, picker, errorMessage) { - trace(connectivity_state_1.ConnectivityState[this.currentState] + " -> " + connectivity_state_1.ConnectivityState[newState]); - this.currentState = newState; - this.channelControlHelper.updateState(newState, picker, errorMessage); - } - resetSubchannelList() { - for (const child of this.children) { - child.subchannel.removeConnectivityStateListener(this.subchannelStateListener); - child.subchannel.unref(); - this.channelControlHelper.removeChannelzChild(child.subchannel.getChannelzRef()); - } - this.currentSubchannelIndex = 0; - this.children = []; - } - connectToAddressList(addressList, options) { - trace("connectToAddressList([" + addressList.map((address) => (0, subchannel_address_1.subchannelAddressToString)(address)) + "])"); - const newChildrenList = addressList.map((address) => ({ - subchannel: this.channelControlHelper.createSubchannel(address, options), - hasReportedTransientFailure: false - })); - for (const { subchannel } of newChildrenList) { - if (subchannel.getConnectivityState() === connectivity_state_1.ConnectivityState.READY) { - this.pickSubchannel(subchannel); - return; - } - } - for (const { subchannel } of newChildrenList) { - subchannel.ref(); - this.channelControlHelper.addChannelzChild(subchannel.getChannelzRef()); - } - this.resetSubchannelList(); - this.children = newChildrenList; - for (const { subchannel } of this.children) { - subchannel.addConnectivityStateListener(this.subchannelStateListener); - } - for (const child of this.children) { - if (child.subchannel.getConnectivityState() === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { - child.hasReportedTransientFailure = true; - } - } - this.startNextSubchannelConnecting(0); - this.calculateAndReportNewState(); - } - updateAddressList(maybeEndpointList, lbConfig, options, resolutionNote) { - if (!(lbConfig instanceof PickFirstLoadBalancingConfig)) { - return false; - } - if (!maybeEndpointList.ok) { - if (this.children.length === 0 && this.currentPick === null) { - this.channelControlHelper.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(maybeEndpointList.error), maybeEndpointList.error.details); - } - return true; - } - let endpointList = maybeEndpointList.value; - this.reportHealthStatus = options[REPORT_HEALTH_STATUS_OPTION_NAME]; - if (lbConfig.getShuffleAddressList()) { - endpointList = shuffled(endpointList); - } - const rawAddressList = [].concat(...endpointList.map((endpoint2) => endpoint2.addresses)); - trace("updateAddressList([" + rawAddressList.map((address) => (0, subchannel_address_1.subchannelAddressToString)(address)) + "])"); - const addressList = interleaveAddressFamilies(rawAddressList); - this.latestAddressList = addressList; - this.latestOptions = options; - this.connectToAddressList(addressList, options); - this.latestResolutionNote = resolutionNote; - if (rawAddressList.length > 0) { - return true; - } else { - this.lastError = "No addresses resolved"; - return false; - } - } - exitIdle() { - if (this.currentState === connectivity_state_1.ConnectivityState.IDLE && this.latestAddressList) { - this.connectToAddressList(this.latestAddressList, this.latestOptions); - } - } - resetBackoff() { - } - destroy() { - this.resetSubchannelList(); - this.removeCurrentPick(); - } - getTypeName() { - return TYPE_NAME; - } - }; - exports2.PickFirstLoadBalancer = PickFirstLoadBalancer; - var LEAF_CONFIG = new PickFirstLoadBalancingConfig(false); - var LeafLoadBalancer = class { - constructor(endpoint2, channelControlHelper, options, resolutionNote) { - this.endpoint = endpoint2; - this.options = options; - this.resolutionNote = resolutionNote; - this.latestState = connectivity_state_1.ConnectivityState.IDLE; - const childChannelControlHelper = (0, load_balancer_1.createChildChannelControlHelper)(channelControlHelper, { - updateState: (connectivityState, picker, errorMessage) => { - this.latestState = connectivityState; - this.latestPicker = picker; - channelControlHelper.updateState(connectivityState, picker, errorMessage); - } - }); - this.pickFirstBalancer = new PickFirstLoadBalancer(childChannelControlHelper); - this.latestPicker = new picker_1.QueuePicker(this.pickFirstBalancer); - } - startConnecting() { - this.pickFirstBalancer.updateAddressList((0, call_interface_1.statusOrFromValue)([this.endpoint]), LEAF_CONFIG, Object.assign(Object.assign({}, this.options), { [REPORT_HEALTH_STATUS_OPTION_NAME]: true }), this.resolutionNote); - } - /** - * Update the endpoint associated with this LeafLoadBalancer to a new - * endpoint. Does not trigger connection establishment if a connection - * attempt is not already in progress. - * @param newEndpoint - */ - updateEndpoint(newEndpoint, newOptions) { - this.options = newOptions; - this.endpoint = newEndpoint; - if (this.latestState !== connectivity_state_1.ConnectivityState.IDLE) { - this.startConnecting(); - } - } - getConnectivityState() { - return this.latestState; - } - getPicker() { - return this.latestPicker; - } - getEndpoint() { - return this.endpoint; - } - exitIdle() { - this.pickFirstBalancer.exitIdle(); - } - destroy() { - this.pickFirstBalancer.destroy(); - } - }; - exports2.LeafLoadBalancer = LeafLoadBalancer; - function setup() { - (0, load_balancer_1.registerLoadBalancerType)(TYPE_NAME, PickFirstLoadBalancer, PickFirstLoadBalancingConfig); - (0, load_balancer_1.registerDefaultLoadBalancerType)(TYPE_NAME); - } - } -}); - -// node_modules/@grpc/grpc-js/build/src/certificate-provider.js -var require_certificate_provider = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/certificate-provider.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.FileWatcherCertificateProvider = void 0; - var fs3 = require("fs"); - var logging = require_logging(); - var constants_1 = require_constants7(); - var util_1 = require("util"); - var TRACER_NAME = "certificate_provider"; - function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); - } - var readFilePromise = (0, util_1.promisify)(fs3.readFile); - var FileWatcherCertificateProvider = class { - constructor(config) { - this.config = config; - this.refreshTimer = null; - this.fileResultPromise = null; - this.latestCaUpdate = void 0; - this.caListeners = /* @__PURE__ */ new Set(); - this.latestIdentityUpdate = void 0; - this.identityListeners = /* @__PURE__ */ new Set(); - this.lastUpdateTime = null; - if (config.certificateFile === void 0 !== (config.privateKeyFile === void 0)) { - throw new Error("certificateFile and privateKeyFile must be set or unset together"); - } - if (config.certificateFile === void 0 && config.caCertificateFile === void 0) { - throw new Error("At least one of certificateFile and caCertificateFile must be set"); - } - trace("File watcher constructed with config " + JSON.stringify(config)); - } - updateCertificates() { - if (this.fileResultPromise) { - return; - } - this.fileResultPromise = Promise.allSettled([ - this.config.certificateFile ? readFilePromise(this.config.certificateFile) : Promise.reject(), - this.config.privateKeyFile ? readFilePromise(this.config.privateKeyFile) : Promise.reject(), - this.config.caCertificateFile ? readFilePromise(this.config.caCertificateFile) : Promise.reject() - ]); - this.fileResultPromise.then(([certificateResult, privateKeyResult, caCertificateResult]) => { - if (!this.refreshTimer) { - return; - } - trace("File watcher read certificates certificate " + certificateResult.status + ", privateKey " + privateKeyResult.status + ", CA certificate " + caCertificateResult.status); - this.lastUpdateTime = /* @__PURE__ */ new Date(); - this.fileResultPromise = null; - if (certificateResult.status === "fulfilled" && privateKeyResult.status === "fulfilled") { - this.latestIdentityUpdate = { - certificate: certificateResult.value, - privateKey: privateKeyResult.value - }; - } else { - this.latestIdentityUpdate = null; - } - if (caCertificateResult.status === "fulfilled") { - this.latestCaUpdate = { - caCertificate: caCertificateResult.value - }; - } else { - this.latestCaUpdate = null; - } - for (const listener of this.identityListeners) { - listener(this.latestIdentityUpdate); - } - for (const listener of this.caListeners) { - listener(this.latestCaUpdate); - } - }); - trace("File watcher initiated certificate update"); - } - maybeStartWatchingFiles() { - if (!this.refreshTimer) { - const timeSinceLastUpdate = this.lastUpdateTime ? (/* @__PURE__ */ new Date()).getTime() - this.lastUpdateTime.getTime() : Infinity; - if (timeSinceLastUpdate > this.config.refreshIntervalMs) { - this.updateCertificates(); - } - if (timeSinceLastUpdate > this.config.refreshIntervalMs * 2) { - this.latestCaUpdate = void 0; - this.latestIdentityUpdate = void 0; - } - this.refreshTimer = setInterval(() => this.updateCertificates(), this.config.refreshIntervalMs); - trace("File watcher started watching"); - } - } - maybeStopWatchingFiles() { - if (this.caListeners.size === 0 && this.identityListeners.size === 0) { - this.fileResultPromise = null; - if (this.refreshTimer) { - clearInterval(this.refreshTimer); - this.refreshTimer = null; - } - } - } - addCaCertificateListener(listener) { - this.caListeners.add(listener); - this.maybeStartWatchingFiles(); - if (this.latestCaUpdate !== void 0) { - process.nextTick(listener, this.latestCaUpdate); - } - } - removeCaCertificateListener(listener) { - this.caListeners.delete(listener); - this.maybeStopWatchingFiles(); - } - addIdentityCertificateListener(listener) { - this.identityListeners.add(listener); - this.maybeStartWatchingFiles(); - if (this.latestIdentityUpdate !== void 0) { - process.nextTick(listener, this.latestIdentityUpdate); - } - } - removeIdentityCertificateListener(listener) { - this.identityListeners.delete(listener); - this.maybeStopWatchingFiles(); - } - }; - exports2.FileWatcherCertificateProvider = FileWatcherCertificateProvider; - } -}); - -// node_modules/@grpc/grpc-js/build/src/experimental.js -var require_experimental = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/experimental.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = exports2.createCertificateProviderChannelCredentials = exports2.FileWatcherCertificateProvider = exports2.createCertificateProviderServerCredentials = exports2.createServerCredentialsWithInterceptors = exports2.BaseSubchannelWrapper = exports2.registerAdminService = exports2.FilterStackFactory = exports2.BaseFilter = exports2.statusOrFromError = exports2.statusOrFromValue = exports2.PickResultType = exports2.QueuePicker = exports2.UnavailablePicker = exports2.ChildLoadBalancerHandler = exports2.EndpointMap = exports2.endpointHasAddress = exports2.endpointToString = exports2.subchannelAddressToString = exports2.LeafLoadBalancer = exports2.isLoadBalancerNameRegistered = exports2.parseLoadBalancingConfig = exports2.selectLbConfigFromList = exports2.registerLoadBalancerType = exports2.createChildChannelControlHelper = exports2.BackoffTimeout = exports2.parseDuration = exports2.durationToMs = exports2.splitHostPort = exports2.uriToString = exports2.CHANNEL_ARGS_CONFIG_SELECTOR_KEY = exports2.createResolver = exports2.registerResolver = exports2.log = exports2.trace = void 0; - var logging_1 = require_logging(); - Object.defineProperty(exports2, "trace", { enumerable: true, get: function() { - return logging_1.trace; - } }); - Object.defineProperty(exports2, "log", { enumerable: true, get: function() { - return logging_1.log; - } }); - var resolver_1 = require_resolver(); - Object.defineProperty(exports2, "registerResolver", { enumerable: true, get: function() { - return resolver_1.registerResolver; - } }); - Object.defineProperty(exports2, "createResolver", { enumerable: true, get: function() { - return resolver_1.createResolver; - } }); - Object.defineProperty(exports2, "CHANNEL_ARGS_CONFIG_SELECTOR_KEY", { enumerable: true, get: function() { - return resolver_1.CHANNEL_ARGS_CONFIG_SELECTOR_KEY; - } }); - var uri_parser_1 = require_uri_parser(); - Object.defineProperty(exports2, "uriToString", { enumerable: true, get: function() { - return uri_parser_1.uriToString; - } }); - Object.defineProperty(exports2, "splitHostPort", { enumerable: true, get: function() { - return uri_parser_1.splitHostPort; - } }); - var duration_1 = require_duration(); - Object.defineProperty(exports2, "durationToMs", { enumerable: true, get: function() { - return duration_1.durationToMs; - } }); - Object.defineProperty(exports2, "parseDuration", { enumerable: true, get: function() { - return duration_1.parseDuration; - } }); - var backoff_timeout_1 = require_backoff_timeout(); - Object.defineProperty(exports2, "BackoffTimeout", { enumerable: true, get: function() { - return backoff_timeout_1.BackoffTimeout; - } }); - var load_balancer_1 = require_load_balancer(); - Object.defineProperty(exports2, "createChildChannelControlHelper", { enumerable: true, get: function() { - return load_balancer_1.createChildChannelControlHelper; - } }); - Object.defineProperty(exports2, "registerLoadBalancerType", { enumerable: true, get: function() { - return load_balancer_1.registerLoadBalancerType; - } }); - Object.defineProperty(exports2, "selectLbConfigFromList", { enumerable: true, get: function() { - return load_balancer_1.selectLbConfigFromList; - } }); - Object.defineProperty(exports2, "parseLoadBalancingConfig", { enumerable: true, get: function() { - return load_balancer_1.parseLoadBalancingConfig; - } }); - Object.defineProperty(exports2, "isLoadBalancerNameRegistered", { enumerable: true, get: function() { - return load_balancer_1.isLoadBalancerNameRegistered; - } }); - var load_balancer_pick_first_1 = require_load_balancer_pick_first(); - Object.defineProperty(exports2, "LeafLoadBalancer", { enumerable: true, get: function() { - return load_balancer_pick_first_1.LeafLoadBalancer; - } }); - var subchannel_address_1 = require_subchannel_address(); - Object.defineProperty(exports2, "subchannelAddressToString", { enumerable: true, get: function() { - return subchannel_address_1.subchannelAddressToString; - } }); - Object.defineProperty(exports2, "endpointToString", { enumerable: true, get: function() { - return subchannel_address_1.endpointToString; - } }); - Object.defineProperty(exports2, "endpointHasAddress", { enumerable: true, get: function() { - return subchannel_address_1.endpointHasAddress; - } }); - Object.defineProperty(exports2, "EndpointMap", { enumerable: true, get: function() { - return subchannel_address_1.EndpointMap; - } }); - var load_balancer_child_handler_1 = require_load_balancer_child_handler(); - Object.defineProperty(exports2, "ChildLoadBalancerHandler", { enumerable: true, get: function() { - return load_balancer_child_handler_1.ChildLoadBalancerHandler; - } }); - var picker_1 = require_picker(); - Object.defineProperty(exports2, "UnavailablePicker", { enumerable: true, get: function() { - return picker_1.UnavailablePicker; - } }); - Object.defineProperty(exports2, "QueuePicker", { enumerable: true, get: function() { - return picker_1.QueuePicker; - } }); - Object.defineProperty(exports2, "PickResultType", { enumerable: true, get: function() { - return picker_1.PickResultType; - } }); - var call_interface_1 = require_call_interface(); - Object.defineProperty(exports2, "statusOrFromValue", { enumerable: true, get: function() { - return call_interface_1.statusOrFromValue; - } }); - Object.defineProperty(exports2, "statusOrFromError", { enumerable: true, get: function() { - return call_interface_1.statusOrFromError; - } }); - var filter_1 = require_filter(); - Object.defineProperty(exports2, "BaseFilter", { enumerable: true, get: function() { - return filter_1.BaseFilter; - } }); - var filter_stack_1 = require_filter_stack(); - Object.defineProperty(exports2, "FilterStackFactory", { enumerable: true, get: function() { - return filter_stack_1.FilterStackFactory; - } }); - var admin_1 = require_admin(); - Object.defineProperty(exports2, "registerAdminService", { enumerable: true, get: function() { - return admin_1.registerAdminService; - } }); - var subchannel_interface_1 = require_subchannel_interface(); - Object.defineProperty(exports2, "BaseSubchannelWrapper", { enumerable: true, get: function() { - return subchannel_interface_1.BaseSubchannelWrapper; - } }); - var server_credentials_1 = require_server_credentials(); - Object.defineProperty(exports2, "createServerCredentialsWithInterceptors", { enumerable: true, get: function() { - return server_credentials_1.createServerCredentialsWithInterceptors; - } }); - Object.defineProperty(exports2, "createCertificateProviderServerCredentials", { enumerable: true, get: function() { - return server_credentials_1.createCertificateProviderServerCredentials; - } }); - var certificate_provider_1 = require_certificate_provider(); - Object.defineProperty(exports2, "FileWatcherCertificateProvider", { enumerable: true, get: function() { - return certificate_provider_1.FileWatcherCertificateProvider; - } }); - var channel_credentials_1 = require_channel_credentials(); - Object.defineProperty(exports2, "createCertificateProviderChannelCredentials", { enumerable: true, get: function() { - return channel_credentials_1.createCertificateProviderChannelCredentials; - } }); - var internal_channel_1 = require_internal_channel(); - Object.defineProperty(exports2, "SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX", { enumerable: true, get: function() { - return internal_channel_1.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX; - } }); - } -}); - -// node_modules/@grpc/grpc-js/build/src/resolver-uds.js -var require_resolver_uds = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/resolver-uds.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.setup = setup; - var resolver_1 = require_resolver(); - var call_interface_1 = require_call_interface(); - var UdsResolver = class { - constructor(target, listener, channelOptions) { - this.listener = listener; - this.hasReturnedResult = false; - this.endpoints = []; - let path; - if (target.authority === "") { - path = "/" + target.path; - } else { - path = target.path; - } - this.endpoints = [{ addresses: [{ path }] }]; - } - updateResolution() { - if (!this.hasReturnedResult) { - this.hasReturnedResult = true; - process.nextTick(this.listener, (0, call_interface_1.statusOrFromValue)(this.endpoints), {}, null, ""); - } - } - destroy() { - this.hasReturnedResult = false; - } - static getDefaultAuthority(target) { - return "localhost"; - } - }; - function setup() { - (0, resolver_1.registerResolver)("unix", UdsResolver); - } - } -}); - -// node_modules/@grpc/grpc-js/build/src/resolver-ip.js -var require_resolver_ip = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/resolver-ip.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.setup = setup; - var net_1 = require("net"); - var call_interface_1 = require_call_interface(); - var constants_1 = require_constants7(); - var metadata_1 = require_metadata(); - var resolver_1 = require_resolver(); - var subchannel_address_1 = require_subchannel_address(); - var uri_parser_1 = require_uri_parser(); - var logging = require_logging(); - var TRACER_NAME = "ip_resolver"; - function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); - } - var IPV4_SCHEME = "ipv4"; - var IPV6_SCHEME = "ipv6"; - var DEFAULT_PORT = 443; - var IpResolver = class { - constructor(target, listener, channelOptions) { - var _a; - this.listener = listener; - this.endpoints = []; - this.error = null; - this.hasReturnedResult = false; - trace("Resolver constructed for target " + (0, uri_parser_1.uriToString)(target)); - const addresses = []; - if (!(target.scheme === IPV4_SCHEME || target.scheme === IPV6_SCHEME)) { - this.error = { - code: constants_1.Status.UNAVAILABLE, - details: `Unrecognized scheme ${target.scheme} in IP resolver`, - metadata: new metadata_1.Metadata() - }; - return; - } - const pathList = target.path.split(","); - for (const path of pathList) { - const hostPort = (0, uri_parser_1.splitHostPort)(path); - if (hostPort === null) { - this.error = { - code: constants_1.Status.UNAVAILABLE, - details: `Failed to parse ${target.scheme} address ${path}`, - metadata: new metadata_1.Metadata() - }; - return; - } - if (target.scheme === IPV4_SCHEME && !(0, net_1.isIPv4)(hostPort.host) || target.scheme === IPV6_SCHEME && !(0, net_1.isIPv6)(hostPort.host)) { - this.error = { - code: constants_1.Status.UNAVAILABLE, - details: `Failed to parse ${target.scheme} address ${path}`, - metadata: new metadata_1.Metadata() - }; - return; - } - addresses.push({ - host: hostPort.host, - port: (_a = hostPort.port) !== null && _a !== void 0 ? _a : DEFAULT_PORT - }); - } - this.endpoints = addresses.map((address) => ({ addresses: [address] })); - trace("Parsed " + target.scheme + " address list " + addresses.map(subchannel_address_1.subchannelAddressToString)); - } - updateResolution() { - if (!this.hasReturnedResult) { - this.hasReturnedResult = true; - process.nextTick(() => { - if (this.error) { - this.listener((0, call_interface_1.statusOrFromError)(this.error), {}, null, ""); - } else { - this.listener((0, call_interface_1.statusOrFromValue)(this.endpoints), {}, null, ""); - } - }); - } - } - destroy() { - this.hasReturnedResult = false; - } - static getDefaultAuthority(target) { - return target.path.split(",")[0]; - } - }; - function setup() { - (0, resolver_1.registerResolver)(IPV4_SCHEME, IpResolver); - (0, resolver_1.registerResolver)(IPV6_SCHEME, IpResolver); - } - } -}); - -// node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.js -var require_load_balancer_round_robin = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RoundRobinLoadBalancer = void 0; - exports2.setup = setup; - var load_balancer_1 = require_load_balancer(); - var connectivity_state_1 = require_connectivity_state(); - var picker_1 = require_picker(); - var logging = require_logging(); - var constants_1 = require_constants7(); - var subchannel_address_1 = require_subchannel_address(); - var load_balancer_pick_first_1 = require_load_balancer_pick_first(); - var TRACER_NAME = "round_robin"; - function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); - } - var TYPE_NAME = "round_robin"; - var RoundRobinLoadBalancingConfig = class _RoundRobinLoadBalancingConfig { - getLoadBalancerName() { - return TYPE_NAME; - } - constructor() { - } - toJsonObject() { - return { - [TYPE_NAME]: {} - }; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - static createFromJson(obj) { - return new _RoundRobinLoadBalancingConfig(); - } - }; - var RoundRobinPicker = class { - constructor(children, nextIndex = 0) { - this.children = children; - this.nextIndex = nextIndex; - } - pick(pickArgs) { - const childPicker = this.children[this.nextIndex].picker; - this.nextIndex = (this.nextIndex + 1) % this.children.length; - return childPicker.pick(pickArgs); - } - /** - * Check what the next subchannel returned would be. Used by the load - * balancer implementation to preserve this part of the picker state if - * possible when a subchannel connects or disconnects. - */ - peekNextEndpoint() { - return this.children[this.nextIndex].endpoint; - } - }; - function rotateArray(list, startIndex) { - return [...list.slice(startIndex), ...list.slice(0, startIndex)]; - } - var RoundRobinLoadBalancer = class { - constructor(channelControlHelper) { - this.channelControlHelper = channelControlHelper; - this.children = []; - this.currentState = connectivity_state_1.ConnectivityState.IDLE; - this.currentReadyPicker = null; - this.updatesPaused = false; - this.lastError = null; - this.childChannelControlHelper = (0, load_balancer_1.createChildChannelControlHelper)(channelControlHelper, { - updateState: (connectivityState, picker, errorMessage) => { - if (this.currentState === connectivity_state_1.ConnectivityState.READY && connectivityState !== connectivity_state_1.ConnectivityState.READY) { - this.channelControlHelper.requestReresolution(); - } - if (errorMessage) { - this.lastError = errorMessage; - } - this.calculateAndUpdateState(); - } - }); - } - countChildrenWithState(state) { - return this.children.filter((child) => child.getConnectivityState() === state).length; - } - calculateAndUpdateState() { - if (this.updatesPaused) { - return; - } - if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.READY) > 0) { - const readyChildren = this.children.filter((child) => child.getConnectivityState() === connectivity_state_1.ConnectivityState.READY); - let index = 0; - if (this.currentReadyPicker !== null) { - const nextPickedEndpoint = this.currentReadyPicker.peekNextEndpoint(); - index = readyChildren.findIndex((child) => (0, subchannel_address_1.endpointEqual)(child.getEndpoint(), nextPickedEndpoint)); - if (index < 0) { - index = 0; - } - } - this.updateState(connectivity_state_1.ConnectivityState.READY, new RoundRobinPicker(readyChildren.map((child) => ({ - endpoint: child.getEndpoint(), - picker: child.getPicker() - })), index), null); - } else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.CONNECTING) > 0) { - this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this), null); - } else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) > 0) { - const errorMessage = `round_robin: No connection established. Last error: ${this.lastError}`; - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ - details: errorMessage - }), errorMessage); - } else { - this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null); - } - for (const child of this.children) { - if (child.getConnectivityState() === connectivity_state_1.ConnectivityState.IDLE) { - child.exitIdle(); - } - } - } - updateState(newState, picker, errorMessage) { - trace(connectivity_state_1.ConnectivityState[this.currentState] + " -> " + connectivity_state_1.ConnectivityState[newState]); - if (newState === connectivity_state_1.ConnectivityState.READY) { - this.currentReadyPicker = picker; - } else { - this.currentReadyPicker = null; - } - this.currentState = newState; - this.channelControlHelper.updateState(newState, picker, errorMessage); - } - resetSubchannelList() { - for (const child of this.children) { - child.destroy(); - } - this.children = []; - } - updateAddressList(maybeEndpointList, lbConfig, options, resolutionNote) { - if (!(lbConfig instanceof RoundRobinLoadBalancingConfig)) { - return false; - } - if (!maybeEndpointList.ok) { - if (this.children.length === 0) { - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(maybeEndpointList.error), maybeEndpointList.error.details); - } - return true; - } - const startIndex = Math.random() * maybeEndpointList.value.length | 0; - const endpointList = rotateArray(maybeEndpointList.value, startIndex); - this.resetSubchannelList(); - if (endpointList.length === 0) { - const errorMessage = `No addresses resolved. Resolution note: ${resolutionNote}`; - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ details: errorMessage }), errorMessage); - } - trace("Connect to endpoint list " + endpointList.map(subchannel_address_1.endpointToString)); - this.updatesPaused = true; - this.children = endpointList.map((endpoint2) => new load_balancer_pick_first_1.LeafLoadBalancer(endpoint2, this.childChannelControlHelper, options, resolutionNote)); - for (const child of this.children) { - child.startConnecting(); - } - this.updatesPaused = false; - this.calculateAndUpdateState(); - return true; - } - exitIdle() { - } - resetBackoff() { - } - destroy() { - this.resetSubchannelList(); - } - getTypeName() { - return TYPE_NAME; - } - }; - exports2.RoundRobinLoadBalancer = RoundRobinLoadBalancer; - function setup() { - (0, load_balancer_1.registerLoadBalancerType)(TYPE_NAME, RoundRobinLoadBalancer, RoundRobinLoadBalancingConfig); - } - } -}); - -// node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.js -var require_load_balancer_outlier_detection = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.js"(exports2) { - "use strict"; - var _a; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.OutlierDetectionLoadBalancer = exports2.OutlierDetectionLoadBalancingConfig = void 0; - exports2.setup = setup; - var connectivity_state_1 = require_connectivity_state(); - var constants_1 = require_constants7(); - var duration_1 = require_duration(); - var experimental_1 = require_experimental(); - var load_balancer_1 = require_load_balancer(); - var load_balancer_child_handler_1 = require_load_balancer_child_handler(); - var picker_1 = require_picker(); - var subchannel_address_1 = require_subchannel_address(); - var subchannel_interface_1 = require_subchannel_interface(); - var logging = require_logging(); - var TRACER_NAME = "outlier_detection"; - function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); - } - var TYPE_NAME = "outlier_detection"; - var OUTLIER_DETECTION_ENABLED = ((_a = process.env.GRPC_EXPERIMENTAL_ENABLE_OUTLIER_DETECTION) !== null && _a !== void 0 ? _a : "true") === "true"; - var defaultSuccessRateEjectionConfig = { - stdev_factor: 1900, - enforcement_percentage: 100, - minimum_hosts: 5, - request_volume: 100 - }; - var defaultFailurePercentageEjectionConfig = { - threshold: 85, - enforcement_percentage: 100, - minimum_hosts: 5, - request_volume: 50 - }; - function validateFieldType(obj, fieldName, expectedType, objectName) { - if (fieldName in obj && obj[fieldName] !== void 0 && typeof obj[fieldName] !== expectedType) { - const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName; - throw new Error(`outlier detection config ${fullFieldName} parse error: expected ${expectedType}, got ${typeof obj[fieldName]}`); - } - } - function validatePositiveDuration(obj, fieldName, objectName) { - const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName; - if (fieldName in obj && obj[fieldName] !== void 0) { - if (!(0, duration_1.isDuration)(obj[fieldName])) { - throw new Error(`outlier detection config ${fullFieldName} parse error: expected Duration, got ${typeof obj[fieldName]}`); - } - if (!(obj[fieldName].seconds >= 0 && obj[fieldName].seconds <= 315576e6 && obj[fieldName].nanos >= 0 && obj[fieldName].nanos <= 999999999)) { - throw new Error(`outlier detection config ${fullFieldName} parse error: values out of range for non-negative Duaration`); - } - } - } - function validatePercentage(obj, fieldName, objectName) { - const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName; - validateFieldType(obj, fieldName, "number", objectName); - if (fieldName in obj && obj[fieldName] !== void 0 && !(obj[fieldName] >= 0 && obj[fieldName] <= 100)) { - throw new Error(`outlier detection config ${fullFieldName} parse error: value out of range for percentage (0-100)`); - } - } - var OutlierDetectionLoadBalancingConfig = class _OutlierDetectionLoadBalancingConfig { - constructor(intervalMs, baseEjectionTimeMs, maxEjectionTimeMs, maxEjectionPercent, successRateEjection, failurePercentageEjection, childPolicy) { - this.childPolicy = childPolicy; - if (childPolicy.getLoadBalancerName() === "pick_first") { - throw new Error("outlier_detection LB policy cannot have a pick_first child policy"); - } - this.intervalMs = intervalMs !== null && intervalMs !== void 0 ? intervalMs : 1e4; - this.baseEjectionTimeMs = baseEjectionTimeMs !== null && baseEjectionTimeMs !== void 0 ? baseEjectionTimeMs : 3e4; - this.maxEjectionTimeMs = maxEjectionTimeMs !== null && maxEjectionTimeMs !== void 0 ? maxEjectionTimeMs : 3e5; - this.maxEjectionPercent = maxEjectionPercent !== null && maxEjectionPercent !== void 0 ? maxEjectionPercent : 10; - this.successRateEjection = successRateEjection ? Object.assign(Object.assign({}, defaultSuccessRateEjectionConfig), successRateEjection) : null; - this.failurePercentageEjection = failurePercentageEjection ? Object.assign(Object.assign({}, defaultFailurePercentageEjectionConfig), failurePercentageEjection) : null; - } - getLoadBalancerName() { - return TYPE_NAME; - } - toJsonObject() { - var _a2, _b; - return { - outlier_detection: { - interval: (0, duration_1.msToDuration)(this.intervalMs), - base_ejection_time: (0, duration_1.msToDuration)(this.baseEjectionTimeMs), - max_ejection_time: (0, duration_1.msToDuration)(this.maxEjectionTimeMs), - max_ejection_percent: this.maxEjectionPercent, - success_rate_ejection: (_a2 = this.successRateEjection) !== null && _a2 !== void 0 ? _a2 : void 0, - failure_percentage_ejection: (_b = this.failurePercentageEjection) !== null && _b !== void 0 ? _b : void 0, - child_policy: [this.childPolicy.toJsonObject()] - } - }; - } - getIntervalMs() { - return this.intervalMs; - } - getBaseEjectionTimeMs() { - return this.baseEjectionTimeMs; - } - getMaxEjectionTimeMs() { - return this.maxEjectionTimeMs; - } - getMaxEjectionPercent() { - return this.maxEjectionPercent; - } - getSuccessRateEjectionConfig() { - return this.successRateEjection; - } - getFailurePercentageEjectionConfig() { - return this.failurePercentageEjection; - } - getChildPolicy() { - return this.childPolicy; - } - static createFromJson(obj) { - var _a2; - validatePositiveDuration(obj, "interval"); - validatePositiveDuration(obj, "base_ejection_time"); - validatePositiveDuration(obj, "max_ejection_time"); - validatePercentage(obj, "max_ejection_percent"); - if ("success_rate_ejection" in obj && obj.success_rate_ejection !== void 0) { - if (typeof obj.success_rate_ejection !== "object") { - throw new Error("outlier detection config success_rate_ejection must be an object"); - } - validateFieldType(obj.success_rate_ejection, "stdev_factor", "number", "success_rate_ejection"); - validatePercentage(obj.success_rate_ejection, "enforcement_percentage", "success_rate_ejection"); - validateFieldType(obj.success_rate_ejection, "minimum_hosts", "number", "success_rate_ejection"); - validateFieldType(obj.success_rate_ejection, "request_volume", "number", "success_rate_ejection"); - } - if ("failure_percentage_ejection" in obj && obj.failure_percentage_ejection !== void 0) { - if (typeof obj.failure_percentage_ejection !== "object") { - throw new Error("outlier detection config failure_percentage_ejection must be an object"); - } - validatePercentage(obj.failure_percentage_ejection, "threshold", "failure_percentage_ejection"); - validatePercentage(obj.failure_percentage_ejection, "enforcement_percentage", "failure_percentage_ejection"); - validateFieldType(obj.failure_percentage_ejection, "minimum_hosts", "number", "failure_percentage_ejection"); - validateFieldType(obj.failure_percentage_ejection, "request_volume", "number", "failure_percentage_ejection"); - } - if (!("child_policy" in obj) || !Array.isArray(obj.child_policy)) { - throw new Error("outlier detection config child_policy must be an array"); - } - const childPolicy = (0, load_balancer_1.selectLbConfigFromList)(obj.child_policy); - if (!childPolicy) { - throw new Error("outlier detection config child_policy: no valid recognized policy found"); - } - return new _OutlierDetectionLoadBalancingConfig(obj.interval ? (0, duration_1.durationToMs)(obj.interval) : null, obj.base_ejection_time ? (0, duration_1.durationToMs)(obj.base_ejection_time) : null, obj.max_ejection_time ? (0, duration_1.durationToMs)(obj.max_ejection_time) : null, (_a2 = obj.max_ejection_percent) !== null && _a2 !== void 0 ? _a2 : null, obj.success_rate_ejection, obj.failure_percentage_ejection, childPolicy); - } - }; - exports2.OutlierDetectionLoadBalancingConfig = OutlierDetectionLoadBalancingConfig; - var OutlierDetectionSubchannelWrapper = class extends subchannel_interface_1.BaseSubchannelWrapper { - constructor(childSubchannel, mapEntry) { - super(childSubchannel); - this.mapEntry = mapEntry; - this.refCount = 0; - } - ref() { - this.child.ref(); - this.refCount += 1; - } - unref() { - this.child.unref(); - this.refCount -= 1; - if (this.refCount <= 0) { - if (this.mapEntry) { - const index = this.mapEntry.subchannelWrappers.indexOf(this); - if (index >= 0) { - this.mapEntry.subchannelWrappers.splice(index, 1); - } - } - } - } - eject() { - this.setHealthy(false); - } - uneject() { - this.setHealthy(true); - } - getMapEntry() { - return this.mapEntry; - } - getWrappedSubchannel() { - return this.child; - } - }; - function createEmptyBucket() { - return { - success: 0, - failure: 0 - }; - } - var CallCounter = class { - constructor() { - this.activeBucket = createEmptyBucket(); - this.inactiveBucket = createEmptyBucket(); - } - addSuccess() { - this.activeBucket.success += 1; - } - addFailure() { - this.activeBucket.failure += 1; - } - switchBuckets() { - this.inactiveBucket = this.activeBucket; - this.activeBucket = createEmptyBucket(); - } - getLastSuccesses() { - return this.inactiveBucket.success; - } - getLastFailures() { - return this.inactiveBucket.failure; - } - }; - var OutlierDetectionPicker = class { - constructor(wrappedPicker, countCalls) { - this.wrappedPicker = wrappedPicker; - this.countCalls = countCalls; - } - pick(pickArgs) { - const wrappedPick = this.wrappedPicker.pick(pickArgs); - if (wrappedPick.pickResultType === picker_1.PickResultType.COMPLETE) { - const subchannelWrapper = wrappedPick.subchannel; - const mapEntry = subchannelWrapper.getMapEntry(); - if (mapEntry) { - let onCallEnded = wrappedPick.onCallEnded; - if (this.countCalls) { - onCallEnded = (statusCode, details, metadata) => { - var _a2; - if (statusCode === constants_1.Status.OK) { - mapEntry.counter.addSuccess(); - } else { - mapEntry.counter.addFailure(); - } - (_a2 = wrappedPick.onCallEnded) === null || _a2 === void 0 ? void 0 : _a2.call(wrappedPick, statusCode, details, metadata); - }; - } - return Object.assign(Object.assign({}, wrappedPick), { subchannel: subchannelWrapper.getWrappedSubchannel(), onCallEnded }); - } else { - return Object.assign(Object.assign({}, wrappedPick), { subchannel: subchannelWrapper.getWrappedSubchannel() }); - } - } else { - return wrappedPick; - } - } - }; - var OutlierDetectionLoadBalancer = class { - constructor(channelControlHelper) { - this.entryMap = new subchannel_address_1.EndpointMap(); - this.latestConfig = null; - this.timerStartTime = null; - this.childBalancer = new load_balancer_child_handler_1.ChildLoadBalancerHandler((0, experimental_1.createChildChannelControlHelper)(channelControlHelper, { - createSubchannel: (subchannelAddress, subchannelArgs) => { - const originalSubchannel = channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs); - const mapEntry = this.entryMap.getForSubchannelAddress(subchannelAddress); - const subchannelWrapper = new OutlierDetectionSubchannelWrapper(originalSubchannel, mapEntry); - if ((mapEntry === null || mapEntry === void 0 ? void 0 : mapEntry.currentEjectionTimestamp) !== null) { - subchannelWrapper.eject(); - } - mapEntry === null || mapEntry === void 0 ? void 0 : mapEntry.subchannelWrappers.push(subchannelWrapper); - return subchannelWrapper; - }, - updateState: (connectivityState, picker, errorMessage) => { - if (connectivityState === connectivity_state_1.ConnectivityState.READY) { - channelControlHelper.updateState(connectivityState, new OutlierDetectionPicker(picker, this.isCountingEnabled()), errorMessage); - } else { - channelControlHelper.updateState(connectivityState, picker, errorMessage); - } - } - })); - this.ejectionTimer = setInterval(() => { - }, 0); - clearInterval(this.ejectionTimer); - } - isCountingEnabled() { - return this.latestConfig !== null && (this.latestConfig.getSuccessRateEjectionConfig() !== null || this.latestConfig.getFailurePercentageEjectionConfig() !== null); - } - getCurrentEjectionPercent() { - let ejectionCount = 0; - for (const mapEntry of this.entryMap.values()) { - if (mapEntry.currentEjectionTimestamp !== null) { - ejectionCount += 1; - } - } - return ejectionCount * 100 / this.entryMap.size; - } - runSuccessRateCheck(ejectionTimestamp) { - if (!this.latestConfig) { - return; - } - const successRateConfig = this.latestConfig.getSuccessRateEjectionConfig(); - if (!successRateConfig) { - return; - } - trace("Running success rate check"); - const targetRequestVolume = successRateConfig.request_volume; - let addresesWithTargetVolume = 0; - const successRates = []; - for (const [endpoint2, mapEntry] of this.entryMap.entries()) { - const successes = mapEntry.counter.getLastSuccesses(); - const failures = mapEntry.counter.getLastFailures(); - trace("Stats for " + (0, subchannel_address_1.endpointToString)(endpoint2) + ": successes=" + successes + " failures=" + failures + " targetRequestVolume=" + targetRequestVolume); - if (successes + failures >= targetRequestVolume) { - addresesWithTargetVolume += 1; - successRates.push(successes / (successes + failures)); - } - } - trace("Found " + addresesWithTargetVolume + " success rate candidates; currentEjectionPercent=" + this.getCurrentEjectionPercent() + " successRates=[" + successRates + "]"); - if (addresesWithTargetVolume < successRateConfig.minimum_hosts) { - return; - } - const successRateMean = successRates.reduce((a, b) => a + b) / successRates.length; - let successRateDeviationSum = 0; - for (const rate of successRates) { - const deviation = rate - successRateMean; - successRateDeviationSum += deviation * deviation; - } - const successRateVariance = successRateDeviationSum / successRates.length; - const successRateStdev = Math.sqrt(successRateVariance); - const ejectionThreshold = successRateMean - successRateStdev * (successRateConfig.stdev_factor / 1e3); - trace("stdev=" + successRateStdev + " ejectionThreshold=" + ejectionThreshold); - for (const [address, mapEntry] of this.entryMap.entries()) { - if (this.getCurrentEjectionPercent() >= this.latestConfig.getMaxEjectionPercent()) { - break; - } - const successes = mapEntry.counter.getLastSuccesses(); - const failures = mapEntry.counter.getLastFailures(); - if (successes + failures < targetRequestVolume) { - continue; - } - const successRate = successes / (successes + failures); - trace("Checking candidate " + address + " successRate=" + successRate); - if (successRate < ejectionThreshold) { - const randomNumber = Math.random() * 100; - trace("Candidate " + address + " randomNumber=" + randomNumber + " enforcement_percentage=" + successRateConfig.enforcement_percentage); - if (randomNumber < successRateConfig.enforcement_percentage) { - trace("Ejecting candidate " + address); - this.eject(mapEntry, ejectionTimestamp); - } - } - } - } - runFailurePercentageCheck(ejectionTimestamp) { - if (!this.latestConfig) { - return; - } - const failurePercentageConfig = this.latestConfig.getFailurePercentageEjectionConfig(); - if (!failurePercentageConfig) { - return; - } - trace("Running failure percentage check. threshold=" + failurePercentageConfig.threshold + " request volume threshold=" + failurePercentageConfig.request_volume); - let addressesWithTargetVolume = 0; - for (const mapEntry of this.entryMap.values()) { - const successes = mapEntry.counter.getLastSuccesses(); - const failures = mapEntry.counter.getLastFailures(); - if (successes + failures >= failurePercentageConfig.request_volume) { - addressesWithTargetVolume += 1; - } - } - if (addressesWithTargetVolume < failurePercentageConfig.minimum_hosts) { - return; - } - for (const [address, mapEntry] of this.entryMap.entries()) { - if (this.getCurrentEjectionPercent() >= this.latestConfig.getMaxEjectionPercent()) { - break; - } - const successes = mapEntry.counter.getLastSuccesses(); - const failures = mapEntry.counter.getLastFailures(); - trace("Candidate successes=" + successes + " failures=" + failures); - if (successes + failures < failurePercentageConfig.request_volume) { - continue; - } - const failurePercentage = failures * 100 / (failures + successes); - if (failurePercentage > failurePercentageConfig.threshold) { - const randomNumber = Math.random() * 100; - trace("Candidate " + address + " randomNumber=" + randomNumber + " enforcement_percentage=" + failurePercentageConfig.enforcement_percentage); - if (randomNumber < failurePercentageConfig.enforcement_percentage) { - trace("Ejecting candidate " + address); - this.eject(mapEntry, ejectionTimestamp); - } - } - } - } - eject(mapEntry, ejectionTimestamp) { - mapEntry.currentEjectionTimestamp = /* @__PURE__ */ new Date(); - mapEntry.ejectionTimeMultiplier += 1; - for (const subchannelWrapper of mapEntry.subchannelWrappers) { - subchannelWrapper.eject(); - } - } - uneject(mapEntry) { - mapEntry.currentEjectionTimestamp = null; - for (const subchannelWrapper of mapEntry.subchannelWrappers) { - subchannelWrapper.uneject(); - } - } - switchAllBuckets() { - for (const mapEntry of this.entryMap.values()) { - mapEntry.counter.switchBuckets(); - } - } - startTimer(delayMs) { - var _a2, _b; - this.ejectionTimer = setTimeout(() => this.runChecks(), delayMs); - (_b = (_a2 = this.ejectionTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a2); - } - runChecks() { - const ejectionTimestamp = /* @__PURE__ */ new Date(); - trace("Ejection timer running"); - this.switchAllBuckets(); - if (!this.latestConfig) { - return; - } - this.timerStartTime = ejectionTimestamp; - this.startTimer(this.latestConfig.getIntervalMs()); - this.runSuccessRateCheck(ejectionTimestamp); - this.runFailurePercentageCheck(ejectionTimestamp); - for (const [address, mapEntry] of this.entryMap.entries()) { - if (mapEntry.currentEjectionTimestamp === null) { - if (mapEntry.ejectionTimeMultiplier > 0) { - mapEntry.ejectionTimeMultiplier -= 1; - } - } else { - const baseEjectionTimeMs = this.latestConfig.getBaseEjectionTimeMs(); - const maxEjectionTimeMs = this.latestConfig.getMaxEjectionTimeMs(); - const returnTime = new Date(mapEntry.currentEjectionTimestamp.getTime()); - returnTime.setMilliseconds(returnTime.getMilliseconds() + Math.min(baseEjectionTimeMs * mapEntry.ejectionTimeMultiplier, Math.max(baseEjectionTimeMs, maxEjectionTimeMs))); - if (returnTime < /* @__PURE__ */ new Date()) { - trace("Unejecting " + address); - this.uneject(mapEntry); - } - } - } - } - updateAddressList(endpointList, lbConfig, options, resolutionNote) { - if (!(lbConfig instanceof OutlierDetectionLoadBalancingConfig)) { - return false; - } - trace("Received update with config: " + JSON.stringify(lbConfig.toJsonObject(), void 0, 2)); - if (endpointList.ok) { - for (const endpoint2 of endpointList.value) { - if (!this.entryMap.has(endpoint2)) { - trace("Adding map entry for " + (0, subchannel_address_1.endpointToString)(endpoint2)); - this.entryMap.set(endpoint2, { - counter: new CallCounter(), - currentEjectionTimestamp: null, - ejectionTimeMultiplier: 0, - subchannelWrappers: [] - }); - } - } - this.entryMap.deleteMissing(endpointList.value); - } - const childPolicy = lbConfig.getChildPolicy(); - this.childBalancer.updateAddressList(endpointList, childPolicy, options, resolutionNote); - if (lbConfig.getSuccessRateEjectionConfig() || lbConfig.getFailurePercentageEjectionConfig()) { - if (this.timerStartTime) { - trace("Previous timer existed. Replacing timer"); - clearTimeout(this.ejectionTimer); - const remainingDelay = lbConfig.getIntervalMs() - ((/* @__PURE__ */ new Date()).getTime() - this.timerStartTime.getTime()); - this.startTimer(remainingDelay); - } else { - trace("Starting new timer"); - this.timerStartTime = /* @__PURE__ */ new Date(); - this.startTimer(lbConfig.getIntervalMs()); - this.switchAllBuckets(); - } - } else { - trace("Counting disabled. Cancelling timer."); - this.timerStartTime = null; - clearTimeout(this.ejectionTimer); - for (const mapEntry of this.entryMap.values()) { - this.uneject(mapEntry); - mapEntry.ejectionTimeMultiplier = 0; - } - } - this.latestConfig = lbConfig; - return true; - } - exitIdle() { - this.childBalancer.exitIdle(); - } - resetBackoff() { - this.childBalancer.resetBackoff(); - } - destroy() { - clearTimeout(this.ejectionTimer); - this.childBalancer.destroy(); - } - getTypeName() { - return TYPE_NAME; - } - }; - exports2.OutlierDetectionLoadBalancer = OutlierDetectionLoadBalancer; - function setup() { - if (OUTLIER_DETECTION_ENABLED) { - (0, experimental_1.registerLoadBalancerType)(TYPE_NAME, OutlierDetectionLoadBalancer, OutlierDetectionLoadBalancingConfig); - } - } - } -}); - -// node_modules/@grpc/grpc-js/build/src/priority-queue.js -var require_priority_queue = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/priority-queue.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.PriorityQueue = void 0; - var top = 0; - var parent = (i) => Math.floor(i / 2); - var left = (i) => i * 2 + 1; - var right = (i) => i * 2 + 2; - var PriorityQueue = class { - /** - * - * @param comparator Returns true if the first argument should precede the - * second in the queue. Defaults to `(a, b) => a > b` - */ - constructor(comparator = (a, b) => a > b) { - this.comparator = comparator; - this.heap = []; - } - /** - * @returns The number of items currently in the queue - */ - size() { - return this.heap.length; - } - /** - * @returns True if there are no items in the queue, false otherwise - */ - isEmpty() { - return this.size() == 0; - } - /** - * Look at the front item that would be popped, without modifying the contents - * of the queue - * @returns The front item in the queue, or undefined if the queue is empty - */ - peek() { - return this.heap[top]; - } - /** - * Add the items to the queue - * @param values The items to add - * @returns The new size of the queue after adding the items - */ - push(...values) { - values.forEach((value) => { - this.heap.push(value); - this.siftUp(); - }); - return this.size(); - } - /** - * Remove the front item in the queue and return it - * @returns The front item in the queue, or undefined if the queue is empty - */ - pop() { - const poppedValue = this.peek(); - const bottom = this.size() - 1; - if (bottom > top) { - this.swap(top, bottom); - } - this.heap.pop(); - this.siftDown(); - return poppedValue; - } - /** - * Simultaneously remove the front item in the queue and add the provided - * item. - * @param value The item to add - * @returns The front item in the queue, or undefined if the queue is empty - */ - replace(value) { - const replacedValue = this.peek(); - this.heap[top] = value; - this.siftDown(); - return replacedValue; - } - greater(i, j) { - return this.comparator(this.heap[i], this.heap[j]); - } - swap(i, j) { - [this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]]; - } - siftUp() { - let node = this.size() - 1; - while (node > top && this.greater(node, parent(node))) { - this.swap(node, parent(node)); - node = parent(node); - } - } - siftDown() { - let node = top; - while (left(node) < this.size() && this.greater(left(node), node) || right(node) < this.size() && this.greater(right(node), node)) { - let maxChild = right(node) < this.size() && this.greater(right(node), left(node)) ? right(node) : left(node); - this.swap(node, maxChild); - node = maxChild; - } - } - }; - exports2.PriorityQueue = PriorityQueue; - } -}); - -// node_modules/@grpc/grpc-js/build/src/load-balancer-weighted-round-robin.js -var require_load_balancer_weighted_round_robin = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/load-balancer-weighted-round-robin.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.WeightedRoundRobinLoadBalancingConfig = void 0; - exports2.setup = setup; - var connectivity_state_1 = require_connectivity_state(); - var constants_1 = require_constants7(); - var duration_1 = require_duration(); - var load_balancer_1 = require_load_balancer(); - var load_balancer_pick_first_1 = require_load_balancer_pick_first(); - var logging = require_logging(); - var orca_1 = require_orca(); - var picker_1 = require_picker(); - var priority_queue_1 = require_priority_queue(); - var subchannel_address_1 = require_subchannel_address(); - var TRACER_NAME = "weighted_round_robin"; - function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); - } - var TYPE_NAME = "weighted_round_robin"; - var DEFAULT_OOB_REPORTING_PERIOD_MS = 1e4; - var DEFAULT_BLACKOUT_PERIOD_MS = 1e4; - var DEFAULT_WEIGHT_EXPIRATION_PERIOD_MS = 3 * 6e4; - var DEFAULT_WEIGHT_UPDATE_PERIOD_MS = 1e3; - var DEFAULT_ERROR_UTILIZATION_PENALTY = 1; - function validateFieldType(obj, fieldName, expectedType) { - if (fieldName in obj && obj[fieldName] !== void 0 && typeof obj[fieldName] !== expectedType) { - throw new Error(`weighted round robin config ${fieldName} parse error: expected ${expectedType}, got ${typeof obj[fieldName]}`); - } - } - function parseDurationField(obj, fieldName) { - if (fieldName in obj && obj[fieldName] !== void 0 && obj[fieldName] !== null) { - let durationObject; - if ((0, duration_1.isDuration)(obj[fieldName])) { - durationObject = obj[fieldName]; - } else if ((0, duration_1.isDurationMessage)(obj[fieldName])) { - durationObject = (0, duration_1.durationMessageToDuration)(obj[fieldName]); - } else if (typeof obj[fieldName] === "string") { - const parsedDuration = (0, duration_1.parseDuration)(obj[fieldName]); - if (!parsedDuration) { - throw new Error(`weighted round robin config ${fieldName}: failed to parse duration string ${obj[fieldName]}`); - } - durationObject = parsedDuration; - } else { - throw new Error(`weighted round robin config ${fieldName}: expected duration, got ${typeof obj[fieldName]}`); - } - return (0, duration_1.durationToMs)(durationObject); - } - return null; - } - var WeightedRoundRobinLoadBalancingConfig = class _WeightedRoundRobinLoadBalancingConfig { - constructor(enableOobLoadReport, oobLoadReportingPeriodMs, blackoutPeriodMs, weightExpirationPeriodMs, weightUpdatePeriodMs, errorUtilizationPenalty) { - this.enableOobLoadReport = enableOobLoadReport !== null && enableOobLoadReport !== void 0 ? enableOobLoadReport : false; - this.oobLoadReportingPeriodMs = oobLoadReportingPeriodMs !== null && oobLoadReportingPeriodMs !== void 0 ? oobLoadReportingPeriodMs : DEFAULT_OOB_REPORTING_PERIOD_MS; - this.blackoutPeriodMs = blackoutPeriodMs !== null && blackoutPeriodMs !== void 0 ? blackoutPeriodMs : DEFAULT_BLACKOUT_PERIOD_MS; - this.weightExpirationPeriodMs = weightExpirationPeriodMs !== null && weightExpirationPeriodMs !== void 0 ? weightExpirationPeriodMs : DEFAULT_WEIGHT_EXPIRATION_PERIOD_MS; - this.weightUpdatePeriodMs = Math.max(weightUpdatePeriodMs !== null && weightUpdatePeriodMs !== void 0 ? weightUpdatePeriodMs : DEFAULT_WEIGHT_UPDATE_PERIOD_MS, 100); - this.errorUtilizationPenalty = errorUtilizationPenalty !== null && errorUtilizationPenalty !== void 0 ? errorUtilizationPenalty : DEFAULT_ERROR_UTILIZATION_PENALTY; - } - getLoadBalancerName() { - return TYPE_NAME; - } - toJsonObject() { - return { - enable_oob_load_report: this.enableOobLoadReport, - oob_load_reporting_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.oobLoadReportingPeriodMs)), - blackout_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.blackoutPeriodMs)), - weight_expiration_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.weightExpirationPeriodMs)), - weight_update_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.weightUpdatePeriodMs)), - error_utilization_penalty: this.errorUtilizationPenalty - }; - } - static createFromJson(obj) { - validateFieldType(obj, "enable_oob_load_report", "boolean"); - validateFieldType(obj, "error_utilization_penalty", "number"); - if (obj.error_utilization_penalty < 0) { - throw new Error("weighted round robin config error_utilization_penalty < 0"); - } - return new _WeightedRoundRobinLoadBalancingConfig(obj.enable_oob_load_report, parseDurationField(obj, "oob_load_reporting_period"), parseDurationField(obj, "blackout_period"), parseDurationField(obj, "weight_expiration_period"), parseDurationField(obj, "weight_update_period"), obj.error_utilization_penalty); - } - getEnableOobLoadReport() { - return this.enableOobLoadReport; - } - getOobLoadReportingPeriodMs() { - return this.oobLoadReportingPeriodMs; - } - getBlackoutPeriodMs() { - return this.blackoutPeriodMs; - } - getWeightExpirationPeriodMs() { - return this.weightExpirationPeriodMs; - } - getWeightUpdatePeriodMs() { - return this.weightUpdatePeriodMs; - } - getErrorUtilizationPenalty() { - return this.errorUtilizationPenalty; - } - }; - exports2.WeightedRoundRobinLoadBalancingConfig = WeightedRoundRobinLoadBalancingConfig; - var WeightedRoundRobinPicker = class { - constructor(children, metricsHandler) { - this.metricsHandler = metricsHandler; - this.queue = new priority_queue_1.PriorityQueue((a, b) => a.deadline < b.deadline); - const positiveWeight = children.filter((picker) => picker.weight > 0); - let averageWeight; - if (positiveWeight.length < 2) { - averageWeight = 1; - } else { - let weightSum = 0; - for (const { weight } of positiveWeight) { - weightSum += weight; - } - averageWeight = weightSum / positiveWeight.length; - } - for (const child of children) { - const period = child.weight > 0 ? 1 / child.weight : averageWeight; - this.queue.push({ - endpointName: child.endpointName, - picker: child.picker, - period, - deadline: Math.random() * period - }); - } - } - pick(pickArgs) { - const entry = this.queue.pop(); - this.queue.push(Object.assign(Object.assign({}, entry), { deadline: entry.deadline + entry.period })); - const childPick = entry.picker.pick(pickArgs); - if (childPick.pickResultType === picker_1.PickResultType.COMPLETE) { - if (this.metricsHandler) { - return Object.assign(Object.assign({}, childPick), { onCallEnded: (0, orca_1.createMetricsReader)((loadReport) => this.metricsHandler(loadReport, entry.endpointName), childPick.onCallEnded) }); - } else { - const subchannelWrapper = childPick.subchannel; - return Object.assign(Object.assign({}, childPick), { subchannel: subchannelWrapper.getWrappedSubchannel() }); - } - } else { - return childPick; - } - } - }; - var WeightedRoundRobinLoadBalancer = class { - constructor(channelControlHelper) { - this.channelControlHelper = channelControlHelper; - this.latestConfig = null; - this.children = /* @__PURE__ */ new Map(); - this.currentState = connectivity_state_1.ConnectivityState.IDLE; - this.updatesPaused = false; - this.lastError = null; - this.weightUpdateTimer = null; - } - countChildrenWithState(state) { - let count = 0; - for (const entry of this.children.values()) { - if (entry.child.getConnectivityState() === state) { - count += 1; - } - } - return count; - } - updateWeight(entry, loadReport) { - var _a, _b; - const qps = loadReport.rps_fractional; - let utilization = loadReport.application_utilization; - if (utilization > 0 && qps > 0) { - utilization += loadReport.eps / qps * ((_b = (_a = this.latestConfig) === null || _a === void 0 ? void 0 : _a.getErrorUtilizationPenalty()) !== null && _b !== void 0 ? _b : 0); - } - const newWeight = utilization === 0 ? 0 : qps / utilization; - if (newWeight === 0) { - return; - } - const now = /* @__PURE__ */ new Date(); - if (entry.nonEmptySince === null) { - entry.nonEmptySince = now; - } - entry.lastUpdated = now; - entry.weight = newWeight; - } - getWeight(entry) { - if (!this.latestConfig) { - return 0; - } - const now = (/* @__PURE__ */ new Date()).getTime(); - if (now - entry.lastUpdated.getTime() >= this.latestConfig.getWeightExpirationPeriodMs()) { - entry.nonEmptySince = null; - return 0; - } - const blackoutPeriod = this.latestConfig.getBlackoutPeriodMs(); - if (blackoutPeriod > 0 && (entry.nonEmptySince === null || now - entry.nonEmptySince.getTime() < blackoutPeriod)) { - return 0; - } - return entry.weight; - } - calculateAndUpdateState() { - if (this.updatesPaused || !this.latestConfig) { - return; - } - if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.READY) > 0) { - const weightedPickers = []; - for (const [endpoint2, entry] of this.children) { - if (entry.child.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) { - continue; - } - weightedPickers.push({ - endpointName: endpoint2, - picker: entry.child.getPicker(), - weight: this.getWeight(entry) - }); - } - trace("Created picker with weights: " + weightedPickers.map((entry) => entry.endpointName + ":" + entry.weight).join(",")); - let metricsHandler; - if (!this.latestConfig.getEnableOobLoadReport()) { - metricsHandler = (loadReport, endpointName) => { - const childEntry = this.children.get(endpointName); - if (childEntry) { - this.updateWeight(childEntry, loadReport); - } - }; - } else { - metricsHandler = null; - } - this.updateState(connectivity_state_1.ConnectivityState.READY, new WeightedRoundRobinPicker(weightedPickers, metricsHandler), null); - } else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.CONNECTING) > 0) { - this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this), null); - } else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) > 0) { - const errorMessage = `weighted_round_robin: No connection established. Last error: ${this.lastError}`; - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ - details: errorMessage - }), errorMessage); - } else { - this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null); - } - for (const { child } of this.children.values()) { - if (child.getConnectivityState() === connectivity_state_1.ConnectivityState.IDLE) { - child.exitIdle(); - } - } - } - updateState(newState, picker, errorMessage) { - trace(connectivity_state_1.ConnectivityState[this.currentState] + " -> " + connectivity_state_1.ConnectivityState[newState]); - this.currentState = newState; - this.channelControlHelper.updateState(newState, picker, errorMessage); - } - updateAddressList(maybeEndpointList, lbConfig, options, resolutionNote) { - var _a, _b; - if (!(lbConfig instanceof WeightedRoundRobinLoadBalancingConfig)) { - return false; - } - if (!maybeEndpointList.ok) { - if (this.children.size === 0) { - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(maybeEndpointList.error), maybeEndpointList.error.details); - } - return true; - } - if (maybeEndpointList.value.length === 0) { - const errorMessage = `No addresses resolved. Resolution note: ${resolutionNote}`; - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ details: errorMessage }), errorMessage); - return false; - } - trace("Connect to endpoint list " + maybeEndpointList.value.map(subchannel_address_1.endpointToString)); - const now = /* @__PURE__ */ new Date(); - const seenEndpointNames = /* @__PURE__ */ new Set(); - this.updatesPaused = true; - this.latestConfig = lbConfig; - for (const endpoint2 of maybeEndpointList.value) { - const name = (0, subchannel_address_1.endpointToString)(endpoint2); - seenEndpointNames.add(name); - let entry = this.children.get(name); - if (!entry) { - entry = { - child: new load_balancer_pick_first_1.LeafLoadBalancer(endpoint2, (0, load_balancer_1.createChildChannelControlHelper)(this.channelControlHelper, { - updateState: (connectivityState, picker, errorMessage) => { - if (this.currentState === connectivity_state_1.ConnectivityState.READY && connectivityState !== connectivity_state_1.ConnectivityState.READY) { - this.channelControlHelper.requestReresolution(); - } - if (connectivityState === connectivity_state_1.ConnectivityState.READY) { - entry.nonEmptySince = null; - } - if (errorMessage) { - this.lastError = errorMessage; - } - this.calculateAndUpdateState(); - }, - createSubchannel: (subchannelAddress, subchannelArgs) => { - const subchannel = this.channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs); - if (entry === null || entry === void 0 ? void 0 : entry.oobMetricsListener) { - return new orca_1.OrcaOobMetricsSubchannelWrapper(subchannel, entry.oobMetricsListener, this.latestConfig.getOobLoadReportingPeriodMs()); - } else { - return subchannel; - } - } - }), options, resolutionNote), - lastUpdated: now, - nonEmptySince: null, - weight: 0, - oobMetricsListener: null - }; - this.children.set(name, entry); - } - if (lbConfig.getEnableOobLoadReport()) { - entry.oobMetricsListener = (loadReport) => { - this.updateWeight(entry, loadReport); - }; - } else { - entry.oobMetricsListener = null; - } - } - for (const [endpointName, entry] of this.children) { - if (seenEndpointNames.has(endpointName)) { - entry.child.startConnecting(); - } else { - entry.child.destroy(); - this.children.delete(endpointName); - } - } - this.updatesPaused = false; - this.calculateAndUpdateState(); - if (this.weightUpdateTimer) { - clearInterval(this.weightUpdateTimer); - } - this.weightUpdateTimer = (_b = (_a = setInterval(() => { - if (this.currentState === connectivity_state_1.ConnectivityState.READY) { - this.calculateAndUpdateState(); - } - }, lbConfig.getWeightUpdatePeriodMs())).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - return true; - } - exitIdle() { - } - resetBackoff() { - } - destroy() { - for (const entry of this.children.values()) { - entry.child.destroy(); - } - this.children.clear(); - if (this.weightUpdateTimer) { - clearInterval(this.weightUpdateTimer); - } - } - getTypeName() { - return TYPE_NAME; - } - }; - function setup() { - (0, load_balancer_1.registerLoadBalancerType)(TYPE_NAME, WeightedRoundRobinLoadBalancer, WeightedRoundRobinLoadBalancingConfig); - } - } -}); - -// node_modules/@grpc/grpc-js/build/src/index.js -var require_src4 = __commonJS({ - "node_modules/@grpc/grpc-js/build/src/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.experimental = exports2.ServerMetricRecorder = exports2.ServerInterceptingCall = exports2.ResponderBuilder = exports2.ServerListenerBuilder = exports2.addAdminServicesToServer = exports2.getChannelzHandlers = exports2.getChannelzServiceDefinition = exports2.InterceptorConfigurationError = exports2.InterceptingCall = exports2.RequesterBuilder = exports2.ListenerBuilder = exports2.StatusBuilder = exports2.getClientChannel = exports2.ServerCredentials = exports2.Server = exports2.setLogVerbosity = exports2.setLogger = exports2.load = exports2.loadObject = exports2.CallCredentials = exports2.ChannelCredentials = exports2.waitForClientReady = exports2.closeClient = exports2.Channel = exports2.makeGenericClientConstructor = exports2.makeClientConstructor = exports2.loadPackageDefinition = exports2.Client = exports2.compressionAlgorithms = exports2.propagate = exports2.connectivityState = exports2.status = exports2.logVerbosity = exports2.Metadata = exports2.credentials = void 0; - var call_credentials_1 = require_call_credentials(); - Object.defineProperty(exports2, "CallCredentials", { enumerable: true, get: function() { - return call_credentials_1.CallCredentials; - } }); - var channel_1 = require_channel(); - Object.defineProperty(exports2, "Channel", { enumerable: true, get: function() { - return channel_1.ChannelImplementation; - } }); - var compression_algorithms_1 = require_compression_algorithms(); - Object.defineProperty(exports2, "compressionAlgorithms", { enumerable: true, get: function() { - return compression_algorithms_1.CompressionAlgorithms; - } }); - var connectivity_state_1 = require_connectivity_state(); - Object.defineProperty(exports2, "connectivityState", { enumerable: true, get: function() { - return connectivity_state_1.ConnectivityState; - } }); - var channel_credentials_1 = require_channel_credentials(); - Object.defineProperty(exports2, "ChannelCredentials", { enumerable: true, get: function() { - return channel_credentials_1.ChannelCredentials; - } }); - var client_1 = require_client3(); - Object.defineProperty(exports2, "Client", { enumerable: true, get: function() { - return client_1.Client; - } }); - var constants_1 = require_constants7(); - Object.defineProperty(exports2, "logVerbosity", { enumerable: true, get: function() { - return constants_1.LogVerbosity; - } }); - Object.defineProperty(exports2, "status", { enumerable: true, get: function() { - return constants_1.Status; - } }); - Object.defineProperty(exports2, "propagate", { enumerable: true, get: function() { - return constants_1.Propagate; - } }); - var logging = require_logging(); - var make_client_1 = require_make_client(); - Object.defineProperty(exports2, "loadPackageDefinition", { enumerable: true, get: function() { - return make_client_1.loadPackageDefinition; - } }); - Object.defineProperty(exports2, "makeClientConstructor", { enumerable: true, get: function() { - return make_client_1.makeClientConstructor; - } }); - Object.defineProperty(exports2, "makeGenericClientConstructor", { enumerable: true, get: function() { - return make_client_1.makeClientConstructor; - } }); - var metadata_1 = require_metadata(); - Object.defineProperty(exports2, "Metadata", { enumerable: true, get: function() { - return metadata_1.Metadata; - } }); - var server_1 = require_server2(); - Object.defineProperty(exports2, "Server", { enumerable: true, get: function() { - return server_1.Server; - } }); - var server_credentials_1 = require_server_credentials(); - Object.defineProperty(exports2, "ServerCredentials", { enumerable: true, get: function() { - return server_credentials_1.ServerCredentials; - } }); - var status_builder_1 = require_status_builder(); - Object.defineProperty(exports2, "StatusBuilder", { enumerable: true, get: function() { - return status_builder_1.StatusBuilder; - } }); - exports2.credentials = { - /** - * Combine a ChannelCredentials with any number of CallCredentials into a - * single ChannelCredentials object. - * @param channelCredentials The ChannelCredentials object. - * @param callCredentials Any number of CallCredentials objects. - * @return The resulting ChannelCredentials object. - */ - combineChannelCredentials: (channelCredentials, ...callCredentials) => { - return callCredentials.reduce((acc, other) => acc.compose(other), channelCredentials); - }, - /** - * Combine any number of CallCredentials into a single CallCredentials - * object. - * @param first The first CallCredentials object. - * @param additional Any number of additional CallCredentials objects. - * @return The resulting CallCredentials object. - */ - combineCallCredentials: (first, ...additional) => { - return additional.reduce((acc, other) => acc.compose(other), first); - }, - // from channel-credentials.ts - createInsecure: channel_credentials_1.ChannelCredentials.createInsecure, - createSsl: channel_credentials_1.ChannelCredentials.createSsl, - createFromSecureContext: channel_credentials_1.ChannelCredentials.createFromSecureContext, - // from call-credentials.ts - createFromMetadataGenerator: call_credentials_1.CallCredentials.createFromMetadataGenerator, - createFromGoogleCredential: call_credentials_1.CallCredentials.createFromGoogleCredential, - createEmpty: call_credentials_1.CallCredentials.createEmpty - }; - var closeClient = (client) => client.close(); - exports2.closeClient = closeClient; - var waitForClientReady = (client, deadline, callback) => client.waitForReady(deadline, callback); - exports2.waitForClientReady = waitForClientReady; - var loadObject = (value, options) => { - throw new Error("Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead"); - }; - exports2.loadObject = loadObject; - var load = (filename, format, options) => { - throw new Error("Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead"); - }; - exports2.load = load; - var setLogger = (logger) => { - logging.setLogger(logger); - }; - exports2.setLogger = setLogger; - var setLogVerbosity = (verbosity) => { - logging.setLoggerVerbosity(verbosity); - }; - exports2.setLogVerbosity = setLogVerbosity; - var getClientChannel = (client) => { - return client_1.Client.prototype.getChannel.call(client); - }; - exports2.getClientChannel = getClientChannel; - var client_interceptors_1 = require_client_interceptors(); - Object.defineProperty(exports2, "ListenerBuilder", { enumerable: true, get: function() { - return client_interceptors_1.ListenerBuilder; - } }); - Object.defineProperty(exports2, "RequesterBuilder", { enumerable: true, get: function() { - return client_interceptors_1.RequesterBuilder; - } }); - Object.defineProperty(exports2, "InterceptingCall", { enumerable: true, get: function() { - return client_interceptors_1.InterceptingCall; - } }); - Object.defineProperty(exports2, "InterceptorConfigurationError", { enumerable: true, get: function() { - return client_interceptors_1.InterceptorConfigurationError; - } }); - var channelz_1 = require_channelz(); - Object.defineProperty(exports2, "getChannelzServiceDefinition", { enumerable: true, get: function() { - return channelz_1.getChannelzServiceDefinition; - } }); - Object.defineProperty(exports2, "getChannelzHandlers", { enumerable: true, get: function() { - return channelz_1.getChannelzHandlers; - } }); - var admin_1 = require_admin(); - Object.defineProperty(exports2, "addAdminServicesToServer", { enumerable: true, get: function() { - return admin_1.addAdminServicesToServer; - } }); - var server_interceptors_1 = require_server_interceptors(); - Object.defineProperty(exports2, "ServerListenerBuilder", { enumerable: true, get: function() { - return server_interceptors_1.ServerListenerBuilder; - } }); - Object.defineProperty(exports2, "ResponderBuilder", { enumerable: true, get: function() { - return server_interceptors_1.ResponderBuilder; - } }); - Object.defineProperty(exports2, "ServerInterceptingCall", { enumerable: true, get: function() { - return server_interceptors_1.ServerInterceptingCall; - } }); - var orca_1 = require_orca(); - Object.defineProperty(exports2, "ServerMetricRecorder", { enumerable: true, get: function() { - return orca_1.ServerMetricRecorder; - } }); - var experimental = require_experimental(); - exports2.experimental = experimental; - var resolver_dns = require_resolver_dns(); - var resolver_uds = require_resolver_uds(); - var resolver_ip = require_resolver_ip(); - var load_balancer_pick_first = require_load_balancer_pick_first(); - var load_balancer_round_robin = require_load_balancer_round_robin(); - var load_balancer_outlier_detection = require_load_balancer_outlier_detection(); - var load_balancer_weighted_round_robin = require_load_balancer_weighted_round_robin(); - var channelz = require_channelz(); - (() => { - resolver_dns.setup(); - resolver_uds.setup(); - resolver_ip.setup(); - load_balancer_pick_first.setup(); - load_balancer_round_robin.setup(); - load_balancer_outlier_detection.setup(); - load_balancer_weighted_round_robin.setup(); - channelz.setup(); - })(); - } -}); - -// node_modules/@grpc/proto-loader/build/src/util.js -var require_util12 = __commonJS({ - "node_modules/@grpc/proto-loader/build/src/util.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.addCommonProtos = exports2.loadProtosWithOptionsSync = exports2.loadProtosWithOptions = void 0; - var fs3 = require("fs"); - var path = require("path"); - var Protobuf = require_protobufjs(); - function addIncludePathResolver(root, includePaths) { - const originalResolvePath = root.resolvePath; - root.resolvePath = (origin, target) => { - if (path.isAbsolute(target)) { - return target; - } - for (const directory of includePaths) { - const fullPath = path.join(directory, target); - try { - fs3.accessSync(fullPath, fs3.constants.R_OK); - return fullPath; - } catch (err) { - continue; - } - } - process.emitWarning(`${target} not found in any of the include paths ${includePaths}`); - return originalResolvePath(origin, target); - }; - } - async function loadProtosWithOptions(filename, options) { - const root = new Protobuf.Root(); - options = options || {}; - if (!!options.includeDirs) { - if (!Array.isArray(options.includeDirs)) { - return Promise.reject(new Error("The includeDirs option must be an array")); - } - addIncludePathResolver(root, options.includeDirs); - } - const loadedRoot = await root.load(filename, options); - loadedRoot.resolveAll(); - return loadedRoot; - } - exports2.loadProtosWithOptions = loadProtosWithOptions; - function loadProtosWithOptionsSync(filename, options) { - const root = new Protobuf.Root(); - options = options || {}; - if (!!options.includeDirs) { - if (!Array.isArray(options.includeDirs)) { - throw new Error("The includeDirs option must be an array"); - } - addIncludePathResolver(root, options.includeDirs); - } - const loadedRoot = root.loadSync(filename, options); - loadedRoot.resolveAll(); - return loadedRoot; - } - exports2.loadProtosWithOptionsSync = loadProtosWithOptionsSync; - function addCommonProtos() { - const apiDescriptor = require_api2(); - const descriptorDescriptor = require_descriptor(); - const sourceContextDescriptor = require_source_context(); - const typeDescriptor = require_type2(); - Protobuf.common("api", apiDescriptor.nested.google.nested.protobuf.nested); - Protobuf.common("descriptor", descriptorDescriptor.nested.google.nested.protobuf.nested); - Protobuf.common("source_context", sourceContextDescriptor.nested.google.nested.protobuf.nested); - Protobuf.common("type", typeDescriptor.nested.google.nested.protobuf.nested); - } - exports2.addCommonProtos = addCommonProtos; - } -}); - -// node_modules/@grpc/proto-loader/build/src/index.js -var require_src5 = __commonJS({ - "node_modules/@grpc/proto-loader/build/src/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.loadFileDescriptorSetFromObject = exports2.loadFileDescriptorSetFromBuffer = exports2.fromJSON = exports2.loadSync = exports2.load = exports2.IdempotencyLevel = exports2.isAnyExtension = exports2.Long = void 0; - var camelCase = require_lodash(); - var Protobuf = require_protobufjs(); - var descriptor = require_descriptor2(); - var util_1 = require_util12(); - var Long = require_umd(); - exports2.Long = Long; - function isAnyExtension(obj) { - return "@type" in obj && typeof obj["@type"] === "string"; - } - exports2.isAnyExtension = isAnyExtension; - var IdempotencyLevel; - (function(IdempotencyLevel2) { - IdempotencyLevel2["IDEMPOTENCY_UNKNOWN"] = "IDEMPOTENCY_UNKNOWN"; - IdempotencyLevel2["NO_SIDE_EFFECTS"] = "NO_SIDE_EFFECTS"; - IdempotencyLevel2["IDEMPOTENT"] = "IDEMPOTENT"; - })(IdempotencyLevel = exports2.IdempotencyLevel || (exports2.IdempotencyLevel = {})); - var descriptorOptions = { - longs: String, - enums: String, - bytes: String, - defaults: true, - oneofs: true, - json: true - }; - function joinName(baseName, name) { - if (baseName === "") { - return name; - } else { - return baseName + "." + name; - } - } - function isHandledReflectionObject(obj) { - return obj instanceof Protobuf.Service || obj instanceof Protobuf.Type || obj instanceof Protobuf.Enum; - } - function isNamespaceBase(obj) { - return obj instanceof Protobuf.Namespace || obj instanceof Protobuf.Root; - } - function getAllHandledReflectionObjects(obj, parentName) { - const objName = joinName(parentName, obj.name); - if (isHandledReflectionObject(obj)) { - return [[objName, obj]]; - } else { - if (isNamespaceBase(obj) && typeof obj.nested !== "undefined") { - return Object.keys(obj.nested).map((name) => { - return getAllHandledReflectionObjects(obj.nested[name], objName); - }).reduce((accumulator, currentValue) => accumulator.concat(currentValue), []); - } - } - return []; - } - function createDeserializer(cls, options) { - return function deserialize(argBuf) { - return cls.toObject(cls.decode(argBuf), options); - }; - } - function createSerializer(cls) { - return function serialize(arg) { - if (Array.isArray(arg)) { - throw new Error(`Failed to serialize message: expected object with ${cls.name} structure, got array instead`); - } - const message = cls.fromObject(arg); - return cls.encode(message).finish(); - }; - } - function mapMethodOptions(options) { - return (options || []).reduce((obj, item) => { - for (const [key, value] of Object.entries(item)) { - switch (key) { - case "uninterpreted_option": - obj.uninterpreted_option.push(item.uninterpreted_option); - break; - default: - obj[key] = value; - } - } - return obj; - }, { - deprecated: false, - idempotency_level: IdempotencyLevel.IDEMPOTENCY_UNKNOWN, - uninterpreted_option: [] - }); - } - function createMethodDefinition(method, serviceName, options, fileDescriptors) { - const requestType = method.resolvedRequestType; - const responseType = method.resolvedResponseType; - return { - path: "/" + serviceName + "/" + method.name, - requestStream: !!method.requestStream, - responseStream: !!method.responseStream, - requestSerialize: createSerializer(requestType), - requestDeserialize: createDeserializer(requestType, options), - responseSerialize: createSerializer(responseType), - responseDeserialize: createDeserializer(responseType, options), - // TODO(murgatroid99): Find a better way to handle this - originalName: camelCase(method.name), - requestType: createMessageDefinition(requestType, fileDescriptors), - responseType: createMessageDefinition(responseType, fileDescriptors), - options: mapMethodOptions(method.parsedOptions) - }; - } - function createServiceDefinition(service, name, options, fileDescriptors) { - const def = {}; - for (const method of service.methodsArray) { - def[method.name] = createMethodDefinition(method, name, options, fileDescriptors); - } - return def; - } - function createMessageDefinition(message, fileDescriptors) { - const messageDescriptor = message.toDescriptor("proto3"); - return { - format: "Protocol Buffer 3 DescriptorProto", - type: messageDescriptor.$type.toObject(messageDescriptor, descriptorOptions), - fileDescriptorProtos: fileDescriptors - }; - } - function createEnumDefinition(enumType, fileDescriptors) { - const enumDescriptor = enumType.toDescriptor("proto3"); - return { - format: "Protocol Buffer 3 EnumDescriptorProto", - type: enumDescriptor.$type.toObject(enumDescriptor, descriptorOptions), - fileDescriptorProtos: fileDescriptors - }; - } - function createDefinition(obj, name, options, fileDescriptors) { - if (obj instanceof Protobuf.Service) { - return createServiceDefinition(obj, name, options, fileDescriptors); - } else if (obj instanceof Protobuf.Type) { - return createMessageDefinition(obj, fileDescriptors); - } else if (obj instanceof Protobuf.Enum) { - return createEnumDefinition(obj, fileDescriptors); - } else { - throw new Error("Type mismatch in reflection object handling"); - } - } - function createPackageDefinition(root, options) { - const def = {}; - root.resolveAll(); - const descriptorList = root.toDescriptor("proto3").file; - const bufferList = descriptorList.map((value) => Buffer.from(descriptor.FileDescriptorProto.encode(value).finish())); - for (const [name, obj] of getAllHandledReflectionObjects(root, "")) { - def[name] = createDefinition(obj, name, options, bufferList); - } - return def; - } - function createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options) { - options = options || {}; - const root = Protobuf.Root.fromDescriptor(decodedDescriptorSet); - root.resolveAll(); - return createPackageDefinition(root, options); - } - function load(filename, options) { - return (0, util_1.loadProtosWithOptions)(filename, options).then((loadedRoot) => { - return createPackageDefinition(loadedRoot, options); - }); - } - exports2.load = load; - function loadSync(filename, options) { - const loadedRoot = (0, util_1.loadProtosWithOptionsSync)(filename, options); - return createPackageDefinition(loadedRoot, options); - } - exports2.loadSync = loadSync; - function fromJSON(json, options) { - options = options || {}; - const loadedRoot = Protobuf.Root.fromJSON(json); - loadedRoot.resolveAll(); - return createPackageDefinition(loadedRoot, options); - } - exports2.fromJSON = fromJSON; - function loadFileDescriptorSetFromBuffer(descriptorSet, options) { - const decodedDescriptorSet = descriptor.FileDescriptorSet.decode(descriptorSet); - return createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options); - } - exports2.loadFileDescriptorSetFromBuffer = loadFileDescriptorSetFromBuffer; - function loadFileDescriptorSetFromObject(descriptorSet, options) { - const decodedDescriptorSet = descriptor.FileDescriptorSet.fromObject(descriptorSet); - return createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options); - } - exports2.loadFileDescriptorSetFromObject = loadFileDescriptorSetFromObject; - (0, util_1.addCommonProtos)(); - } -}); - -// node_modules/dockerode/lib/session.js -var require_session = __commonJS({ - "node_modules/dockerode/lib/session.js"(exports2, module2) { - var grpc = require_src4(); - var protoLoader = require_src5(); - var path = require("path"); - var crypto = require("crypto"); - function withSession(docker, auth2, handler2) { - const sessionId = crypto.randomUUID(); - const opts = { - method: "POST", - path: "/session", - hijack: true, - headers: { - Upgrade: "h2c", - "X-Docker-Expose-Session-Uuid": sessionId, - "X-Docker-Expose-Session-Name": "testcontainers" - }, - statusCodes: { - 200: true, - 500: "server error" - } - }; - docker.modem.dial(opts, function(err, socket) { - if (err) { - return handler2(err, null, () => void 0); - } - const server = new grpc.Server(); - const creds = grpc.ServerCredentials.createInsecure(); - const injector = server.createConnectionInjector(creds); - injector.injectConnection(socket); - const pkg = protoLoader.loadSync( - path.resolve(__dirname, "proto", "auth.proto") - ); - const service = grpc.loadPackageDefinition(pkg); - server.addService(service.moby.filesync.v1.Auth.service, { - Credentials({ request: request2 }, callback) { - if (auth2) { - callback(null, { - Username: auth2.username, - Secret: auth2.password - }); - } else { - callback(null, {}); - } - } - }); - function done() { - server.forceShutdown(); - socket.end(); - } - handler2(null, sessionId, done); - }); - } - module2.exports = withSession; - } -}); - -// node_modules/dockerode/lib/buildkit.js -var require_buildkit = __commonJS({ - "node_modules/dockerode/lib/buildkit.js"(exports2, module2) { - var protobuf = require_protobufjs(); - var path = require("path"); - var BUILDKIT_TRACE_ID = "moby.buildkit.trace"; - var BUILDKIT_IMAGE_ID = "moby.image.id"; - var PROTO_TYPE = "moby.buildkit.v1.StatusResponse"; - var ENCODING_UTF8 = "utf8"; - var ENCODING_BASE64 = "base64"; - var StatusResponse; - function loadProto() { - if (StatusResponse) return StatusResponse; - var root = protobuf.loadSync( - path.resolve(__dirname, "proto", "buildkit_status.proto") - ); - StatusResponse = root.lookupType(PROTO_TYPE); - return StatusResponse; - } - function decodeBuildKitStatus(base64Data) { - var StatusResponse2 = loadProto(); - if (!base64Data || base64Data.length === 0) { - return { - vertexes: [], - statuses: [], - logs: [], - warnings: [] - }; - } - var buffer = Buffer.from(base64Data, ENCODING_BASE64); - var message = StatusResponse2.decode(buffer); - return StatusResponse2.toObject(message, { - longs: String, - enums: String, - bytes: String, - defaults: true - }); - } - function formatBuildKitStatus(status) { - var lines = []; - if (status.vertexes && status.vertexes.length > 0) { - status.vertexes.forEach(function(vertex) { - if (vertex.name && vertex.started && !vertex.completed) { - lines.push("[" + vertex.digest.substring(0, 12) + "] " + vertex.name); - } - if (vertex.error) { - lines.push("ERROR: " + vertex.error); - } - if (vertex.completed && vertex.cached) { - lines.push("CACHED: " + vertex.name); - } - }); - } - if (status.logs && status.logs.length > 0) { - status.logs.forEach(function(log) { - var msg = Buffer.from(log.msg).toString(ENCODING_UTF8); - if (msg.trim()) { - lines.push(msg.trimEnd()); - } - }); - } - if (status.statuses && status.statuses.length > 0) { - status.statuses.forEach(function(s) { - if (s.name && s.total > 0) { - var percent = Math.floor(s.current / s.total * 100); - lines.push(s.name + ": " + percent + "% (" + s.current + "/" + s.total + ")"); - } - }); - } - if (status.warnings && status.warnings.length > 0) { - status.warnings.forEach(function(warning5) { - var msg = Buffer.from(warning5.short).toString(ENCODING_UTF8); - lines.push("WARNING: " + msg); - }); - } - return lines; - } - function parseBuildKitLine(line) { - try { - var json = JSON.parse(line); - if (json.id === BUILDKIT_TRACE_ID && json.aux !== void 0) { - var status = decodeBuildKitStatus(json.aux); - var logs = formatBuildKitStatus(status); - return { - isBuildKit: true, - logs, - raw: status - }; - } - if (json.id === BUILDKIT_IMAGE_ID && json.aux && json.aux.ID) { - return { - isBuildKit: true, - logs: ["Built image: " + json.aux.ID], - raw: json.aux - }; - } - return { - isBuildKit: false, - logs: [], - raw: json - }; - } catch (e) { - return { - isBuildKit: false, - logs: [], - raw: null, - error: e.message - }; - } - } - function followProgress(stream2, onFinished, onProgress) { - var buffer = ""; - var output = []; - var finished = false; - stream2.on("data", onStreamEvent); - stream2.on("error", onStreamError); - stream2.on("end", onStreamEnd); - stream2.on("close", onStreamEnd); - function onStreamEvent(data) { - buffer += data.toString(); - var lines = buffer.split("\n"); - buffer = lines.pop(); - lines.forEach(function(line) { - if (!line.trim()) return; - processLine(line); - }); - } - function processLine(line) { - try { - var result = parseBuildKitLine(line); - if (result.isBuildKit) { - result.logs.forEach(function(log) { - var event = { stream: log + "\n" }; - output.push(event); - if (onProgress) onProgress(event); - }); - } else if (result.raw) { - output.push(result.raw); - if (onProgress) onProgress(result.raw); - } - } catch (e) { - try { - var json = JSON.parse(line); - output.push(json); - if (onProgress) onProgress(json); - } catch (e2) { - } - } - } - function onStreamError(err) { - finished = true; - stream2.removeListener("data", onStreamEvent); - stream2.removeListener("error", onStreamError); - stream2.removeListener("end", onStreamEnd); - stream2.removeListener("close", onStreamEnd); - if (onFinished) onFinished(err, output); - } - function onStreamEnd() { - if (finished) return; - finished = true; - if (buffer.trim()) { - processLine(buffer); - } - stream2.removeListener("data", onStreamEvent); - stream2.removeListener("error", onStreamError); - stream2.removeListener("end", onStreamEnd); - stream2.removeListener("close", onStreamEnd); - if (onFinished) onFinished(null, output); - } - } - module2.exports = { - followProgress - }; - } -}); - -// node_modules/dockerode/lib/docker.js -var require_docker = __commonJS({ - "node_modules/dockerode/lib/docker.js"(exports2, module2) { - var EventEmitter = require("events").EventEmitter; - var Modem = require_modem(); - var Container2 = require_container(); - var Image = require_image(); - var Volume = require_volume(); - var Network = require_network(); - var Service = require_service(); - var Plugin = require_plugin(); - var Secret = require_secret(); - var Config = require_config(); - var Task = require_task(); - var Node = require_node3(); - var Exec = require_exec2(); - var util = require_util9(); - var withSession = require_session(); - var extend = util.extend; - var Docker3 = function(opts) { - if (!(this instanceof Docker3)) return new Docker3(opts); - var plibrary = global.Promise; - if (opts && opts.Promise) { - plibrary = opts.Promise; - if (Object.keys(opts).length === 1) { - opts = void 0; - } - } - if (opts && opts.modem) { - this.modem = opts.modem; - } else { - this.modem = new Modem(opts); - } - this.modem.Promise = plibrary; - }; - Docker3.prototype.createContainer = function(opts, callback) { - var self2 = this; - var optsf = { - path: "/containers/create?", - method: "POST", - options: opts, - authconfig: opts.authconfig, - abortSignal: opts.abortSignal, - statusCodes: { - 200: true, - // unofficial, but proxies may return it - 201: true, - 400: "bad parameter", - 404: "no such container", - 406: "impossible to attach", - 500: "server error" - } - }; - delete opts.authconfig; - if (callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(self2.getContainer(data.Id)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return callback(err, data); - callback(err, self2.getContainer(data.Id)); - }); - } - }; - Docker3.prototype.createImage = function(auth2, opts, callback) { - var self2 = this; - if (!callback && typeof opts === "function") { - callback = opts; - opts = auth2; - auth2 = opts.authconfig || void 0; - } else if (!callback && !opts) { - opts = auth2; - auth2 = opts.authconfig; - } - var optsf = { - path: "/images/create?", - method: "POST", - options: opts, - authconfig: auth2, - abortSignal: opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 500: "server error" - } - }; - if (callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } - }; - Docker3.prototype.loadImage = function(file, opts, callback) { - var self2 = this; - if (!callback && typeof opts === "function") { - callback = opts; - opts = null; - } - var optsf = { - path: "/images/load?", - method: "POST", - options: opts, - file, - abortSignal: opts && opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 500: "server error" - } - }; - if (callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } - }; - Docker3.prototype.importImage = function(file, opts, callback) { - var self2 = this; - if (!callback && typeof opts === "function") { - callback = opts; - opts = void 0; - } - if (!opts) - opts = {}; - opts.fromSrc = "-"; - var optsf = { - path: "/images/create?", - method: "POST", - options: opts, - file, - abortSignal: opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 500: "server error" - } - }; - if (callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } - }; - Docker3.prototype.checkAuth = function(opts, callback) { - var self2 = this; - var optsf = { - path: "/auth", - method: "POST", - options: opts, - abortSignal: opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 500: "server error" - } - }; - if (callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } - }; - Docker3.prototype.buildImage = function(file, opts, callback) { - var self2 = this; - if (!callback && typeof opts === "function") { - callback = opts; - opts = null; - } - var optsf = { - path: "/build?", - method: "POST", - file: void 0, - options: opts, - abortSignal: opts && opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 500: "server error" - } - }; - if (opts) { - if (opts.registryconfig) { - optsf.registryconfig = optsf.options.registryconfig; - delete optsf.options.registryconfig; - } - if (opts.authconfig) { - optsf.authconfig = optsf.options.authconfig; - delete optsf.options.authconfig; - } - if (opts.cachefrom && Array.isArray(opts.cachefrom)) { - optsf.options.cachefrom = JSON.stringify(opts.cachefrom); - } - } - function dial(callback2) { - util.prepareBuildContext(file, (ctx) => { - optsf.file = ctx; - self2.modem.dial(optsf, callback2); - }); - } - function dialWithSession(callback2) { - if (opts?.version === "2") { - withSession(self2, optsf.authconfig, (err, sessionId, done) => { - if (err) { - return callback2(err); - } - optsf.options.session = sessionId; - dial((err2, data) => { - callback2(err2, data); - if (data) { - data.on("end", done); - } - }); - }); - } else { - dial(callback2); - } - } - if (callback === void 0) { - return new self2.modem.Promise(function(resolve, reject) { - dialWithSession(function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - dialWithSession(callback); - } - }; - Docker3.prototype.followProgress = function(stream2, onFinished, onProgress) { - var buildkit = require_buildkit(); - return buildkit.followProgress(stream2, onFinished, onProgress); - }; - Docker3.prototype.getContainer = function(id) { - return new Container2(this.modem, id); - }; - Docker3.prototype.getImage = function(name) { - return new Image(this.modem, name); - }; - Docker3.prototype.getVolume = function(name) { - return new Volume(this.modem, name); - }; - Docker3.prototype.getPlugin = function(name, remote) { - return new Plugin(this.modem, name, remote); - }; - Docker3.prototype.getService = function(id) { - return new Service(this.modem, id); - }; - Docker3.prototype.getTask = function(id) { - return new Task(this.modem, id); - }; - Docker3.prototype.getNode = function(id) { - return new Node(this.modem, id); - }; - Docker3.prototype.getNetwork = function(id) { - return new Network(this.modem, id); - }; - Docker3.prototype.getSecret = function(id) { - return new Secret(this.modem, id); - }; - Docker3.prototype.getConfig = function(id) { - return new Config(this.modem, id); - }; - Docker3.prototype.getExec = function(id) { - return new Exec(this.modem, id); - }; - Docker3.prototype.listContainers = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/containers/json?", - method: "GET", - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: "bad parameter", - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Docker3.prototype.listImages = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/images/json?", - method: "GET", - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: "bad parameter", - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Docker3.prototype.getImages = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/images/get?", - method: "GET", - options: args.opts, - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 400: "bad parameter", - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Docker3.prototype.listServices = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/services?", - method: "GET", - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Docker3.prototype.listNodes = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/nodes?", - method: "GET", - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: "bad parameter", - 404: "no such node", - 500: "server error", - 503: "node is not part of a swarm" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Docker3.prototype.listTasks = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/tasks?", - method: "GET", - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Docker3.prototype.createSecret = function(opts, callback) { - var args = util.processArgs(opts, callback); - var self2 = this; - var optsf = { - path: "/secrets/create?", - method: "POST", - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - // unofficial, but proxies may return it - 201: true, - 406: "server error or node is not part of a swarm", - 409: "name conflicts with an existing object", - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(self2.getSecret(data.ID)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, self2.getSecret(data.ID)); - }); - } - }; - Docker3.prototype.createConfig = function(opts, callback) { - var args = util.processArgs(opts, callback); - var self2 = this; - var optsf = { - path: "/configs/create?", - method: "POST", - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - // unofficial, but proxies may return it - 201: true, - 406: "server error or node is not part of a swarm", - 409: "name conflicts with an existing object", - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(self2.getConfig(data.ID)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, self2.getConfig(data.ID)); - }); - } - }; - Docker3.prototype.listSecrets = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/secrets?", - method: "GET", - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Docker3.prototype.listConfigs = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/configs?", - method: "GET", - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Docker3.prototype.createPlugin = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/plugins/create?", - method: "POST", - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - // unofficial, but proxies may return it - 204: true, - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(self2.getPlugin(args.opts.name)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, self2.getPlugin(args.opts.name)); - }); - } - }; - Docker3.prototype.listPlugins = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/plugins?", - method: "GET", - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Docker3.prototype.pruneImages = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/images/prune?", - method: "POST", - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Docker3.prototype.pruneBuilder = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/build/prune", - method: "POST", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Docker3.prototype.pruneContainers = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/containers/prune?", - method: "POST", - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Docker3.prototype.pruneVolumes = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/volumes/prune?", - method: "POST", - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Docker3.prototype.pruneNetworks = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/networks/prune?", - method: "POST", - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Docker3.prototype.createVolume = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/volumes/create?", - method: "POST", - allowEmpty: true, - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - // unofficial, but proxies may return it - 201: true, - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(self2.getVolume(data.Name)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, self2.getVolume(data.Name)); - }); - } - }; - Docker3.prototype.createService = function(auth2, opts, callback) { - if (!callback && typeof opts === "function") { - callback = opts; - opts = auth2; - auth2 = opts.authconfig || void 0; - } else if (!opts && !callback) { - opts = auth2; - } - var self2 = this; - var optsf = { - path: "/services/create", - method: "POST", - options: opts, - authconfig: auth2, - abortSignal: opts && opts.abortSignal, - statusCodes: { - 200: true, - 201: true, - 500: "server error" - } - }; - if (callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(self2.getService(data.ID || data.Id)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return callback(err, data); - callback(err, self2.getService(data.ID || data.Id)); - }); - } - }; - Docker3.prototype.listVolumes = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/volumes?", - method: "GET", - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: "bad parameter", - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Docker3.prototype.createNetwork = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/networks/create?", - method: "POST", - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - // unofficial, but proxies may return it - 201: true, - 404: "driver not found", - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(self2.getNetwork(data.Id)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, self2.getNetwork(data.Id)); - }); - } - }; - Docker3.prototype.listNetworks = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/networks?", - method: "GET", - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: "bad parameter", - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Docker3.prototype.searchImages = function(opts, callback) { - var self2 = this; - var optsf = { - path: "/images/search?", - method: "GET", - options: opts, - authconfig: opts.authconfig, - abortSignal: opts.abortSignal, - statusCodes: { - 200: true, - 500: "server error" - } - }; - if (callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } - }; - Docker3.prototype.info = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var opts = { - path: "/info", - method: "GET", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(opts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(opts, function(err, data) { - args.callback(err, data); - }); - } - }; - Docker3.prototype.version = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var opts = { - path: "/version", - method: "GET", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(opts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(opts, function(err, data) { - args.callback(err, data); - }); - } - }; - Docker3.prototype.ping = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/_ping", - method: "GET", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Docker3.prototype.df = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/system/df", - method: "GET", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Docker3.prototype.getEvents = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/events?", - method: "GET", - options: args.opts, - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Docker3.prototype.pull = function(repoTag, opts, callback, auth2) { - var args = util.processArgs(opts, callback); - var imageSrc = util.parseRepositoryTag(repoTag); - args.opts.fromImage = imageSrc.repository; - args.opts.tag = imageSrc.tag || "latest"; - var argsf = [args.opts, args.callback]; - if (auth2) { - argsf = [auth2, args.opts, args.callback]; - } - return this.createImage.apply(this, argsf); - }; - Docker3.prototype.pullAll = function(repoTag, opts, callback, auth2) { - var args = util.processArgs(opts, callback); - var imageSrc = util.parseRepositoryTag(repoTag); - args.opts.fromImage = imageSrc.repository; - var argsf = [args.opts, args.callback]; - if (auth2) { - argsf = [auth2, args.opts, args.callback]; - } - return this.createImage.apply(this, argsf); - }; - Docker3.prototype.run = function(image, cmd, streamo, createOptions, startOptions, callback) { - if (typeof arguments[arguments.length - 1] === "function") { - return this.runCallback(image, cmd, streamo, createOptions, startOptions, callback); - } else { - return this.runPromise(image, cmd, streamo, createOptions, startOptions); - } - }; - Docker3.prototype.runCallback = function(image, cmd, streamo, createOptions, startOptions, callback) { - if (!callback && typeof createOptions === "function") { - callback = createOptions; - createOptions = {}; - startOptions = {}; - } else if (!callback && typeof startOptions === "function") { - callback = startOptions; - startOptions = {}; - } - var hub = new EventEmitter(); - function handler2(err, container) { - if (err) return callback(err, null, container); - hub.emit("container", container); - container.attach({ - stream: true, - stdout: true, - stderr: true - }, function handler3(err2, stream2) { - if (err2) return callback(err2, null, container); - hub.emit("stream", stream2); - if (streamo) { - if (streamo instanceof Array) { - stream2.on("end", function() { - try { - streamo[0].end(); - } catch (e) { - } - try { - streamo[1].end(); - } catch (e) { - } - }); - container.modem.demuxStream(stream2, streamo[0], streamo[1]); - } else { - stream2.setEncoding("utf8"); - stream2.pipe(streamo, { - end: true - }); - } - } - container.start(startOptions, function(err3, data) { - if (err3) return callback(err3, data, container); - hub.emit("start", container); - container.wait(function(err4, data2) { - hub.emit("data", data2); - callback(err4, data2, container); - }); - }); - }); - } - var optsc = { - "Hostname": "", - "User": "", - "AttachStdin": false, - "AttachStdout": true, - "AttachStderr": true, - "Tty": true, - "OpenStdin": false, - "StdinOnce": false, - "Env": null, - "Cmd": cmd, - "Image": image, - "Volumes": {}, - "VolumesFrom": [] - }; - extend(optsc, createOptions); - this.createContainer(optsc, handler2); - return hub; - }; - Docker3.prototype.runPromise = function(image, cmd, streamo, createOptions, startOptions) { - var self2 = this; - createOptions = createOptions || {}; - startOptions = startOptions || {}; - var optsc = { - "Hostname": "", - "User": "", - "AttachStdin": false, - "AttachStdout": true, - "AttachStderr": true, - "Tty": true, - "OpenStdin": false, - "StdinOnce": false, - "Env": null, - "Cmd": cmd, - "Image": image, - "Volumes": {}, - "VolumesFrom": [] - }; - extend(optsc, createOptions); - var containero; - return new this.modem.Promise(function(resolve, reject) { - self2.createContainer(optsc).then(function(container) { - containero = container; - return container.attach({ - stream: true, - stdout: true, - stderr: true - }); - }).then(function(stream2) { - if (streamo) { - if (streamo instanceof Array) { - stream2.on("end", function() { - try { - streamo[0].end(); - } catch (e) { - } - try { - streamo[1].end(); - } catch (e) { - } - }); - containero.modem.demuxStream(stream2, streamo[0], streamo[1]); - } else { - stream2.setEncoding("utf8"); - stream2.pipe(streamo, { - end: true - }); - } - } - return containero.start(startOptions); - }).then(function(data) { - return containero.wait(); - }).then(function(data) { - resolve([data, containero]); - }).catch(function(err) { - reject(err); - }); - }); - }; - Docker3.prototype.swarmInit = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/swarm/init", - method: "POST", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: "bad parameter", - 406: "node is already part of a Swarm" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Docker3.prototype.swarmJoin = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/swarm/join", - method: "POST", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: "bad parameter", - 406: "node is already part of a Swarm" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Docker3.prototype.swarmLeave = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/swarm/leave?", - method: "POST", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 406: "node is not part of a Swarm" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Docker3.prototype.swarmUpdate = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/swarm/update?", - method: "POST", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: "bad parameter", - 406: "node is already part of a Swarm" - }, - options: args.opts - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Docker3.prototype.swarmInspect = function(opts, callback) { - var self2 = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: "/swarm", - method: "GET", - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 406: "This node is not a swarm manager", - 500: "server error" - } - }; - if (args.callback === void 0) { - return new this.modem.Promise(function(resolve, reject) { - self2.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } - }; - Docker3.Container = Container2; - Docker3.Image = Image; - Docker3.Volume = Volume; - Docker3.Network = Network; - Docker3.Service = Service; - Docker3.Plugin = Plugin; - Docker3.Secret = Secret; - Docker3.Task = Task; - Docker3.Node = Node; - Docker3.Exec = Exec; - module2.exports = Docker3; - } -}); - -// node_modules/events-universal/default.js -var require_default = __commonJS({ - "node_modules/events-universal/default.js"(exports2, module2) { - module2.exports = require("events"); - } -}); - -// node_modules/fast-fifo/fixed-size.js -var require_fixed_size = __commonJS({ - "node_modules/fast-fifo/fixed-size.js"(exports2, module2) { - module2.exports = class FixedFIFO { - constructor(hwm) { - if (!(hwm > 0) || (hwm - 1 & hwm) !== 0) throw new Error("Max size for a FixedFIFO should be a power of two"); - this.buffer = new Array(hwm); - this.mask = hwm - 1; - this.top = 0; - this.btm = 0; - this.next = null; - } - clear() { - this.top = this.btm = 0; - this.next = null; - this.buffer.fill(void 0); - } - push(data) { - if (this.buffer[this.top] !== void 0) return false; - this.buffer[this.top] = data; - this.top = this.top + 1 & this.mask; - return true; - } - shift() { - const last = this.buffer[this.btm]; - if (last === void 0) return void 0; - this.buffer[this.btm] = void 0; - this.btm = this.btm + 1 & this.mask; - return last; - } - peek() { - return this.buffer[this.btm]; - } - isEmpty() { - return this.buffer[this.btm] === void 0; - } - }; - } -}); - -// node_modules/fast-fifo/index.js -var require_fast_fifo = __commonJS({ - "node_modules/fast-fifo/index.js"(exports2, module2) { - var FixedFIFO = require_fixed_size(); - module2.exports = class FastFIFO { - constructor(hwm) { - this.hwm = hwm || 16; - this.head = new FixedFIFO(this.hwm); - this.tail = this.head; - this.length = 0; - } - clear() { - this.head = this.tail; - this.head.clear(); - this.length = 0; - } - push(val) { - this.length++; - if (!this.head.push(val)) { - const prev = this.head; - this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length); - this.head.push(val); - } - } - shift() { - if (this.length !== 0) this.length--; - const val = this.tail.shift(); - if (val === void 0 && this.tail.next) { - const next = this.tail.next; - this.tail.next = null; - this.tail = next; - return this.tail.shift(); - } - return val; - } - peek() { - const val = this.tail.peek(); - if (val === void 0 && this.tail.next) return this.tail.next.peek(); - return val; - } - isEmpty() { - return this.length === 0; - } - }; - } -}); - -// node_modules/b4a/index.js -var require_b4a = __commonJS({ - "node_modules/b4a/index.js"(exports2, module2) { - function isBuffer(value) { - return Buffer.isBuffer(value) || value instanceof Uint8Array; - } - function isEncoding(encoding) { - return Buffer.isEncoding(encoding); - } - function alloc(size, fill2, encoding) { - return Buffer.alloc(size, fill2, encoding); - } - function allocUnsafe(size) { - return Buffer.allocUnsafe(size); - } - function allocUnsafeSlow(size) { - return Buffer.allocUnsafeSlow(size); - } - function byteLength(string, encoding) { - return Buffer.byteLength(string, encoding); - } - function compare(a, b) { - return Buffer.compare(a, b); - } - function concat(buffers, totalLength) { - return Buffer.concat(buffers, totalLength); - } - function copy(source, target, targetStart, start, end) { - return toBuffer(source).copy(target, targetStart, start, end); - } - function equals(a, b) { - return toBuffer(a).equals(b); - } - function fill(buffer, value, offset, end, encoding) { - return toBuffer(buffer).fill(value, offset, end, encoding); - } - function from(value, encodingOrOffset, length) { - return Buffer.from(value, encodingOrOffset, length); - } - function includes(buffer, value, byteOffset, encoding) { - return toBuffer(buffer).includes(value, byteOffset, encoding); - } - function indexOf(buffer, value, byfeOffset, encoding) { - return toBuffer(buffer).indexOf(value, byfeOffset, encoding); - } - function lastIndexOf(buffer, value, byteOffset, encoding) { - return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding); - } - function swap16(buffer) { - return toBuffer(buffer).swap16(); - } - function swap32(buffer) { - return toBuffer(buffer).swap32(); - } - function swap64(buffer) { - return toBuffer(buffer).swap64(); - } - function toBuffer(buffer) { - if (Buffer.isBuffer(buffer)) return buffer; - return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength); - } - function toString(buffer, encoding, start, end) { - return toBuffer(buffer).toString(encoding, start, end); - } - function write(buffer, string, offset, length, encoding) { - return toBuffer(buffer).write(string, offset, length, encoding); - } - function writeDoubleLE(buffer, value, offset) { - return toBuffer(buffer).writeDoubleLE(value, offset); - } - function writeFloatLE(buffer, value, offset) { - return toBuffer(buffer).writeFloatLE(value, offset); - } - function writeUInt32LE(buffer, value, offset) { - return toBuffer(buffer).writeUInt32LE(value, offset); - } - function writeInt32LE(buffer, value, offset) { - return toBuffer(buffer).writeInt32LE(value, offset); - } - function readDoubleLE(buffer, offset) { - return toBuffer(buffer).readDoubleLE(offset); - } - function readFloatLE(buffer, offset) { - return toBuffer(buffer).readFloatLE(offset); - } - function readUInt32LE(buffer, offset) { - return toBuffer(buffer).readUInt32LE(offset); - } - function readInt32LE(buffer, offset) { - return toBuffer(buffer).readInt32LE(offset); - } - module2.exports = { - isBuffer, - isEncoding, - alloc, - allocUnsafe, - allocUnsafeSlow, - byteLength, - compare, - concat, - copy, - equals, - fill, - from, - includes, - indexOf, - lastIndexOf, - swap16, - swap32, - swap64, - toBuffer, - toString, - write, - writeDoubleLE, - writeFloatLE, - writeUInt32LE, - writeInt32LE, - readDoubleLE, - readFloatLE, - readUInt32LE, - readInt32LE - }; - } -}); - -// node_modules/text-decoder/lib/pass-through-decoder.js -var require_pass_through_decoder = __commonJS({ - "node_modules/text-decoder/lib/pass-through-decoder.js"(exports2, module2) { - var b4a = require_b4a(); - module2.exports = class PassThroughDecoder { - constructor(encoding) { - this.encoding = encoding; - } - get remaining() { - return 0; - } - decode(data) { - return b4a.toString(data, this.encoding); - } - flush() { - return ""; - } - }; - } -}); - -// node_modules/text-decoder/lib/utf8-decoder.js -var require_utf8_decoder = __commonJS({ - "node_modules/text-decoder/lib/utf8-decoder.js"(exports2, module2) { - var b4a = require_b4a(); - module2.exports = class UTF8Decoder { - constructor() { - this._reset(); - } - get remaining() { - return this.bytesSeen; - } - decode(data) { - if (data.byteLength === 0) return ""; - if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) { - this.bytesSeen = trailingBytesSeen(data); - return b4a.toString(data, "utf8"); - } - let result = ""; - let start = 0; - if (this.bytesNeeded > 0) { - while (start < data.byteLength) { - const byte = data[start]; - if (byte < this.lowerBoundary || byte > this.upperBoundary) { - result += "\uFFFD"; - this._reset(); - break; - } - this.lowerBoundary = 128; - this.upperBoundary = 191; - this.codePoint = this.codePoint << 6 | byte & 63; - this.bytesSeen++; - start++; - if (this.bytesSeen === this.bytesNeeded) { - result += String.fromCodePoint(this.codePoint); - this._reset(); - break; - } - } - if (this.bytesNeeded > 0) return result; - } - const trailing = trailingIncomplete(data, start); - const end = data.byteLength - trailing; - if (end > start) result += b4a.toString(data, "utf8", start, end); - for (let i = end; i < data.byteLength; i++) { - const byte = data[i]; - if (this.bytesNeeded === 0) { - if (byte <= 127) { - this.bytesSeen = 0; - result += String.fromCharCode(byte); - } else if (byte >= 194 && byte <= 223) { - this.bytesNeeded = 2; - this.bytesSeen = 1; - this.codePoint = byte & 31; - } else if (byte >= 224 && byte <= 239) { - if (byte === 224) this.lowerBoundary = 160; - else if (byte === 237) this.upperBoundary = 159; - this.bytesNeeded = 3; - this.bytesSeen = 1; - this.codePoint = byte & 15; - } else if (byte >= 240 && byte <= 244) { - if (byte === 240) this.lowerBoundary = 144; - else if (byte === 244) this.upperBoundary = 143; - this.bytesNeeded = 4; - this.bytesSeen = 1; - this.codePoint = byte & 7; - } else { - this.bytesSeen = 1; - result += "\uFFFD"; - } - continue; - } - if (byte < this.lowerBoundary || byte > this.upperBoundary) { - result += "\uFFFD"; - i--; - this._reset(); - continue; - } - this.lowerBoundary = 128; - this.upperBoundary = 191; - this.codePoint = this.codePoint << 6 | byte & 63; - this.bytesSeen++; - if (this.bytesSeen === this.bytesNeeded) { - result += String.fromCodePoint(this.codePoint); - this._reset(); - } - } - return result; - } - flush() { - const result = this.bytesNeeded > 0 ? "\uFFFD" : ""; - this._reset(); - return result; - } - _reset() { - this.codePoint = 0; - this.bytesNeeded = 0; - this.bytesSeen = 0; - this.lowerBoundary = 128; - this.upperBoundary = 191; - } - }; - function trailingIncomplete(data, start) { - const len = data.byteLength; - if (len <= start) return 0; - const limit = Math.max(start, len - 4); - let i = len - 1; - while (i > limit && (data[i] & 192) === 128) i--; - if (i < start) return 0; - const byte = data[i]; - let needed; - if (byte <= 127) return 0; - if (byte >= 194 && byte <= 223) needed = 2; - else if (byte >= 224 && byte <= 239) needed = 3; - else if (byte >= 240 && byte <= 244) needed = 4; - else return 0; - const available = len - i; - return available < needed ? available : 0; - } - function trailingBytesSeen(data) { - const len = data.byteLength; - if (len === 0) return 0; - const last = data[len - 1]; - if (last <= 127) return 0; - if ((last & 192) !== 128) return 1; - const limit = Math.max(0, len - 4); - let i = len - 2; - while (i >= limit && (data[i] & 192) === 128) i--; - if (i < 0) return 1; - const first = data[i]; - let needed; - if (first >= 194 && first <= 223) needed = 2; - else if (first >= 224 && first <= 239) needed = 3; - else if (first >= 240 && first <= 244) needed = 4; - else return 1; - if (len - i !== needed) return 1; - if (needed >= 3) { - const second = data[i + 1]; - if (first === 224 && second < 160) return 1; - if (first === 237 && second > 159) return 1; - if (first === 240 && second < 144) return 1; - if (first === 244 && second > 143) return 1; - } - return 0; - } - } -}); - -// node_modules/text-decoder/index.js -var require_text_decoder = __commonJS({ - "node_modules/text-decoder/index.js"(exports2, module2) { - var PassThroughDecoder = require_pass_through_decoder(); - var UTF8Decoder = require_utf8_decoder(); - module2.exports = class TextDecoder { - constructor(encoding = "utf8") { - this.encoding = normalizeEncoding(encoding); - switch (this.encoding) { - case "utf8": - this.decoder = new UTF8Decoder(); - break; - case "utf16le": - case "base64": - throw new Error("Unsupported encoding: " + this.encoding); - default: - this.decoder = new PassThroughDecoder(this.encoding); - } - } - get remaining() { - return this.decoder.remaining; - } - push(data) { - if (typeof data === "string") return data; - return this.decoder.decode(data); - } - // For Node.js compatibility - write(data) { - return this.push(data); - } - end(data) { - let result = ""; - if (data) result = this.push(data); - result += this.decoder.flush(); - return result; - } - }; - function normalizeEncoding(encoding) { - encoding = encoding.toLowerCase(); - switch (encoding) { - 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 encoding; - default: - throw new Error("Unknown encoding: " + encoding); - } - } - } -}); - -// node_modules/streamx/index.js -var require_streamx = __commonJS({ - "node_modules/streamx/index.js"(exports2, module2) { - var { EventEmitter } = require_default(); - var STREAM_DESTROYED = new Error("Stream was destroyed"); - var PREMATURE_CLOSE = new Error("Premature close"); - var FIFO = require_fast_fifo(); - var TextDecoder2 = require_text_decoder(); - var qmt = typeof queueMicrotask === "undefined" ? (fn) => global.process.nextTick(fn) : queueMicrotask; - var MAX = (1 << 29) - 1; - var OPENING = 1; - var PREDESTROYING = 2; - var DESTROYING = 4; - var DESTROYED = 8; - var NOT_OPENING = MAX ^ OPENING; - var NOT_PREDESTROYING = MAX ^ PREDESTROYING; - var READ_ACTIVE = 1 << 4; - var READ_UPDATING = 2 << 4; - var READ_PRIMARY = 4 << 4; - var READ_QUEUED = 8 << 4; - var READ_RESUMED = 16 << 4; - var READ_PIPE_DRAINED = 32 << 4; - var READ_ENDING = 64 << 4; - var READ_EMIT_DATA = 128 << 4; - var READ_EMIT_READABLE = 256 << 4; - var READ_EMITTED_READABLE = 512 << 4; - var READ_DONE = 1024 << 4; - var READ_NEXT_TICK = 2048 << 4; - var READ_NEEDS_PUSH = 4096 << 4; - var READ_READ_AHEAD = 8192 << 4; - var READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED; - var READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH; - var READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE; - var READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED; - var READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD; - var READ_NOT_ACTIVE = MAX ^ READ_ACTIVE; - var READ_NON_PRIMARY = MAX ^ READ_PRIMARY; - var READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH); - var READ_PUSHED = MAX ^ READ_NEEDS_PUSH; - var READ_PAUSED = MAX ^ READ_RESUMED; - var READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE); - var READ_NOT_ENDING = MAX ^ READ_ENDING; - var READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING; - var READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK; - var READ_NOT_UPDATING = MAX ^ READ_UPDATING; - var READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD; - var READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD; - var WRITE_ACTIVE = 1 << 18; - var WRITE_UPDATING = 2 << 18; - var WRITE_PRIMARY = 4 << 18; - var WRITE_QUEUED = 8 << 18; - var WRITE_UNDRAINED = 16 << 18; - var WRITE_DONE = 32 << 18; - var WRITE_EMIT_DRAIN = 64 << 18; - var WRITE_NEXT_TICK = 128 << 18; - var WRITE_WRITING = 256 << 18; - var WRITE_FINISHING = 512 << 18; - var WRITE_CORKED = 1024 << 18; - var WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING); - var WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY; - var WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING); - var WRITE_DRAINED = MAX ^ WRITE_UNDRAINED; - var WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED; - var WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK; - var WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING; - var WRITE_NOT_CORKED = MAX ^ WRITE_CORKED; - var ACTIVE = READ_ACTIVE | WRITE_ACTIVE; - var NOT_ACTIVE = MAX ^ ACTIVE; - var DONE = READ_DONE | WRITE_DONE; - var DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING; - var OPEN_STATUS = DESTROY_STATUS | OPENING; - var AUTO_DESTROY = DESTROY_STATUS | DONE; - var NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY; - var ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK; - var TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE; - var IS_OPENING = OPEN_STATUS | TICKING; - var READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE; - var READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED; - var READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED; - var READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE; - var SHOULD_NOT_READ = OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD; - var READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE; - var READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY; - var READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING; - var WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE; - var WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED; - var WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE; - var WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE; - var WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED; - var WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE; - var WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING; - var WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE; - var WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE; - var WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY; - var WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS; - var asyncIterator = Symbol.asyncIterator || /* @__PURE__ */ Symbol("asyncIterator"); - var WritableState = class { - constructor(stream2, { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}) { - this.stream = stream2; - this.queue = new FIFO(); - this.highWaterMark = highWaterMark; - this.buffered = 0; - this.error = null; - this.pipeline = null; - this.drains = null; - this.byteLength = byteLengthWritable || byteLength || defaultByteLength; - this.map = mapWritable || map; - this.afterWrite = afterWrite.bind(this); - this.afterUpdateNextTick = updateWriteNT.bind(this); - } - get ended() { - return (this.stream._duplexState & WRITE_DONE) !== 0; - } - push(data) { - if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false; - if (this.map !== null) data = this.map(data); - this.buffered += this.byteLength(data); - this.queue.push(data); - if (this.buffered < this.highWaterMark) { - this.stream._duplexState |= WRITE_QUEUED; - return true; - } - this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED; - return false; - } - shift() { - const data = this.queue.shift(); - this.buffered -= this.byteLength(data); - if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED; - return data; - } - end(data) { - if (typeof data === "function") this.stream.once("finish", data); - else if (data !== void 0 && data !== null) this.push(data); - this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY; - } - autoBatch(data, cb) { - const buffer = []; - const stream2 = this.stream; - buffer.push(data); - while ((stream2._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) { - buffer.push(stream2._writableState.shift()); - } - if ((stream2._duplexState & OPEN_STATUS) !== 0) return cb(null); - stream2._writev(buffer, cb); - } - update() { - const stream2 = this.stream; - stream2._duplexState |= WRITE_UPDATING; - do { - while ((stream2._duplexState & WRITE_STATUS) === WRITE_QUEUED) { - const data = this.shift(); - stream2._duplexState |= WRITE_ACTIVE_AND_WRITING; - stream2._write(data, this.afterWrite); - } - if ((stream2._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary(); - } while (this.continueUpdate() === true); - stream2._duplexState &= WRITE_NOT_UPDATING; - } - updateNonPrimary() { - const stream2 = this.stream; - if ((stream2._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) { - stream2._duplexState = stream2._duplexState | WRITE_ACTIVE; - stream2._final(afterFinal.bind(this)); - return; - } - if ((stream2._duplexState & DESTROY_STATUS) === DESTROYING) { - if ((stream2._duplexState & ACTIVE_OR_TICKING) === 0) { - stream2._duplexState |= ACTIVE; - stream2._destroy(afterDestroy.bind(this)); - } - return; - } - if ((stream2._duplexState & IS_OPENING) === OPENING) { - stream2._duplexState = (stream2._duplexState | ACTIVE) & NOT_OPENING; - stream2._open(afterOpen.bind(this)); - } - } - continueUpdate() { - if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false; - this.stream._duplexState &= WRITE_NOT_NEXT_TICK; - return true; - } - updateCallback() { - if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) this.update(); - else this.updateNextTick(); - } - updateNextTick() { - if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return; - this.stream._duplexState |= WRITE_NEXT_TICK; - if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick); - } - }; - var ReadableState = class { - constructor(stream2, { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}) { - this.stream = stream2; - this.queue = new FIFO(); - this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark; - this.buffered = 0; - this.readAhead = highWaterMark > 0; - this.error = null; - this.pipeline = null; - this.byteLength = byteLengthReadable || byteLength || defaultByteLength; - this.map = mapReadable || map; - this.pipeTo = null; - this.afterRead = afterRead.bind(this); - this.afterUpdateNextTick = updateReadNT.bind(this); - } - get ended() { - return (this.stream._duplexState & READ_DONE) !== 0; - } - pipe(pipeTo, cb) { - if (this.pipeTo !== null) throw new Error("Can only pipe to one destination"); - if (typeof cb !== "function") cb = null; - this.stream._duplexState |= READ_PIPE_DRAINED; - this.pipeTo = pipeTo; - this.pipeline = new Pipeline(this.stream, pipeTo, cb); - if (cb) this.stream.on("error", noop3); - if (isStreamx(pipeTo)) { - pipeTo._writableState.pipeline = this.pipeline; - if (cb) pipeTo.on("error", noop3); - pipeTo.on("finish", this.pipeline.finished.bind(this.pipeline)); - } else { - const onerror = this.pipeline.done.bind(this.pipeline, pipeTo); - const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null); - pipeTo.on("error", onerror); - pipeTo.on("close", onclose); - pipeTo.on("finish", this.pipeline.finished.bind(this.pipeline)); - } - pipeTo.on("drain", afterDrain.bind(this)); - this.stream.emit("piping", pipeTo); - pipeTo.emit("pipe", this.stream); - } - push(data) { - const stream2 = this.stream; - if (data === null) { - this.highWaterMark = 0; - stream2._duplexState = (stream2._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED; - return false; - } - if (this.map !== null) { - data = this.map(data); - if (data === null) { - stream2._duplexState &= READ_PUSHED; - return this.buffered < this.highWaterMark; - } - } - this.buffered += this.byteLength(data); - this.queue.push(data); - stream2._duplexState = (stream2._duplexState | READ_QUEUED) & READ_PUSHED; - return this.buffered < this.highWaterMark; - } - shift() { - const data = this.queue.shift(); - this.buffered -= this.byteLength(data); - if (this.buffered === 0) this.stream._duplexState &= READ_NOT_QUEUED; - return data; - } - unshift(data) { - const pending = [this.map !== null ? this.map(data) : data]; - while (this.buffered > 0) pending.push(this.shift()); - for (let i = 0; i < pending.length - 1; i++) { - const data2 = pending[i]; - this.buffered += this.byteLength(data2); - this.queue.push(data2); - } - this.push(pending[pending.length - 1]); - } - read() { - const stream2 = this.stream; - if ((stream2._duplexState & READ_STATUS) === READ_QUEUED) { - const data = this.shift(); - if (this.pipeTo !== null && this.pipeTo.write(data) === false) stream2._duplexState &= READ_PIPE_NOT_DRAINED; - if ((stream2._duplexState & READ_EMIT_DATA) !== 0) stream2.emit("data", data); - return data; - } - if (this.readAhead === false) { - stream2._duplexState |= READ_READ_AHEAD; - this.updateNextTick(); - } - return null; - } - drain() { - const stream2 = this.stream; - while ((stream2._duplexState & READ_STATUS) === READ_QUEUED && (stream2._duplexState & READ_FLOWING) !== 0) { - const data = this.shift(); - if (this.pipeTo !== null && this.pipeTo.write(data) === false) stream2._duplexState &= READ_PIPE_NOT_DRAINED; - if ((stream2._duplexState & READ_EMIT_DATA) !== 0) stream2.emit("data", data); - } - } - update() { - const stream2 = this.stream; - stream2._duplexState |= READ_UPDATING; - do { - this.drain(); - while (this.buffered < this.highWaterMark && (stream2._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD) { - stream2._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH; - stream2._read(this.afterRead); - this.drain(); - } - if ((stream2._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) { - stream2._duplexState |= READ_EMITTED_READABLE; - stream2.emit("readable"); - } - if ((stream2._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary(); - } while (this.continueUpdate() === true); - stream2._duplexState &= READ_NOT_UPDATING; - } - updateNonPrimary() { - const stream2 = this.stream; - if ((stream2._duplexState & READ_ENDING_STATUS) === READ_ENDING) { - stream2._duplexState = (stream2._duplexState | READ_DONE) & READ_NOT_ENDING; - stream2.emit("end"); - if ((stream2._duplexState & AUTO_DESTROY) === DONE) stream2._duplexState |= DESTROYING; - if (this.pipeTo !== null) this.pipeTo.end(); - } - if ((stream2._duplexState & DESTROY_STATUS) === DESTROYING) { - if ((stream2._duplexState & ACTIVE_OR_TICKING) === 0) { - stream2._duplexState |= ACTIVE; - stream2._destroy(afterDestroy.bind(this)); - } - return; - } - if ((stream2._duplexState & IS_OPENING) === OPENING) { - stream2._duplexState = (stream2._duplexState | ACTIVE) & NOT_OPENING; - stream2._open(afterOpen.bind(this)); - } - } - continueUpdate() { - if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false; - this.stream._duplexState &= READ_NOT_NEXT_TICK; - return true; - } - updateCallback() { - if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) this.update(); - else this.updateNextTick(); - } - updateNextTickIfOpen() { - if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return; - this.stream._duplexState |= READ_NEXT_TICK; - if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick); - } - updateNextTick() { - if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return; - this.stream._duplexState |= READ_NEXT_TICK; - if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick); - } - }; - var TransformState = class { - constructor(stream2) { - this.data = null; - this.afterTransform = afterTransform.bind(stream2); - this.afterFinal = null; - } - }; - var Pipeline = class { - constructor(src, dst, cb) { - this.from = src; - this.to = dst; - this.afterPipe = cb; - this.error = null; - this.pipeToFinished = false; - } - finished() { - this.pipeToFinished = true; - } - done(stream2, err) { - if (err) this.error = err; - if (stream2 === this.to) { - this.to = null; - if (this.from !== null) { - if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) { - this.from.destroy(this.error || new Error("Writable stream closed prematurely")); - } - return; - } - } - if (stream2 === this.from) { - this.from = null; - if (this.to !== null) { - if ((stream2._duplexState & READ_DONE) === 0) { - this.to.destroy(this.error || new Error("Readable stream closed before ending")); - } - return; - } - } - if (this.afterPipe !== null) this.afterPipe(this.error); - this.to = this.from = this.afterPipe = null; - } - }; - function afterDrain() { - this.stream._duplexState |= READ_PIPE_DRAINED; - this.updateCallback(); - } - function afterFinal(err) { - const stream2 = this.stream; - if (err) stream2.destroy(err); - if ((stream2._duplexState & DESTROY_STATUS) === 0) { - stream2._duplexState |= WRITE_DONE; - stream2.emit("finish"); - } - if ((stream2._duplexState & AUTO_DESTROY) === DONE) { - stream2._duplexState |= DESTROYING; - } - stream2._duplexState &= WRITE_NOT_FINISHING; - if ((stream2._duplexState & WRITE_UPDATING) === 0) this.update(); - else this.updateNextTick(); - } - function afterDestroy(err) { - const stream2 = this.stream; - if (!err && this.error !== STREAM_DESTROYED) err = this.error; - if (err) stream2.emit("error", err); - stream2._duplexState |= DESTROYED; - stream2.emit("close"); - const rs = stream2._readableState; - const ws = stream2._writableState; - if (rs !== null && rs.pipeline !== null) rs.pipeline.done(stream2, err); - if (ws !== null) { - while (ws.drains !== null && ws.drains.length > 0) ws.drains.shift().resolve(false); - if (ws.pipeline !== null) ws.pipeline.done(stream2, err); - } - } - function afterWrite(err) { - const stream2 = this.stream; - if (err) stream2.destroy(err); - stream2._duplexState &= WRITE_NOT_ACTIVE; - if (this.drains !== null) tickDrains(this.drains); - if ((stream2._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) { - stream2._duplexState &= WRITE_DRAINED; - if ((stream2._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) { - stream2.emit("drain"); - } - } - this.updateCallback(); - } - function afterRead(err) { - if (err) this.stream.destroy(err); - this.stream._duplexState &= READ_NOT_ACTIVE; - if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0) this.stream._duplexState &= READ_NO_READ_AHEAD; - this.updateCallback(); - } - function updateReadNT() { - if ((this.stream._duplexState & READ_UPDATING) === 0) { - this.stream._duplexState &= READ_NOT_NEXT_TICK; - this.update(); - } - } - function updateWriteNT() { - if ((this.stream._duplexState & WRITE_UPDATING) === 0) { - this.stream._duplexState &= WRITE_NOT_NEXT_TICK; - this.update(); - } - } - function tickDrains(drains) { - for (let i = 0; i < drains.length; i++) { - if (--drains[i].writes === 0) { - drains.shift().resolve(true); - i--; - } - } - } - function afterOpen(err) { - const stream2 = this.stream; - if (err) stream2.destroy(err); - if ((stream2._duplexState & DESTROYING) === 0) { - if ((stream2._duplexState & READ_PRIMARY_STATUS) === 0) stream2._duplexState |= READ_PRIMARY; - if ((stream2._duplexState & WRITE_PRIMARY_STATUS) === 0) stream2._duplexState |= WRITE_PRIMARY; - stream2.emit("open"); - } - stream2._duplexState &= NOT_ACTIVE; - if (stream2._writableState !== null) { - stream2._writableState.updateCallback(); - } - if (stream2._readableState !== null) { - stream2._readableState.updateCallback(); - } - } - function afterTransform(err, data) { - if (data !== void 0 && data !== null) this.push(data); - this._writableState.afterWrite(err); - } - function newListener(name) { - if (this._readableState !== null) { - if (name === "data") { - this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD; - this._readableState.updateNextTick(); - } - if (name === "readable") { - this._duplexState |= READ_EMIT_READABLE; - this._readableState.updateNextTick(); - } - } - if (this._writableState !== null) { - if (name === "drain") { - this._duplexState |= WRITE_EMIT_DRAIN; - this._writableState.updateNextTick(); - } - } - } - var Stream = class extends EventEmitter { - constructor(opts) { - super(); - this._duplexState = 0; - this._readableState = null; - this._writableState = null; - if (opts) { - if (opts.open) this._open = opts.open; - if (opts.destroy) this._destroy = opts.destroy; - if (opts.predestroy) this._predestroy = opts.predestroy; - if (opts.signal) { - opts.signal.addEventListener("abort", abort.bind(this)); - } - } - this.on("newListener", newListener); - } - _open(cb) { - cb(null); - } - _destroy(cb) { - cb(null); - } - _predestroy() { - } - get readable() { - return this._readableState !== null ? true : void 0; - } - get writable() { - return this._writableState !== null ? true : void 0; - } - get destroyed() { - return (this._duplexState & DESTROYED) !== 0; - } - get destroying() { - return (this._duplexState & DESTROY_STATUS) !== 0; - } - destroy(err) { - if ((this._duplexState & DESTROY_STATUS) === 0) { - if (!err) err = STREAM_DESTROYED; - this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY; - if (this._readableState !== null) { - this._readableState.highWaterMark = 0; - this._readableState.error = err; - } - if (this._writableState !== null) { - this._writableState.highWaterMark = 0; - this._writableState.error = err; - } - this._duplexState |= PREDESTROYING; - this._predestroy(); - this._duplexState &= NOT_PREDESTROYING; - if (this._readableState !== null) this._readableState.updateNextTick(); - if (this._writableState !== null) this._writableState.updateNextTick(); - } - } - }; - var Readable2 = class _Readable extends Stream { - constructor(opts) { - super(opts); - this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD; - this._readableState = new ReadableState(this, opts); - if (opts) { - if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD; - if (opts.read) this._read = opts.read; - if (opts.eagerOpen) this._readableState.updateNextTick(); - if (opts.encoding) this.setEncoding(opts.encoding); - } - } - setEncoding(encoding) { - const dec = new TextDecoder2(encoding); - const map = this._readableState.map || echo; - this._readableState.map = mapOrSkip; - return this; - function mapOrSkip(data) { - const next = dec.push(data); - return next === "" && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next); - } - } - _read(cb) { - cb(null); - } - pipe(dest, cb) { - this._readableState.updateNextTick(); - this._readableState.pipe(dest, cb); - return dest; - } - read() { - this._readableState.updateNextTick(); - return this._readableState.read(); - } - push(data) { - this._readableState.updateNextTickIfOpen(); - return this._readableState.push(data); - } - unshift(data) { - this._readableState.updateNextTickIfOpen(); - return this._readableState.unshift(data); - } - resume() { - this._duplexState |= READ_RESUMED_READ_AHEAD; - this._readableState.updateNextTick(); - return this; - } - pause() { - this._duplexState &= this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED; - return this; - } - static _fromAsyncIterator(ite, opts) { - let destroy; - const rs = new _Readable({ - ...opts, - read(cb) { - ite.next().then(push).then(cb.bind(null, null)).catch(cb); - }, - predestroy() { - destroy = ite.return(); - }, - destroy(cb) { - if (!destroy) return cb(null); - destroy.then(cb.bind(null, null)).catch(cb); - } - }); - return rs; - function push(data) { - if (data.done) rs.push(null); - else rs.push(data.value); - } - } - static from(data, opts) { - if (isReadStreamx(data)) return data; - if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts); - if (!Array.isArray(data)) data = data === void 0 ? [] : [data]; - let i = 0; - return new _Readable({ - ...opts, - read(cb) { - this.push(i === data.length ? null : data[i++]); - cb(null); - } - }); - } - static isBackpressured(rs) { - return (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 || rs._readableState.buffered >= rs._readableState.highWaterMark; - } - static isPaused(rs) { - return (rs._duplexState & READ_RESUMED) === 0; - } - [asyncIterator]() { - const stream2 = this; - let error3 = null; - let promiseResolve = null; - let promiseReject = null; - this.on("error", (err) => { - error3 = err; - }); - this.on("readable", onreadable); - this.on("close", onclose); - return { - [asyncIterator]() { - return this; - }, - next() { - return new Promise(function(resolve, reject) { - promiseResolve = resolve; - promiseReject = reject; - const data = stream2.read(); - if (data !== null) ondata(data); - else if ((stream2._duplexState & DESTROYED) !== 0) ondata(null); - }); - }, - return() { - return destroy(null); - }, - throw(err) { - return destroy(err); - } - }; - function onreadable() { - if (promiseResolve !== null) ondata(stream2.read()); - } - function onclose() { - if (promiseResolve !== null) ondata(null); - } - function ondata(data) { - if (promiseReject === null) return; - if (error3) promiseReject(error3); - else if (data === null && (stream2._duplexState & READ_DONE) === 0) promiseReject(STREAM_DESTROYED); - else promiseResolve({ value: data, done: data === null }); - promiseReject = promiseResolve = null; - } - function destroy(err) { - stream2.destroy(err); - return new Promise((resolve, reject) => { - if (stream2._duplexState & DESTROYED) return resolve({ value: void 0, done: true }); - stream2.once("close", function() { - if (err) reject(err); - else resolve({ value: void 0, done: true }); - }); - }); - } - } - }; - var Writable2 = class extends Stream { - constructor(opts) { - super(opts); - this._duplexState |= OPENING | READ_DONE; - this._writableState = new WritableState(this, opts); - if (opts) { - if (opts.writev) this._writev = opts.writev; - if (opts.write) this._write = opts.write; - if (opts.final) this._final = opts.final; - if (opts.eagerOpen) this._writableState.updateNextTick(); - } - } - cork() { - this._duplexState |= WRITE_CORKED; - } - uncork() { - this._duplexState &= WRITE_NOT_CORKED; - this._writableState.updateNextTick(); - } - _writev(batch, cb) { - cb(null); - } - _write(data, cb) { - this._writableState.autoBatch(data, cb); - } - _final(cb) { - cb(null); - } - static isBackpressured(ws) { - return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0; - } - static drained(ws) { - if (ws.destroyed) return Promise.resolve(false); - const state = ws._writableState; - const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length; - const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0); - if (writes === 0) return Promise.resolve(true); - if (state.drains === null) state.drains = []; - return new Promise((resolve) => { - state.drains.push({ writes, resolve }); - }); - } - write(data) { - this._writableState.updateNextTick(); - return this._writableState.push(data); - } - end(data) { - this._writableState.updateNextTick(); - this._writableState.end(data); - return this; - } - }; - var Duplex = class extends Readable2 { - // and Writable - constructor(opts) { - super(opts); - this._duplexState = OPENING | this._duplexState & READ_READ_AHEAD; - this._writableState = new WritableState(this, opts); - if (opts) { - if (opts.writev) this._writev = opts.writev; - if (opts.write) this._write = opts.write; - if (opts.final) this._final = opts.final; - } - } - cork() { - this._duplexState |= WRITE_CORKED; - } - uncork() { - this._duplexState &= WRITE_NOT_CORKED; - this._writableState.updateNextTick(); - } - _writev(batch, cb) { - cb(null); - } - _write(data, cb) { - this._writableState.autoBatch(data, cb); - } - _final(cb) { - cb(null); - } - write(data) { - this._writableState.updateNextTick(); - return this._writableState.push(data); - } - end(data) { - this._writableState.updateNextTick(); - this._writableState.end(data); - return this; - } - }; - var Transform = class extends Duplex { - constructor(opts) { - super(opts); - this._transformState = new TransformState(this); - if (opts) { - if (opts.transform) this._transform = opts.transform; - if (opts.flush) this._flush = opts.flush; - } - } - _write(data, cb) { - if (this._readableState.buffered >= this._readableState.highWaterMark) { - this._transformState.data = data; - } else { - this._transform(data, this._transformState.afterTransform); - } - } - _read(cb) { - if (this._transformState.data !== null) { - const data = this._transformState.data; - this._transformState.data = null; - cb(null); - this._transform(data, this._transformState.afterTransform); - } else { - cb(null); - } - } - destroy(err) { - super.destroy(err); - if (this._transformState.data !== null) { - this._transformState.data = null; - this._transformState.afterTransform(); - } - } - _transform(data, cb) { - cb(null, data); - } - _flush(cb) { - cb(null); - } - _final(cb) { - this._transformState.afterFinal = cb; - this._flush(transformAfterFlush.bind(this)); - } - }; - var PassThrough = class extends Transform { - }; - function transformAfterFlush(err, data) { - const cb = this._transformState.afterFinal; - if (err) return cb(err); - if (data !== null && data !== void 0) this.push(data); - this.push(null); - cb(null); - } - function pipelinePromise(...streams) { - return new Promise((resolve, reject) => { - return pipeline(...streams, (err) => { - if (err) return reject(err); - resolve(); - }); - }); - } - function pipeline(stream2, ...streams) { - const all = Array.isArray(stream2) ? [...stream2, ...streams] : [stream2, ...streams]; - const done = all.length && typeof all[all.length - 1] === "function" ? all.pop() : null; - if (all.length < 2) throw new Error("Pipeline requires at least 2 streams"); - let src = all[0]; - let dest = null; - let error3 = null; - for (let i = 1; i < all.length; i++) { - dest = all[i]; - if (isStreamx(src)) { - src.pipe(dest, onerror); - } else { - errorHandle(src, true, i > 1, onerror); - src.pipe(dest); - } - src = dest; - } - if (done) { - let fin = false; - const autoDestroy = isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy); - dest.on("error", (err) => { - if (error3 === null) error3 = err; - }); - dest.on("finish", () => { - fin = true; - if (!autoDestroy) done(error3); - }); - if (autoDestroy) { - dest.on("close", () => done(error3 || (fin ? null : PREMATURE_CLOSE))); - } - } - return dest; - function errorHandle(s, rd, wr, onerror2) { - s.on("error", onerror2); - s.on("close", onclose); - function onclose() { - if (rd && s._readableState && !s._readableState.ended) return onerror2(PREMATURE_CLOSE); - if (wr && s._writableState && !s._writableState.ended) return onerror2(PREMATURE_CLOSE); - } - } - function onerror(err) { - if (!err || error3) return; - error3 = err; - for (const s of all) { - s.destroy(err); - } - } - } - function echo(s) { - return s; - } - function isStream(stream2) { - return !!stream2._readableState || !!stream2._writableState; - } - function isStreamx(stream2) { - return typeof stream2._duplexState === "number" && isStream(stream2); - } - function isEnded(stream2) { - return !!stream2._readableState && stream2._readableState.ended; - } - function isFinished(stream2) { - return !!stream2._writableState && stream2._writableState.ended; - } - function getStreamError(stream2, opts = {}) { - const err = stream2._readableState && stream2._readableState.error || stream2._writableState && stream2._writableState.error; - return !opts.all && err === STREAM_DESTROYED ? null : err; - } - function isReadStreamx(stream2) { - return isStreamx(stream2) && stream2.readable; - } - function isDisturbed(stream2) { - return (stream2._duplexState & OPENING) !== OPENING || (stream2._duplexState & ACTIVE_OR_TICKING) !== 0; - } - function isTypedArray(data) { - return typeof data === "object" && data !== null && typeof data.byteLength === "number"; - } - function defaultByteLength(data) { - return isTypedArray(data) ? data.byteLength : 1024; - } - function noop3() { - } - function abort() { - this.destroy(new Error("Stream aborted.")); - } - function isWritev(s) { - return s._writev !== Writable2.prototype._writev && s._writev !== Duplex.prototype._writev; - } - module2.exports = { - pipeline, - pipelinePromise, - isStream, - isStreamx, - isEnded, - isFinished, - isDisturbed, - getStreamError, - Stream, - Writable: Writable2, - Readable: Readable2, - Duplex, - Transform, - // Export PassThrough for compatibility with Node.js core's stream module - PassThrough - }; - } -}); - -// node_modules/tar-stream/headers.js -var require_headers3 = __commonJS({ - "node_modules/tar-stream/headers.js"(exports2) { - var b4a = require_b4a(); - var ZEROS = "0000000000000000000"; - var SEVENS = "7777777777777777777"; - var ZERO_OFFSET = "0".charCodeAt(0); - var USTAR_MAGIC = b4a.from([117, 115, 116, 97, 114, 0]); - var USTAR_VER = b4a.from([ZERO_OFFSET, ZERO_OFFSET]); - var GNU_MAGIC = b4a.from([117, 115, 116, 97, 114, 32]); - var GNU_VER = b4a.from([32, 0]); - var MASK = 4095; - var MAGIC_OFFSET = 257; - var VERSION_OFFSET = 263; - exports2.decodeLongPath = function decodeLongPath(buf, encoding) { - return decodeStr(buf, 0, buf.length, encoding); - }; - exports2.encodePax = function encodePax(opts) { - let result = ""; - if (opts.name) result += addLength(" path=" + opts.name + "\n"); - if (opts.linkname) result += addLength(" linkpath=" + opts.linkname + "\n"); - const pax = opts.pax; - if (pax) { - for (const key in pax) { - result += addLength(" " + key + "=" + pax[key] + "\n"); - } - } - return b4a.from(result); - }; - exports2.decodePax = function decodePax(buf) { - const result = {}; - while (buf.length) { - let i = 0; - while (i < buf.length && buf[i] !== 32) i++; - const len = parseInt(b4a.toString(buf.subarray(0, i)), 10); - if (!len) return result; - const b = b4a.toString(buf.subarray(i + 1, len - 1)); - const keyIndex = b.indexOf("="); - if (keyIndex === -1) return result; - result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1); - buf = buf.subarray(len); - } - return result; - }; - exports2.encode = function encode(opts) { - const buf = b4a.alloc(512); - let name = opts.name; - let prefix = ""; - if (opts.typeflag === 5 && name[name.length - 1] !== "/") name += "/"; - if (b4a.byteLength(name) !== name.length) return null; - while (b4a.byteLength(name) > 100) { - const i = name.indexOf("/"); - if (i === -1) return null; - prefix += prefix ? "/" + name.slice(0, i) : name.slice(0, i); - name = name.slice(i + 1); - } - if (b4a.byteLength(name) > 100 || b4a.byteLength(prefix) > 155) return null; - if (opts.linkname && b4a.byteLength(opts.linkname) > 100) return null; - b4a.write(buf, name); - b4a.write(buf, encodeOct(opts.mode & MASK, 6), 100); - b4a.write(buf, encodeOct(opts.uid, 6), 108); - b4a.write(buf, encodeOct(opts.gid, 6), 116); - encodeSize(opts.size, buf, 124); - b4a.write(buf, encodeOct(opts.mtime.getTime() / 1e3 | 0, 11), 136); - buf[156] = ZERO_OFFSET + toTypeflag(opts.type); - if (opts.linkname) b4a.write(buf, opts.linkname, 157); - b4a.copy(USTAR_MAGIC, buf, MAGIC_OFFSET); - b4a.copy(USTAR_VER, buf, VERSION_OFFSET); - if (opts.uname) b4a.write(buf, opts.uname, 265); - if (opts.gname) b4a.write(buf, opts.gname, 297); - b4a.write(buf, encodeOct(opts.devmajor || 0, 6), 329); - b4a.write(buf, encodeOct(opts.devminor || 0, 6), 337); - if (prefix) b4a.write(buf, prefix, 345); - b4a.write(buf, encodeOct(cksum(buf), 6), 148); - return buf; - }; - exports2.decode = function decode(buf, filenameEncoding, allowUnknownFormat) { - let typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET; - let name = decodeStr(buf, 0, 100, filenameEncoding); - const mode = decodeOct(buf, 100, 8); - const uid = decodeOct(buf, 108, 8); - const gid = decodeOct(buf, 116, 8); - const size = decodeOct(buf, 124, 12); - const mtime = decodeOct(buf, 136, 12); - const type = toType(typeflag); - const linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100, filenameEncoding); - const uname = decodeStr(buf, 265, 32); - const gname = decodeStr(buf, 297, 32); - const devmajor = decodeOct(buf, 329, 8); - const devminor = decodeOct(buf, 337, 8); - const c = cksum(buf); - if (c === 8 * 32) return null; - if (c !== decodeOct(buf, 148, 8)) throw new Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?"); - if (isUSTAR(buf)) { - if (buf[345]) name = decodeStr(buf, 345, 155, filenameEncoding) + "/" + name; - } else if (isGNU(buf)) { - } else { - if (!allowUnknownFormat) { - throw new Error("Invalid tar header: unknown format."); - } - } - if (typeflag === 0 && name && name[name.length - 1] === "/") typeflag = 5; - return { - name, - mode, - uid, - gid, - size, - byteOffset: 0, - mtime: new Date(1e3 * mtime), - type, - linkname, - uname, - gname, - devmajor, - devminor, - pax: null - }; - }; - function isUSTAR(buf) { - return b4a.equals(USTAR_MAGIC, buf.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6)); - } - function isGNU(buf) { - return b4a.equals(GNU_MAGIC, buf.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6)) && b4a.equals(GNU_VER, buf.subarray(VERSION_OFFSET, VERSION_OFFSET + 2)); - } - function clamp(index, len, defaultValue) { - if (typeof index !== "number") return defaultValue; - index = ~~index; - if (index >= len) return len; - if (index >= 0) return index; - index += len; - if (index >= 0) return index; - return 0; - } - function toType(flag) { - switch (flag) { - case 0: - return "file"; - case 1: - return "link"; - case 2: - return "symlink"; - case 3: - return "character-device"; - case 4: - return "block-device"; - case 5: - return "directory"; - case 6: - return "fifo"; - case 7: - return "contiguous-file"; - case 72: - return "pax-header"; - case 55: - return "pax-global-header"; - case 27: - return "gnu-long-link-path"; - case 28: - case 30: - return "gnu-long-path"; - } - return null; - } - function toTypeflag(flag) { - switch (flag) { - case "file": - return 0; - case "link": - return 1; - case "symlink": - return 2; - case "character-device": - return 3; - case "block-device": - return 4; - case "directory": - return 5; - case "fifo": - return 6; - case "contiguous-file": - return 7; - case "pax-header": - return 72; - } - return 0; - } - function indexOf(block, num, offset, end) { - for (; offset < end; offset++) { - if (block[offset] === num) return offset; - } - return end; - } - function cksum(block) { - let sum = 8 * 32; - for (let i = 0; i < 148; i++) sum += block[i]; - for (let j = 156; j < 512; j++) sum += block[j]; - return sum; - } - function encodeOct(val, n) { - val = val.toString(8); - if (val.length > n) return SEVENS.slice(0, n) + " "; - return ZEROS.slice(0, n - val.length) + val + " "; - } - function encodeSizeBin(num, buf, off) { - buf[off] = 128; - for (let i = 11; i > 0; i--) { - buf[off + i] = num & 255; - num = Math.floor(num / 256); - } - } - function encodeSize(num, buf, off) { - if (num.toString(8).length > 11) { - encodeSizeBin(num, buf, off); - } else { - b4a.write(buf, encodeOct(num, 11), off); - } - } - function parse256(buf) { - let positive; - if (buf[0] === 128) positive = true; - else if (buf[0] === 255) positive = false; - else return null; - const tuple = []; - let i; - for (i = buf.length - 1; i > 0; i--) { - const byte = buf[i]; - if (positive) tuple.push(byte); - else tuple.push(255 - byte); - } - let sum = 0; - const l = tuple.length; - for (i = 0; i < l; i++) { - sum += tuple[i] * Math.pow(256, i); - } - return positive ? sum : -1 * sum; - } - function decodeOct(val, offset, length) { - val = val.subarray(offset, offset + length); - offset = 0; - if (val[offset] & 128) { - return parse256(val); - } else { - while (offset < val.length && val[offset] === 32) offset++; - const end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length); - while (offset < end && val[offset] === 0) offset++; - if (end === offset) return 0; - return parseInt(b4a.toString(val.subarray(offset, end)), 8); - } - } - function decodeStr(val, offset, length, encoding) { - return b4a.toString(val.subarray(offset, indexOf(val, 0, offset, offset + length)), encoding); - } - function addLength(str) { - const len = b4a.byteLength(str); - let digits = Math.floor(Math.log(len) / Math.log(10)) + 1; - if (len + digits >= Math.pow(10, digits)) digits++; - return len + digits + str; - } - } -}); - -// node_modules/tar-stream/extract.js -var require_extract2 = __commonJS({ - "node_modules/tar-stream/extract.js"(exports2, module2) { - var { Writable: Writable2, Readable: Readable2, getStreamError } = require_streamx(); - var FIFO = require_fast_fifo(); - var b4a = require_b4a(); - var headers = require_headers3(); - var EMPTY = b4a.alloc(0); - var MAX_HEADER_SIZE = 4 * 1024 * 1024; - var BufferList = class { - constructor() { - this.buffered = 0; - this.shifted = 0; - this.queue = new FIFO(); - this._offset = 0; - } - push(buffer) { - this.buffered += buffer.byteLength; - this.queue.push(buffer); - } - shiftFirst(size) { - return this.buffered === 0 ? null : this._next(size); - } - shift(size) { - if (size > this.buffered) return null; - if (size === 0) return EMPTY; - let chunk = this._next(size); - if (size === chunk.byteLength) return chunk; - const chunks = [chunk]; - while ((size -= chunk.byteLength) > 0) { - chunk = this._next(size); - chunks.push(chunk); - } - return b4a.concat(chunks); - } - _next(size) { - const buf = this.queue.peek(); - const rem = buf.byteLength - this._offset; - if (size >= rem) { - const sub = this._offset ? buf.subarray(this._offset, buf.byteLength) : buf; - this.queue.shift(); - this._offset = 0; - this.buffered -= rem; - this.shifted += rem; - return sub; - } - this.buffered -= size; - this.shifted += size; - return buf.subarray(this._offset, this._offset += size); - } - }; - var Source = class extends Readable2 { - constructor(self2, header, offset) { - super(); - this.header = header; - this.offset = offset; - this._parent = self2; - } - _read(cb) { - if (this.header.size === 0) { - this.push(null); - } - if (this._parent._stream === this) { - this._parent._update(); - } - cb(null); - } - _predestroy() { - this._parent.destroy(getStreamError(this)); - } - _detach() { - if (this._parent._stream === this) { - this._parent._stream = null; - this._parent._missing = overflow(this.header.size); - this._parent._update(); - } - } - _destroy(cb) { - this._detach(); - cb(null); - } - }; - var Extract = class extends Writable2 { - constructor(opts) { - super(opts); - if (!opts) opts = {}; - this._buffer = new BufferList(); - this._offset = 0; - this._header = null; - this._stream = null; - this._missing = 0; - this._longHeader = false; - this._callback = noop3; - this._locked = false; - this._finished = false; - this._pax = null; - this._paxGlobal = null; - this._gnuLongPath = null; - this._gnuLongLinkPath = null; - this._filenameEncoding = opts.filenameEncoding || "utf-8"; - this._allowUnknownFormat = !!opts.allowUnknownFormat; - this._unlockBound = this._unlock.bind(this); - } - _unlock(err) { - this._locked = false; - if (err) { - this.destroy(err); - this._continueWrite(err); - return; - } - this._update(); - } - _consumeHeader() { - if (this._locked) return false; - this._offset = this._buffer.shifted; - try { - this._header = headers.decode(this._buffer.shift(512), this._filenameEncoding, this._allowUnknownFormat); - } catch (err) { - this._continueWrite(err); - return false; - } - if (!this._header) return true; - this._header.byteOffset = this._buffer.shifted; - switch (this._header.type) { - case "gnu-long-path": - case "gnu-long-link-path": - case "pax-global-header": - case "pax-header": - this._longHeader = true; - this._missing = this._header.size; - if (this._missing > MAX_HEADER_SIZE) { - this._continueWrite(new Error("Header exceeds max size")); - return false; - } - return true; - } - this._locked = true; - this._applyLongHeaders(); - if (!(this._header.size >= 0)) { - this._continueWrite(new Error("Invalid header")); - return false; - } - if (this._header.size === 0 || this._header.type === "directory") { - this.emit("entry", this._header, this._createStream(), this._unlockBound); - return true; - } - this._stream = this._createStream(); - this._missing = this._header.size; - this.emit("entry", this._header, this._stream, this._unlockBound); - return true; - } - _applyLongHeaders() { - if (this._gnuLongPath) { - this._header.name = this._gnuLongPath; - this._gnuLongPath = null; - } - if (this._gnuLongLinkPath) { - this._header.linkname = this._gnuLongLinkPath; - this._gnuLongLinkPath = null; - } - if (this._pax) { - if (this._pax.path) this._header.name = this._pax.path; - if (this._pax.linkpath) this._header.linkname = this._pax.linkpath; - if (this._pax.size) this._header.size = parseInt(this._pax.size, 10); - this._header.pax = this._pax; - this._pax = null; - } - } - _decodeLongHeader(buf) { - switch (this._header.type) { - case "gnu-long-path": - this._gnuLongPath = headers.decodeLongPath(buf, this._filenameEncoding); - break; - case "gnu-long-link-path": - this._gnuLongLinkPath = headers.decodeLongPath(buf, this._filenameEncoding); - break; - case "pax-global-header": - this._paxGlobal = headers.decodePax(buf); - break; - case "pax-header": - this._pax = this._paxGlobal === null ? headers.decodePax(buf) : Object.assign({}, this._paxGlobal, headers.decodePax(buf)); - break; - } - } - _consumeLongHeader() { - this._longHeader = false; - this._missing = overflow(this._header.size); - const buf = this._buffer.shift(this._header.size); - try { - this._decodeLongHeader(buf); - } catch (err) { - this._continueWrite(err); - return false; - } - return true; - } - _consumeStream() { - const buf = this._buffer.shiftFirst(this._missing); - if (buf === null) return false; - this._missing -= buf.byteLength; - const drained = this._stream.push(buf); - if (this._missing === 0) { - this._stream.push(null); - if (drained) this._stream._detach(); - return drained && this._locked === false; - } - return drained; - } - _createStream() { - return new Source(this, this._header, this._offset); - } - _update() { - while (this._buffer.buffered > 0 && !this.destroying) { - if (this._missing > 0) { - if (this._stream !== null) { - if (this._consumeStream() === false) return; - continue; - } - if (this._longHeader === true) { - if (this._missing > this._buffer.buffered) break; - if (this._consumeLongHeader() === false) return false; - continue; - } - const ignore = this._buffer.shiftFirst(this._missing); - if (ignore !== null) this._missing -= ignore.byteLength; - continue; - } - if (this._buffer.buffered < 512) break; - if (this._stream !== null || this._consumeHeader() === false) return; - } - this._continueWrite(null); - } - _continueWrite(err) { - const cb = this._callback; - this._callback = noop3; - cb(err); - } - _write(data, cb) { - this._callback = cb; - this._buffer.push(data); - this._update(); - } - _final(cb) { - this._finished = this._missing === 0 && this._buffer.buffered === 0; - cb(this._finished ? null : new Error("Unexpected end of data")); - } - _predestroy() { - this._continueWrite(null); - } - _destroy(cb) { - if (this._stream) this._stream.destroy(getStreamError(this)); - cb(null); - } - [Symbol.asyncIterator]() { - let error3 = null; - let promiseResolve = null; - let promiseReject = null; - let entryStream = null; - let entryCallback = null; - const extract2 = this; - this.on("entry", onentry); - this.on("error", (err) => { - error3 = err; - }); - this.on("close", onclose); - return { - [Symbol.asyncIterator]() { - return this; - }, - next() { - return new Promise(onnext); - }, - return() { - return destroy(null); - }, - throw(err) { - return destroy(err); - } - }; - function consumeCallback(err) { - if (!entryCallback) return; - const cb = entryCallback; - entryCallback = null; - cb(err); - } - function onnext(resolve, reject) { - if (error3) { - return reject(error3); - } - if (entryStream) { - resolve({ value: entryStream, done: false }); - entryStream = null; - return; - } - promiseResolve = resolve; - promiseReject = reject; - consumeCallback(null); - if (extract2._finished && promiseResolve) { - promiseResolve({ value: void 0, done: true }); - promiseResolve = promiseReject = null; - } - } - function onentry(header, stream2, callback) { - entryCallback = callback; - stream2.on("error", noop3); - if (promiseResolve) { - promiseResolve({ value: stream2, done: false }); - promiseResolve = promiseReject = null; - } else { - entryStream = stream2; - } - } - function onclose() { - consumeCallback(error3); - if (!promiseResolve) return; - if (error3) promiseReject(error3); - else promiseResolve({ value: void 0, done: true }); - promiseResolve = promiseReject = null; - } - function destroy(err) { - extract2.destroy(err); - consumeCallback(err); - return new Promise((resolve, reject) => { - if (extract2.destroyed) return resolve({ value: void 0, done: true }); - extract2.once("close", function() { - if (err) reject(err); - else resolve({ value: void 0, done: true }); - }); - }); - } - } - }; - module2.exports = function extract2(opts) { - return new Extract(opts); - }; - function noop3() { - } - function overflow(size) { - size &= 511; - return size && 512 - size; - } - } -}); - -// node_modules/tar-stream/constants.js -var require_constants8 = __commonJS({ - "node_modules/tar-stream/constants.js"(exports2, module2) { - var constants = { - // just for envs without fs - S_IFMT: 61440, - S_IFDIR: 16384, - S_IFCHR: 8192, - S_IFBLK: 24576, - S_IFIFO: 4096, - S_IFLNK: 40960 - }; - try { - module2.exports = require("fs").constants || constants; - } catch { - module2.exports = constants; - } - } -}); - -// node_modules/tar-stream/pack.js -var require_pack2 = __commonJS({ - "node_modules/tar-stream/pack.js"(exports2, module2) { - var { Readable: Readable2, Writable: Writable2, getStreamError } = require_streamx(); - var b4a = require_b4a(); - var constants = require_constants8(); - var headers = require_headers3(); - var DMODE = 493; - var FMODE = 420; - var END_OF_TAR = b4a.alloc(1024); - var Sink = class extends Writable2 { - constructor(pack2, header, callback) { - super({ mapWritable, eagerOpen: true }); - this.written = 0; - this.header = header; - this._callback = callback; - this._linkname = null; - this._isLinkname = header.type === "symlink" && !header.linkname; - this._isVoid = header.type !== "file" && header.type !== "contiguous-file"; - this._finished = false; - this._pack = pack2; - this._openCallback = null; - if (this._pack._stream === null) this._pack._stream = this; - else this._pack._pending.push(this); - } - _open(cb) { - this._openCallback = cb; - if (this._pack._stream === this) this._continueOpen(); - } - _continuePack(err) { - if (this._callback === null) return; - const callback = this._callback; - this._callback = null; - callback(err); - } - _continueOpen() { - if (this._pack._stream === null) this._pack._stream = this; - const cb = this._openCallback; - this._openCallback = null; - if (cb === null) return; - if (this._pack.destroying) return cb(new Error("pack stream destroyed")); - if (this._pack._finalized) return cb(new Error("pack stream is already finalized")); - this._pack._stream = this; - if (!this._isLinkname) { - this._pack._encode(this.header); - } - if (this._isVoid) { - this._finish(); - this._continuePack(null); - } - cb(null); - } - _write(data, cb) { - if (this._isLinkname) { - this._linkname = this._linkname ? b4a.concat([this._linkname, data]) : data; - return cb(null); - } - if (this._isVoid) { - if (data.byteLength > 0) { - return cb(new Error("No body allowed for this entry")); - } - return cb(); - } - this.written += data.byteLength; - if (this._pack.push(data)) return cb(); - this._pack._drain = cb; - } - _finish() { - if (this._finished) return; - this._finished = true; - if (this._isLinkname) { - this.header.linkname = this._linkname ? b4a.toString(this._linkname, "utf-8") : ""; - this._pack._encode(this.header); - } - overflow(this._pack, this.header.size); - this._pack._done(this); - } - _final(cb) { - if (this.written !== this.header.size) { - return cb(new Error("Size mismatch")); - } - this._finish(); - cb(null); - } - _getError() { - return getStreamError(this) || new Error("tar entry destroyed"); - } - _predestroy() { - this._pack.destroy(this._getError()); - } - _destroy(cb) { - this._pack._done(this); - this._continuePack(this._finished ? null : this._getError()); - cb(); - } - }; - var Pack = class extends Readable2 { - constructor(opts) { - super(opts); - this._drain = noop3; - this._finalized = false; - this._finalizing = false; - this._pending = []; - this._stream = null; - } - entry(header, buffer, callback) { - if (this._finalized || this.destroying) throw new Error("already finalized or destroyed"); - if (typeof buffer === "function") { - callback = buffer; - buffer = null; - } - if (!callback) callback = noop3; - if (!header.size || header.type === "symlink") header.size = 0; - if (!header.type) header.type = modeToType(header.mode); - if (!header.mode) header.mode = header.type === "directory" ? DMODE : FMODE; - if (!header.uid) header.uid = 0; - if (!header.gid) header.gid = 0; - if (!header.mtime) header.mtime = /* @__PURE__ */ new Date(); - if (typeof buffer === "string") buffer = b4a.from(buffer); - const sink = new Sink(this, header, callback); - if (b4a.isBuffer(buffer)) { - header.size = buffer.byteLength; - sink.write(buffer); - sink.end(); - return sink; - } - if (sink._isVoid) { - return sink; - } - return sink; - } - finalize() { - if (this._stream || this._pending.length > 0) { - this._finalizing = true; - return; - } - if (this._finalized) return; - this._finalized = true; - this.push(END_OF_TAR); - this.push(null); - } - _done(stream2) { - if (stream2 !== this._stream) return; - this._stream = null; - if (this._finalizing) this.finalize(); - if (this._pending.length) this._pending.shift()._continueOpen(); - } - _encode(header) { - if (!header.pax) { - const buf = headers.encode(header); - if (buf) { - this.push(buf); - return; - } - } - this._encodePax(header); - } - _encodePax(header) { - const paxHeader = headers.encodePax({ - name: header.name, - linkname: header.linkname, - pax: header.pax - }); - const newHeader = { - name: "PaxHeader", - mode: header.mode, - uid: header.uid, - gid: header.gid, - size: paxHeader.byteLength, - mtime: header.mtime, - type: "pax-header", - linkname: header.linkname && "PaxHeader", - uname: header.uname, - gname: header.gname, - devmajor: header.devmajor, - devminor: header.devminor - }; - this.push(headers.encode(newHeader)); - this.push(paxHeader); - overflow(this, paxHeader.byteLength); - newHeader.size = header.size; - newHeader.type = header.type; - this.push(headers.encode(newHeader)); - } - _doDrain() { - const drain = this._drain; - this._drain = noop3; - drain(); - } - _predestroy() { - const err = getStreamError(this); - if (this._stream) this._stream.destroy(err); - while (this._pending.length) { - const stream2 = this._pending.shift(); - stream2.destroy(err); - stream2._continueOpen(); - } - this._doDrain(); - } - _read(cb) { - this._doDrain(); - cb(); - } - }; - module2.exports = function pack2(opts) { - return new Pack(opts); - }; - function modeToType(mode) { - switch (mode & constants.S_IFMT) { - case constants.S_IFBLK: - return "block-device"; - case constants.S_IFCHR: - return "character-device"; - case constants.S_IFDIR: - return "directory"; - case constants.S_IFIFO: - return "fifo"; - case constants.S_IFLNK: - return "symlink"; - } - return "file"; - } - function noop3() { - } - function overflow(self2, size) { - size &= 511; - if (size) self2.push(END_OF_TAR.subarray(0, 512 - size)); - } - function mapWritable(buf) { - return b4a.isBuffer(buf) ? buf : b4a.from(buf); - } - } -}); - -// node_modules/tar-stream/index.js -var require_tar_stream2 = __commonJS({ - "node_modules/tar-stream/index.js"(exports2) { - exports2.extract = require_extract2(); - exports2.pack = require_pack2(); - } -}); - -// node_modules/node-forge/lib/forge.js -var require_forge = __commonJS({ - "node_modules/node-forge/lib/forge.js"(exports2, module2) { - module2.exports = { - // default options - options: { - usePureJavaScript: false - } - }; - } -}); - -// node_modules/node-forge/lib/baseN.js -var require_baseN = __commonJS({ - "node_modules/node-forge/lib/baseN.js"(exports2, module2) { - var api = {}; - module2.exports = api; - var _reverseAlphabets = {}; - api.encode = function(input, alphabet, maxline) { - if (typeof alphabet !== "string") { - throw new TypeError('"alphabet" must be a string.'); - } - if (maxline !== void 0 && typeof maxline !== "number") { - throw new TypeError('"maxline" must be a number.'); - } - var output = ""; - if (!(input instanceof Uint8Array)) { - output = _encodeWithByteBuffer(input, alphabet); - } else { - var i = 0; - var base = alphabet.length; - var first = alphabet.charAt(0); - var digits = [0]; - for (i = 0; i < input.length; ++i) { - for (var j = 0, carry = input[i]; j < digits.length; ++j) { - carry += digits[j] << 8; - digits[j] = carry % base; - carry = carry / base | 0; - } - while (carry > 0) { - digits.push(carry % base); - carry = carry / base | 0; - } - } - for (i = 0; input[i] === 0 && i < input.length - 1; ++i) { - output += first; - } - for (i = digits.length - 1; i >= 0; --i) { - output += alphabet[digits[i]]; - } - } - if (maxline) { - var regex = new RegExp(".{1," + maxline + "}", "g"); - output = output.match(regex).join("\r\n"); - } - return output; - }; - api.decode = function(input, alphabet) { - if (typeof input !== "string") { - throw new TypeError('"input" must be a string.'); - } - if (typeof alphabet !== "string") { - throw new TypeError('"alphabet" must be a string.'); - } - var table = _reverseAlphabets[alphabet]; - if (!table) { - table = _reverseAlphabets[alphabet] = []; - for (var i = 0; i < alphabet.length; ++i) { - table[alphabet.charCodeAt(i)] = i; - } - } - input = input.replace(/\s/g, ""); - var base = alphabet.length; - var first = alphabet.charAt(0); - var bytes = [0]; - for (var i = 0; i < input.length; i++) { - var value = table[input.charCodeAt(i)]; - if (value === void 0) { - return; - } - for (var j = 0, carry = value; j < bytes.length; ++j) { - carry += bytes[j] * base; - bytes[j] = carry & 255; - carry >>= 8; - } - while (carry > 0) { - bytes.push(carry & 255); - carry >>= 8; - } - } - for (var k = 0; input[k] === first && k < input.length - 1; ++k) { - bytes.push(0); - } - if (typeof Buffer !== "undefined") { - return Buffer.from(bytes.reverse()); - } - return new Uint8Array(bytes.reverse()); - }; - function _encodeWithByteBuffer(input, alphabet) { - var i = 0; - var base = alphabet.length; - var first = alphabet.charAt(0); - var digits = [0]; - for (i = 0; i < input.length(); ++i) { - for (var j = 0, carry = input.at(i); j < digits.length; ++j) { - carry += digits[j] << 8; - digits[j] = carry % base; - carry = carry / base | 0; - } - while (carry > 0) { - digits.push(carry % base); - carry = carry / base | 0; - } - } - var output = ""; - for (i = 0; input.at(i) === 0 && i < input.length() - 1; ++i) { - output += first; - } - for (i = digits.length - 1; i >= 0; --i) { - output += alphabet[digits[i]]; - } - return output; - } - } -}); - -// node_modules/node-forge/lib/util.js -var require_util13 = __commonJS({ - "node_modules/node-forge/lib/util.js"(exports2, module2) { - var forge = require_forge(); - var baseN = require_baseN(); - var util = module2.exports = forge.util = forge.util || {}; - (function() { - if (typeof process !== "undefined" && process.nextTick && !process.browser) { - util.nextTick = process.nextTick; - if (typeof setImmediate === "function") { - util.setImmediate = setImmediate; - } else { - util.setImmediate = util.nextTick; - } - return; - } - if (typeof setImmediate === "function") { - util.setImmediate = function() { - return setImmediate.apply(void 0, arguments); - }; - util.nextTick = function(callback) { - return setImmediate(callback); - }; - return; - } - util.setImmediate = function(callback) { - setTimeout(callback, 0); - }; - if (typeof window !== "undefined" && typeof window.postMessage === "function") { - let handler3 = function(event) { - if (event.source === window && event.data === msg) { - event.stopPropagation(); - var copy = callbacks.slice(); - callbacks.length = 0; - copy.forEach(function(callback) { - callback(); - }); - } - }; - var handler2 = handler3; - var msg = "forge.setImmediate"; - var callbacks = []; - util.setImmediate = function(callback) { - callbacks.push(callback); - if (callbacks.length === 1) { - window.postMessage(msg, "*"); - } - }; - window.addEventListener("message", handler3, true); - } - if (typeof MutationObserver !== "undefined") { - var now = Date.now(); - var attr = true; - var div = document.createElement("div"); - var callbacks = []; - new MutationObserver(function() { - var copy = callbacks.slice(); - callbacks.length = 0; - copy.forEach(function(callback) { - callback(); - }); - }).observe(div, { attributes: true }); - var oldSetImmediate = util.setImmediate; - util.setImmediate = function(callback) { - if (Date.now() - now > 15) { - now = Date.now(); - oldSetImmediate(callback); - } else { - callbacks.push(callback); - if (callbacks.length === 1) { - div.setAttribute("a", attr = !attr); - } - } - }; - } - util.nextTick = util.setImmediate; - })(); - util.isNodejs = typeof process !== "undefined" && process.versions && process.versions.node; - util.globalScope = (function() { - if (util.isNodejs) { - return global; - } - return typeof self === "undefined" ? window : self; - })(); - util.isArray = Array.isArray || function(x) { - return Object.prototype.toString.call(x) === "[object Array]"; - }; - util.isArrayBuffer = function(x) { - return typeof ArrayBuffer !== "undefined" && x instanceof ArrayBuffer; - }; - util.isArrayBufferView = function(x) { - return x && util.isArrayBuffer(x.buffer) && x.byteLength !== void 0; - }; - function _checkBitsParam(n) { - if (!(n === 8 || n === 16 || n === 24 || n === 32)) { - throw new Error("Only 8, 16, 24, or 32 bits supported: " + n); - } - } - util.ByteBuffer = ByteStringBuffer; - function ByteStringBuffer(b) { - this.data = ""; - this.read = 0; - if (typeof b === "string") { - this.data = b; - } else if (util.isArrayBuffer(b) || util.isArrayBufferView(b)) { - if (typeof Buffer !== "undefined" && b instanceof Buffer) { - this.data = b.toString("binary"); - } else { - var arr = new Uint8Array(b); - try { - this.data = String.fromCharCode.apply(null, arr); - } catch (e) { - for (var i = 0; i < arr.length; ++i) { - this.putByte(arr[i]); - } - } - } - } else if (b instanceof ByteStringBuffer || typeof b === "object" && typeof b.data === "string" && typeof b.read === "number") { - this.data = b.data; - this.read = b.read; - } - this._constructedStringLength = 0; - } - util.ByteStringBuffer = ByteStringBuffer; - var _MAX_CONSTRUCTED_STRING_LENGTH = 4096; - util.ByteStringBuffer.prototype._optimizeConstructedString = function(x) { - this._constructedStringLength += x; - if (this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) { - this.data.substr(0, 1); - this._constructedStringLength = 0; - } - }; - util.ByteStringBuffer.prototype.length = function() { - return this.data.length - this.read; - }; - util.ByteStringBuffer.prototype.isEmpty = function() { - return this.length() <= 0; - }; - util.ByteStringBuffer.prototype.putByte = function(b) { - return this.putBytes(String.fromCharCode(b)); - }; - util.ByteStringBuffer.prototype.fillWithByte = function(b, n) { - b = String.fromCharCode(b); - var d = this.data; - while (n > 0) { - if (n & 1) { - d += b; - } - n >>>= 1; - if (n > 0) { - b += b; - } - } - this.data = d; - this._optimizeConstructedString(n); - return this; - }; - util.ByteStringBuffer.prototype.putBytes = function(bytes) { - this.data += bytes; - this._optimizeConstructedString(bytes.length); - return this; - }; - util.ByteStringBuffer.prototype.putString = function(str) { - return this.putBytes(util.encodeUtf8(str)); - }; - util.ByteStringBuffer.prototype.putInt16 = function(i) { - return this.putBytes( - String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i & 255) - ); - }; - util.ByteStringBuffer.prototype.putInt24 = function(i) { - return this.putBytes( - String.fromCharCode(i >> 16 & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i & 255) - ); - }; - util.ByteStringBuffer.prototype.putInt32 = function(i) { - return this.putBytes( - String.fromCharCode(i >> 24 & 255) + String.fromCharCode(i >> 16 & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i & 255) - ); - }; - util.ByteStringBuffer.prototype.putInt16Le = function(i) { - return this.putBytes( - String.fromCharCode(i & 255) + String.fromCharCode(i >> 8 & 255) - ); - }; - util.ByteStringBuffer.prototype.putInt24Le = function(i) { - return this.putBytes( - String.fromCharCode(i & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i >> 16 & 255) - ); - }; - util.ByteStringBuffer.prototype.putInt32Le = function(i) { - return this.putBytes( - String.fromCharCode(i & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i >> 16 & 255) + String.fromCharCode(i >> 24 & 255) - ); - }; - util.ByteStringBuffer.prototype.putInt = function(i, n) { - _checkBitsParam(n); - var bytes = ""; - do { - n -= 8; - bytes += String.fromCharCode(i >> n & 255); - } while (n > 0); - return this.putBytes(bytes); - }; - util.ByteStringBuffer.prototype.putSignedInt = function(i, n) { - if (i < 0) { - i += 2 << n - 1; - } - return this.putInt(i, n); - }; - util.ByteStringBuffer.prototype.putBuffer = function(buffer) { - return this.putBytes(buffer.getBytes()); - }; - util.ByteStringBuffer.prototype.getByte = function() { - return this.data.charCodeAt(this.read++); - }; - util.ByteStringBuffer.prototype.getInt16 = function() { - var rval = this.data.charCodeAt(this.read) << 8 ^ this.data.charCodeAt(this.read + 1); - this.read += 2; - return rval; - }; - util.ByteStringBuffer.prototype.getInt24 = function() { - var rval = this.data.charCodeAt(this.read) << 16 ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2); - this.read += 3; - return rval; - }; - util.ByteStringBuffer.prototype.getInt32 = function() { - var rval = this.data.charCodeAt(this.read) << 24 ^ this.data.charCodeAt(this.read + 1) << 16 ^ this.data.charCodeAt(this.read + 2) << 8 ^ this.data.charCodeAt(this.read + 3); - this.read += 4; - return rval; - }; - util.ByteStringBuffer.prototype.getInt16Le = function() { - var rval = this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8; - this.read += 2; - return rval; - }; - util.ByteStringBuffer.prototype.getInt24Le = function() { - var rval = this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2) << 16; - this.read += 3; - return rval; - }; - util.ByteStringBuffer.prototype.getInt32Le = function() { - var rval = this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2) << 16 ^ this.data.charCodeAt(this.read + 3) << 24; - this.read += 4; - return rval; - }; - util.ByteStringBuffer.prototype.getInt = function(n) { - _checkBitsParam(n); - var rval = 0; - do { - rval = (rval << 8) + this.data.charCodeAt(this.read++); - n -= 8; - } while (n > 0); - return rval; - }; - util.ByteStringBuffer.prototype.getSignedInt = function(n) { - var x = this.getInt(n); - var max = 2 << n - 2; - if (x >= max) { - x -= max << 1; - } - return x; - }; - util.ByteStringBuffer.prototype.getBytes = function(count) { - var rval; - if (count) { - count = Math.min(this.length(), count); - rval = this.data.slice(this.read, this.read + count); - this.read += count; - } else if (count === 0) { - rval = ""; - } else { - rval = this.read === 0 ? this.data : this.data.slice(this.read); - this.clear(); - } - return rval; - }; - util.ByteStringBuffer.prototype.bytes = function(count) { - return typeof count === "undefined" ? this.data.slice(this.read) : this.data.slice(this.read, this.read + count); - }; - util.ByteStringBuffer.prototype.at = function(i) { - return this.data.charCodeAt(this.read + i); - }; - util.ByteStringBuffer.prototype.setAt = function(i, b) { - this.data = this.data.substr(0, this.read + i) + String.fromCharCode(b) + this.data.substr(this.read + i + 1); - return this; - }; - util.ByteStringBuffer.prototype.last = function() { - return this.data.charCodeAt(this.data.length - 1); - }; - util.ByteStringBuffer.prototype.copy = function() { - var c = util.createBuffer(this.data); - c.read = this.read; - return c; - }; - util.ByteStringBuffer.prototype.compact = function() { - if (this.read > 0) { - this.data = this.data.slice(this.read); - this.read = 0; - } - return this; - }; - util.ByteStringBuffer.prototype.clear = function() { - this.data = ""; - this.read = 0; - return this; - }; - util.ByteStringBuffer.prototype.truncate = function(count) { - var len = Math.max(0, this.length() - count); - this.data = this.data.substr(this.read, len); - this.read = 0; - return this; - }; - util.ByteStringBuffer.prototype.toHex = function() { - var rval = ""; - for (var i = this.read; i < this.data.length; ++i) { - var b = this.data.charCodeAt(i); - if (b < 16) { - rval += "0"; - } - rval += b.toString(16); - } - return rval; - }; - util.ByteStringBuffer.prototype.toString = function() { - return util.decodeUtf8(this.bytes()); - }; - function DataBuffer(b, options) { - options = options || {}; - this.read = options.readOffset || 0; - this.growSize = options.growSize || 1024; - var isArrayBuffer = util.isArrayBuffer(b); - var isArrayBufferView = util.isArrayBufferView(b); - if (isArrayBuffer || isArrayBufferView) { - if (isArrayBuffer) { - this.data = new DataView(b); - } else { - this.data = new DataView(b.buffer, b.byteOffset, b.byteLength); - } - this.write = "writeOffset" in options ? options.writeOffset : this.data.byteLength; - return; - } - this.data = new DataView(new ArrayBuffer(0)); - this.write = 0; - if (b !== null && b !== void 0) { - this.putBytes(b); - } - if ("writeOffset" in options) { - this.write = options.writeOffset; - } - } - util.DataBuffer = DataBuffer; - util.DataBuffer.prototype.length = function() { - return this.write - this.read; - }; - util.DataBuffer.prototype.isEmpty = function() { - return this.length() <= 0; - }; - util.DataBuffer.prototype.accommodate = function(amount, growSize) { - if (this.length() >= amount) { - return this; - } - growSize = Math.max(growSize || this.growSize, amount); - var src = new Uint8Array( - this.data.buffer, - this.data.byteOffset, - this.data.byteLength - ); - var dst = new Uint8Array(this.length() + growSize); - dst.set(src); - this.data = new DataView(dst.buffer); - return this; - }; - util.DataBuffer.prototype.putByte = function(b) { - this.accommodate(1); - this.data.setUint8(this.write++, b); - return this; - }; - util.DataBuffer.prototype.fillWithByte = function(b, n) { - this.accommodate(n); - for (var i = 0; i < n; ++i) { - this.data.setUint8(b); - } - return this; - }; - util.DataBuffer.prototype.putBytes = function(bytes, encoding) { - if (util.isArrayBufferView(bytes)) { - var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength); - var len = src.byteLength - src.byteOffset; - this.accommodate(len); - var dst = new Uint8Array(this.data.buffer, this.write); - dst.set(src); - this.write += len; - return this; - } - if (util.isArrayBuffer(bytes)) { - var src = new Uint8Array(bytes); - this.accommodate(src.byteLength); - var dst = new Uint8Array(this.data.buffer); - dst.set(src, this.write); - this.write += src.byteLength; - return this; - } - if (bytes instanceof util.DataBuffer || typeof bytes === "object" && typeof bytes.read === "number" && typeof bytes.write === "number" && util.isArrayBufferView(bytes.data)) { - var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length()); - this.accommodate(src.byteLength); - var dst = new Uint8Array(bytes.data.byteLength, this.write); - dst.set(src); - this.write += src.byteLength; - return this; - } - if (bytes instanceof util.ByteStringBuffer) { - bytes = bytes.data; - encoding = "binary"; - } - encoding = encoding || "binary"; - if (typeof bytes === "string") { - var view; - if (encoding === "hex") { - this.accommodate(Math.ceil(bytes.length / 2)); - view = new Uint8Array(this.data.buffer, this.write); - this.write += util.binary.hex.decode(bytes, view, this.write); - return this; - } - if (encoding === "base64") { - this.accommodate(Math.ceil(bytes.length / 4) * 3); - view = new Uint8Array(this.data.buffer, this.write); - this.write += util.binary.base64.decode(bytes, view, this.write); - return this; - } - if (encoding === "utf8") { - bytes = util.encodeUtf8(bytes); - encoding = "binary"; - } - if (encoding === "binary" || encoding === "raw") { - this.accommodate(bytes.length); - view = new Uint8Array(this.data.buffer, this.write); - this.write += util.binary.raw.decode(view); - return this; - } - if (encoding === "utf16") { - this.accommodate(bytes.length * 2); - view = new Uint16Array(this.data.buffer, this.write); - this.write += util.text.utf16.encode(view); - return this; - } - throw new Error("Invalid encoding: " + encoding); - } - throw Error("Invalid parameter: " + bytes); - }; - util.DataBuffer.prototype.putBuffer = function(buffer) { - this.putBytes(buffer); - buffer.clear(); - return this; - }; - util.DataBuffer.prototype.putString = function(str) { - return this.putBytes(str, "utf16"); - }; - util.DataBuffer.prototype.putInt16 = function(i) { - this.accommodate(2); - this.data.setInt16(this.write, i); - this.write += 2; - return this; - }; - util.DataBuffer.prototype.putInt24 = function(i) { - this.accommodate(3); - this.data.setInt16(this.write, i >> 8 & 65535); - this.data.setInt8(this.write, i >> 16 & 255); - this.write += 3; - return this; - }; - util.DataBuffer.prototype.putInt32 = function(i) { - this.accommodate(4); - this.data.setInt32(this.write, i); - this.write += 4; - return this; - }; - util.DataBuffer.prototype.putInt16Le = function(i) { - this.accommodate(2); - this.data.setInt16(this.write, i, true); - this.write += 2; - return this; - }; - util.DataBuffer.prototype.putInt24Le = function(i) { - this.accommodate(3); - this.data.setInt8(this.write, i >> 16 & 255); - this.data.setInt16(this.write, i >> 8 & 65535, true); - this.write += 3; - return this; - }; - util.DataBuffer.prototype.putInt32Le = function(i) { - this.accommodate(4); - this.data.setInt32(this.write, i, true); - this.write += 4; - return this; - }; - util.DataBuffer.prototype.putInt = function(i, n) { - _checkBitsParam(n); - this.accommodate(n / 8); - do { - n -= 8; - this.data.setInt8(this.write++, i >> n & 255); - } while (n > 0); - return this; - }; - util.DataBuffer.prototype.putSignedInt = function(i, n) { - _checkBitsParam(n); - this.accommodate(n / 8); - if (i < 0) { - i += 2 << n - 1; - } - return this.putInt(i, n); - }; - util.DataBuffer.prototype.getByte = function() { - return this.data.getInt8(this.read++); - }; - util.DataBuffer.prototype.getInt16 = function() { - var rval = this.data.getInt16(this.read); - this.read += 2; - return rval; - }; - util.DataBuffer.prototype.getInt24 = function() { - var rval = this.data.getInt16(this.read) << 8 ^ this.data.getInt8(this.read + 2); - this.read += 3; - return rval; - }; - util.DataBuffer.prototype.getInt32 = function() { - var rval = this.data.getInt32(this.read); - this.read += 4; - return rval; - }; - util.DataBuffer.prototype.getInt16Le = function() { - var rval = this.data.getInt16(this.read, true); - this.read += 2; - return rval; - }; - util.DataBuffer.prototype.getInt24Le = function() { - var rval = this.data.getInt8(this.read) ^ this.data.getInt16(this.read + 1, true) << 8; - this.read += 3; - return rval; - }; - util.DataBuffer.prototype.getInt32Le = function() { - var rval = this.data.getInt32(this.read, true); - this.read += 4; - return rval; - }; - util.DataBuffer.prototype.getInt = function(n) { - _checkBitsParam(n); - var rval = 0; - do { - rval = (rval << 8) + this.data.getInt8(this.read++); - n -= 8; - } while (n > 0); - return rval; - }; - util.DataBuffer.prototype.getSignedInt = function(n) { - var x = this.getInt(n); - var max = 2 << n - 2; - if (x >= max) { - x -= max << 1; - } - return x; - }; - util.DataBuffer.prototype.getBytes = function(count) { - var rval; - if (count) { - count = Math.min(this.length(), count); - rval = this.data.slice(this.read, this.read + count); - this.read += count; - } else if (count === 0) { - rval = ""; - } else { - rval = this.read === 0 ? this.data : this.data.slice(this.read); - this.clear(); - } - return rval; - }; - util.DataBuffer.prototype.bytes = function(count) { - return typeof count === "undefined" ? this.data.slice(this.read) : this.data.slice(this.read, this.read + count); - }; - util.DataBuffer.prototype.at = function(i) { - return this.data.getUint8(this.read + i); - }; - util.DataBuffer.prototype.setAt = function(i, b) { - this.data.setUint8(i, b); - return this; - }; - util.DataBuffer.prototype.last = function() { - return this.data.getUint8(this.write - 1); - }; - util.DataBuffer.prototype.copy = function() { - return new util.DataBuffer(this); - }; - util.DataBuffer.prototype.compact = function() { - if (this.read > 0) { - var src = new Uint8Array(this.data.buffer, this.read); - var dst = new Uint8Array(src.byteLength); - dst.set(src); - this.data = new DataView(dst); - this.write -= this.read; - this.read = 0; - } - return this; - }; - util.DataBuffer.prototype.clear = function() { - this.data = new DataView(new ArrayBuffer(0)); - this.read = this.write = 0; - return this; - }; - util.DataBuffer.prototype.truncate = function(count) { - this.write = Math.max(0, this.length() - count); - this.read = Math.min(this.read, this.write); - return this; - }; - util.DataBuffer.prototype.toHex = function() { - var rval = ""; - for (var i = this.read; i < this.data.byteLength; ++i) { - var b = this.data.getUint8(i); - if (b < 16) { - rval += "0"; - } - rval += b.toString(16); - } - return rval; - }; - util.DataBuffer.prototype.toString = function(encoding) { - var view = new Uint8Array(this.data, this.read, this.length()); - encoding = encoding || "utf8"; - if (encoding === "binary" || encoding === "raw") { - return util.binary.raw.encode(view); - } - if (encoding === "hex") { - return util.binary.hex.encode(view); - } - if (encoding === "base64") { - return util.binary.base64.encode(view); - } - if (encoding === "utf8") { - return util.text.utf8.decode(view); - } - if (encoding === "utf16") { - return util.text.utf16.decode(view); - } - throw new Error("Invalid encoding: " + encoding); - }; - util.createBuffer = function(input, encoding) { - encoding = encoding || "raw"; - if (input !== void 0 && encoding === "utf8") { - input = util.encodeUtf8(input); - } - return new util.ByteBuffer(input); - }; - util.fillString = function(c, n) { - var s = ""; - while (n > 0) { - if (n & 1) { - s += c; - } - n >>>= 1; - if (n > 0) { - c += c; - } - } - return s; - }; - util.xorBytes = function(s1, s2, n) { - var s3 = ""; - var b = ""; - var t = ""; - var i = 0; - var c = 0; - for (; n > 0; --n, ++i) { - b = s1.charCodeAt(i) ^ s2.charCodeAt(i); - if (c >= 10) { - s3 += t; - t = ""; - c = 0; - } - t += String.fromCharCode(b); - ++c; - } - s3 += t; - return s3; - }; - util.hexToBytes = function(hex) { - var rval = ""; - var i = 0; - if (hex.length & true) { - i = 1; - rval += String.fromCharCode(parseInt(hex[0], 16)); - } - for (; i < hex.length; i += 2) { - rval += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); - } - return rval; - }; - util.bytesToHex = function(bytes) { - return util.createBuffer(bytes).toHex(); - }; - util.int32ToBytes = function(i) { - return String.fromCharCode(i >> 24 & 255) + String.fromCharCode(i >> 16 & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i & 255); - }; - var _base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; - var _base64Idx = [ - /*43 -43 = 0*/ - /*'+', 1, 2, 3,'/' */ - 62, - -1, - -1, - -1, - 63, - /*'0','1','2','3','4','5','6','7','8','9' */ - 52, - 53, - 54, - 55, - 56, - 57, - 58, - 59, - 60, - 61, - /*15, 16, 17,'=', 19, 20, 21 */ - -1, - -1, - -1, - 64, - -1, - -1, - -1, - /*65 - 43 = 22*/ - /*'A','B','C','D','E','F','G','H','I','J','K','L','M', */ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - /*'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */ - 13, - 14, - 15, - 16, - 17, - 18, - 19, - 20, - 21, - 22, - 23, - 24, - 25, - /*91 - 43 = 48 */ - /*48, 49, 50, 51, 52, 53 */ - -1, - -1, - -1, - -1, - -1, - -1, - /*97 - 43 = 54*/ - /*'a','b','c','d','e','f','g','h','i','j','k','l','m' */ - 26, - 27, - 28, - 29, - 30, - 31, - 32, - 33, - 34, - 35, - 36, - 37, - 38, - /*'n','o','p','q','r','s','t','u','v','w','x','y','z' */ - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 46, - 47, - 48, - 49, - 50, - 51 - ]; - var _base58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; - util.encode64 = function(input, maxline) { - var line = ""; - var output = ""; - var chr1, chr2, chr3; - var i = 0; - while (i < input.length) { - chr1 = input.charCodeAt(i++); - chr2 = input.charCodeAt(i++); - chr3 = input.charCodeAt(i++); - line += _base64.charAt(chr1 >> 2); - line += _base64.charAt((chr1 & 3) << 4 | chr2 >> 4); - if (isNaN(chr2)) { - line += "=="; - } else { - line += _base64.charAt((chr2 & 15) << 2 | chr3 >> 6); - line += isNaN(chr3) ? "=" : _base64.charAt(chr3 & 63); - } - if (maxline && line.length > maxline) { - output += line.substr(0, maxline) + "\r\n"; - line = line.substr(maxline); - } - } - output += line; - return output; - }; - util.decode64 = function(input) { - input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); - var output = ""; - var enc1, enc2, enc3, enc4; - var i = 0; - while (i < input.length) { - enc1 = _base64Idx[input.charCodeAt(i++) - 43]; - enc2 = _base64Idx[input.charCodeAt(i++) - 43]; - enc3 = _base64Idx[input.charCodeAt(i++) - 43]; - enc4 = _base64Idx[input.charCodeAt(i++) - 43]; - output += String.fromCharCode(enc1 << 2 | enc2 >> 4); - if (enc3 !== 64) { - output += String.fromCharCode((enc2 & 15) << 4 | enc3 >> 2); - if (enc4 !== 64) { - output += String.fromCharCode((enc3 & 3) << 6 | enc4); - } - } - } - return output; - }; - util.encodeUtf8 = function(str) { - return unescape(encodeURIComponent(str)); - }; - util.decodeUtf8 = function(str) { - return decodeURIComponent(escape(str)); - }; - util.binary = { - raw: {}, - hex: {}, - base64: {}, - base58: {}, - baseN: { - encode: baseN.encode, - decode: baseN.decode - } - }; - util.binary.raw.encode = function(bytes) { - return String.fromCharCode.apply(null, bytes); - }; - util.binary.raw.decode = function(str, output, offset) { - var out = output; - if (!out) { - out = new Uint8Array(str.length); - } - offset = offset || 0; - var j = offset; - for (var i = 0; i < str.length; ++i) { - out[j++] = str.charCodeAt(i); - } - return output ? j - offset : out; - }; - util.binary.hex.encode = util.bytesToHex; - util.binary.hex.decode = function(hex, output, offset) { - var out = output; - if (!out) { - out = new Uint8Array(Math.ceil(hex.length / 2)); - } - offset = offset || 0; - var i = 0, j = offset; - if (hex.length & 1) { - i = 1; - out[j++] = parseInt(hex[0], 16); - } - for (; i < hex.length; i += 2) { - out[j++] = parseInt(hex.substr(i, 2), 16); - } - return output ? j - offset : out; - }; - util.binary.base64.encode = function(input, maxline) { - var line = ""; - var output = ""; - var chr1, chr2, chr3; - var i = 0; - while (i < input.byteLength) { - chr1 = input[i++]; - chr2 = input[i++]; - chr3 = input[i++]; - line += _base64.charAt(chr1 >> 2); - line += _base64.charAt((chr1 & 3) << 4 | chr2 >> 4); - if (isNaN(chr2)) { - line += "=="; - } else { - line += _base64.charAt((chr2 & 15) << 2 | chr3 >> 6); - line += isNaN(chr3) ? "=" : _base64.charAt(chr3 & 63); - } - if (maxline && line.length > maxline) { - output += line.substr(0, maxline) + "\r\n"; - line = line.substr(maxline); - } - } - output += line; - return output; - }; - util.binary.base64.decode = function(input, output, offset) { - var out = output; - if (!out) { - out = new Uint8Array(Math.ceil(input.length / 4) * 3); - } - input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); - offset = offset || 0; - var enc1, enc2, enc3, enc4; - var i = 0, j = offset; - while (i < input.length) { - enc1 = _base64Idx[input.charCodeAt(i++) - 43]; - enc2 = _base64Idx[input.charCodeAt(i++) - 43]; - enc3 = _base64Idx[input.charCodeAt(i++) - 43]; - enc4 = _base64Idx[input.charCodeAt(i++) - 43]; - out[j++] = enc1 << 2 | enc2 >> 4; - if (enc3 !== 64) { - out[j++] = (enc2 & 15) << 4 | enc3 >> 2; - if (enc4 !== 64) { - out[j++] = (enc3 & 3) << 6 | enc4; - } - } - } - return output ? j - offset : out.subarray(0, j); - }; - util.binary.base58.encode = function(input, maxline) { - return util.binary.baseN.encode(input, _base58, maxline); - }; - util.binary.base58.decode = function(input, maxline) { - return util.binary.baseN.decode(input, _base58, maxline); - }; - util.text = { - utf8: {}, - utf16: {} - }; - util.text.utf8.encode = function(str, output, offset) { - str = util.encodeUtf8(str); - var out = output; - if (!out) { - out = new Uint8Array(str.length); - } - offset = offset || 0; - var j = offset; - for (var i = 0; i < str.length; ++i) { - out[j++] = str.charCodeAt(i); - } - return output ? j - offset : out; - }; - util.text.utf8.decode = function(bytes) { - return util.decodeUtf8(String.fromCharCode.apply(null, bytes)); - }; - util.text.utf16.encode = function(str, output, offset) { - var out = output; - if (!out) { - out = new Uint8Array(str.length * 2); - } - var view = new Uint16Array(out.buffer); - offset = offset || 0; - var j = offset; - var k = offset; - for (var i = 0; i < str.length; ++i) { - view[k++] = str.charCodeAt(i); - j += 2; - } - return output ? j - offset : out; - }; - util.text.utf16.decode = function(bytes) { - return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer)); - }; - util.deflate = function(api, bytes, raw) { - bytes = util.decode64(api.deflate(util.encode64(bytes)).rval); - if (raw) { - var start = 2; - var flg = bytes.charCodeAt(1); - if (flg & 32) { - start = 6; - } - bytes = bytes.substring(start, bytes.length - 4); - } - return bytes; - }; - util.inflate = function(api, bytes, raw) { - var rval = api.inflate(util.encode64(bytes)).rval; - return rval === null ? null : util.decode64(rval); - }; - var _setStorageObject = function(api, id, obj) { - if (!api) { - throw new Error("WebStorage not available."); - } - var rval; - if (obj === null) { - rval = api.removeItem(id); - } else { - obj = util.encode64(JSON.stringify(obj)); - rval = api.setItem(id, obj); - } - if (typeof rval !== "undefined" && rval.rval !== true) { - var error3 = new Error(rval.error.message); - error3.id = rval.error.id; - error3.name = rval.error.name; - throw error3; - } - }; - var _getStorageObject = function(api, id) { - if (!api) { - throw new Error("WebStorage not available."); - } - var rval = api.getItem(id); - if (api.init) { - if (rval.rval === null) { - if (rval.error) { - var error3 = new Error(rval.error.message); - error3.id = rval.error.id; - error3.name = rval.error.name; - throw error3; - } - rval = null; - } else { - rval = rval.rval; - } - } - if (rval !== null) { - rval = JSON.parse(util.decode64(rval)); - } - return rval; - }; - var _setItem = function(api, id, key, data) { - var obj = _getStorageObject(api, id); - if (obj === null) { - obj = {}; - } - obj[key] = data; - _setStorageObject(api, id, obj); - }; - var _getItem = function(api, id, key) { - var rval = _getStorageObject(api, id); - if (rval !== null) { - rval = key in rval ? rval[key] : null; - } - return rval; - }; - var _removeItem = function(api, id, key) { - var obj = _getStorageObject(api, id); - if (obj !== null && key in obj) { - delete obj[key]; - var empty = true; - for (var prop in obj) { - empty = false; - break; - } - if (empty) { - obj = null; - } - _setStorageObject(api, id, obj); - } - }; - var _clearItems = function(api, id) { - _setStorageObject(api, id, null); - }; - var _callStorageFunction = function(func, args, location) { - var rval = null; - if (typeof location === "undefined") { - location = ["web", "flash"]; - } - var type; - var done = false; - var exception = null; - for (var idx in location) { - type = location[idx]; - try { - if (type === "flash" || type === "both") { - if (args[0] === null) { - throw new Error("Flash local storage not available."); - } - rval = func.apply(this, args); - done = type === "flash"; - } - if (type === "web" || type === "both") { - args[0] = localStorage; - rval = func.apply(this, args); - done = true; - } - } catch (ex) { - exception = ex; - } - if (done) { - break; - } - } - if (!done) { - throw exception; - } - return rval; - }; - util.setItem = function(api, id, key, data, location) { - _callStorageFunction(_setItem, arguments, location); - }; - util.getItem = function(api, id, key, location) { - return _callStorageFunction(_getItem, arguments, location); - }; - util.removeItem = function(api, id, key, location) { - _callStorageFunction(_removeItem, arguments, location); - }; - util.clearItems = function(api, id, location) { - _callStorageFunction(_clearItems, arguments, location); - }; - util.isEmpty = function(obj) { - for (var prop in obj) { - if (obj.hasOwnProperty(prop)) { - return false; - } - } - return true; - }; - util.format = function(format) { - var re = /%./g; - var match; - var part; - var argi = 0; - var parts = []; - var last = 0; - while (match = re.exec(format)) { - part = format.substring(last, re.lastIndex - 2); - if (part.length > 0) { - parts.push(part); - } - last = re.lastIndex; - var code = match[0][1]; - switch (code) { - case "s": - case "o": - if (argi < arguments.length) { - parts.push(arguments[argi++ + 1]); - } else { - parts.push(""); - } - break; - // FIXME: do proper formatting for numbers, etc - //case 'f': - //case 'd': - case "%": - parts.push("%"); - break; - default: - parts.push("<%" + code + "?>"); - } - } - parts.push(format.substring(last)); - return parts.join(""); - }; - util.formatNumber = function(number, decimals, dec_point, thousands_sep) { - var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals; - var d = dec_point === void 0 ? "," : dec_point; - var t = thousands_sep === void 0 ? "." : thousands_sep, s = n < 0 ? "-" : ""; - var i = parseInt(n = Math.abs(+n || 0).toFixed(c), 10) + ""; - var j = i.length > 3 ? i.length % 3 : 0; - return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); - }; - util.formatSize = function(size) { - if (size >= 1073741824) { - size = util.formatNumber(size / 1073741824, 2, ".", "") + " GiB"; - } else if (size >= 1048576) { - size = util.formatNumber(size / 1048576, 2, ".", "") + " MiB"; - } else if (size >= 1024) { - size = util.formatNumber(size / 1024, 0) + " KiB"; - } else { - size = util.formatNumber(size, 0) + " bytes"; - } - return size; - }; - util.bytesFromIP = function(ip) { - if (ip.indexOf(".") !== -1) { - return util.bytesFromIPv4(ip); - } - if (ip.indexOf(":") !== -1) { - return util.bytesFromIPv6(ip); - } - return null; - }; - util.bytesFromIPv4 = function(ip) { - ip = ip.split("."); - if (ip.length !== 4) { - return null; - } - var b = util.createBuffer(); - for (var i = 0; i < ip.length; ++i) { - var num = parseInt(ip[i], 10); - if (isNaN(num)) { - return null; - } - b.putByte(num); - } - return b.getBytes(); - }; - util.bytesFromIPv6 = function(ip) { - var blanks = 0; - ip = ip.split(":").filter(function(e) { - if (e.length === 0) ++blanks; - return true; - }); - var zeros = (8 - ip.length + blanks) * 2; - var b = util.createBuffer(); - for (var i = 0; i < 8; ++i) { - if (!ip[i] || ip[i].length === 0) { - b.fillWithByte(0, zeros); - zeros = 0; - continue; - } - var bytes = util.hexToBytes(ip[i]); - if (bytes.length < 2) { - b.putByte(0); - } - b.putBytes(bytes); - } - return b.getBytes(); - }; - util.bytesToIP = function(bytes) { - if (bytes.length === 4) { - return util.bytesToIPv4(bytes); - } - if (bytes.length === 16) { - return util.bytesToIPv6(bytes); - } - return null; - }; - util.bytesToIPv4 = function(bytes) { - if (bytes.length !== 4) { - return null; - } - var ip = []; - for (var i = 0; i < bytes.length; ++i) { - ip.push(bytes.charCodeAt(i)); - } - return ip.join("."); - }; - util.bytesToIPv6 = function(bytes) { - if (bytes.length !== 16) { - return null; - } - var ip = []; - var zeroGroups = []; - var zeroMaxGroup = 0; - for (var i = 0; i < bytes.length; i += 2) { - var hex = util.bytesToHex(bytes[i] + bytes[i + 1]); - while (hex[0] === "0" && hex !== "0") { - hex = hex.substr(1); - } - if (hex === "0") { - var last = zeroGroups[zeroGroups.length - 1]; - var idx = ip.length; - if (!last || idx !== last.end + 1) { - zeroGroups.push({ start: idx, end: idx }); - } else { - last.end = idx; - if (last.end - last.start > zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start) { - zeroMaxGroup = zeroGroups.length - 1; - } - } - } - ip.push(hex); - } - if (zeroGroups.length > 0) { - var group = zeroGroups[zeroMaxGroup]; - if (group.end - group.start > 0) { - ip.splice(group.start, group.end - group.start + 1, ""); - if (group.start === 0) { - ip.unshift(""); - } - if (group.end === 7) { - ip.push(""); - } - } - } - return ip.join(":"); - }; - util.estimateCores = function(options, callback) { - if (typeof options === "function") { - callback = options; - options = {}; - } - options = options || {}; - if ("cores" in util && !options.update) { - return callback(null, util.cores); - } - if (typeof navigator !== "undefined" && "hardwareConcurrency" in navigator && navigator.hardwareConcurrency > 0) { - util.cores = navigator.hardwareConcurrency; - return callback(null, util.cores); - } - if (typeof Worker === "undefined") { - util.cores = 1; - return callback(null, util.cores); - } - if (typeof Blob === "undefined") { - util.cores = 2; - return callback(null, util.cores); - } - var blobUrl = URL.createObjectURL(new Blob([ - "(", - function() { - self.addEventListener("message", function(e) { - var st = Date.now(); - var et = st + 4; - while (Date.now() < et) ; - self.postMessage({ st, et }); - }); - }.toString(), - ")()" - ], { type: "application/javascript" })); - sample([], 5, 16); - function sample(max, samples, numWorkers) { - if (samples === 0) { - var avg = Math.floor(max.reduce(function(avg2, x) { - return avg2 + x; - }, 0) / max.length); - util.cores = Math.max(1, avg); - URL.revokeObjectURL(blobUrl); - return callback(null, util.cores); - } - map(numWorkers, function(err, results) { - max.push(reduce(numWorkers, results)); - sample(max, samples - 1, numWorkers); - }); - } - function map(numWorkers, callback2) { - var workers = []; - var results = []; - for (var i = 0; i < numWorkers; ++i) { - var worker = new Worker(blobUrl); - worker.addEventListener("message", function(e) { - results.push(e.data); - if (results.length === numWorkers) { - for (var i2 = 0; i2 < numWorkers; ++i2) { - workers[i2].terminate(); - } - callback2(null, results); - } - }); - workers.push(worker); - } - for (var i = 0; i < numWorkers; ++i) { - workers[i].postMessage(i); - } - } - function reduce(numWorkers, results) { - var overlaps = []; - for (var n = 0; n < numWorkers; ++n) { - var r1 = results[n]; - var overlap = overlaps[n] = []; - for (var i = 0; i < numWorkers; ++i) { - if (n === i) { - continue; - } - var r2 = results[i]; - if (r1.st > r2.st && r1.st < r2.et || r2.st > r1.st && r2.st < r1.et) { - overlap.push(i); - } - } - } - return overlaps.reduce(function(max, overlap2) { - return Math.max(max, overlap2.length); - }, 0); - } - }; - } -}); - -// node_modules/node-forge/lib/cipher.js -var require_cipher = __commonJS({ - "node_modules/node-forge/lib/cipher.js"(exports2, module2) { - var forge = require_forge(); - require_util13(); - module2.exports = forge.cipher = forge.cipher || {}; - forge.cipher.algorithms = forge.cipher.algorithms || {}; - forge.cipher.createCipher = function(algorithm, key) { - var api = algorithm; - if (typeof api === "string") { - api = forge.cipher.getAlgorithm(api); - if (api) { - api = api(); - } - } - if (!api) { - throw new Error("Unsupported algorithm: " + algorithm); - } - return new forge.cipher.BlockCipher({ - algorithm: api, - key, - decrypt: false - }); - }; - forge.cipher.createDecipher = function(algorithm, key) { - var api = algorithm; - if (typeof api === "string") { - api = forge.cipher.getAlgorithm(api); - if (api) { - api = api(); - } - } - if (!api) { - throw new Error("Unsupported algorithm: " + algorithm); - } - return new forge.cipher.BlockCipher({ - algorithm: api, - key, - decrypt: true - }); - }; - forge.cipher.registerAlgorithm = function(name, algorithm) { - name = name.toUpperCase(); - forge.cipher.algorithms[name] = algorithm; - }; - forge.cipher.getAlgorithm = function(name) { - name = name.toUpperCase(); - if (name in forge.cipher.algorithms) { - return forge.cipher.algorithms[name]; - } - return null; - }; - var BlockCipher = forge.cipher.BlockCipher = function(options) { - this.algorithm = options.algorithm; - this.mode = this.algorithm.mode; - this.blockSize = this.mode.blockSize; - this._finish = false; - this._input = null; - this.output = null; - this._op = options.decrypt ? this.mode.decrypt : this.mode.encrypt; - this._decrypt = options.decrypt; - this.algorithm.initialize(options); - }; - BlockCipher.prototype.start = function(options) { - options = options || {}; - var opts = {}; - for (var key in options) { - opts[key] = options[key]; - } - opts.decrypt = this._decrypt; - this._finish = false; - this._input = forge.util.createBuffer(); - this.output = options.output || forge.util.createBuffer(); - this.mode.start(opts); - }; - BlockCipher.prototype.update = function(input) { - if (input) { - this._input.putBuffer(input); - } - while (!this._op.call(this.mode, this._input, this.output, this._finish) && !this._finish) { - } - this._input.compact(); - }; - BlockCipher.prototype.finish = function(pad) { - if (pad && (this.mode.name === "ECB" || this.mode.name === "CBC")) { - this.mode.pad = function(input) { - return pad(this.blockSize, input, false); - }; - this.mode.unpad = function(output) { - return pad(this.blockSize, output, true); - }; - } - var options = {}; - options.decrypt = this._decrypt; - options.overflow = this._input.length() % this.blockSize; - if (!this._decrypt && this.mode.pad) { - if (!this.mode.pad(this._input, options)) { - return false; - } - } - this._finish = true; - this.update(); - if (this._decrypt && this.mode.unpad) { - if (!this.mode.unpad(this.output, options)) { - return false; - } - } - if (this.mode.afterFinish) { - if (!this.mode.afterFinish(this.output, options)) { - return false; - } - } - return true; - }; - } -}); - -// node_modules/node-forge/lib/cipherModes.js -var require_cipherModes = __commonJS({ - "node_modules/node-forge/lib/cipherModes.js"(exports2, module2) { - var forge = require_forge(); - require_util13(); - forge.cipher = forge.cipher || {}; - var modes = module2.exports = forge.cipher.modes = forge.cipher.modes || {}; - modes.ecb = function(options) { - options = options || {}; - this.name = "ECB"; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = new Array(this._ints); - this._outBlock = new Array(this._ints); - }; - modes.ecb.prototype.start = function(options) { - }; - modes.ecb.prototype.encrypt = function(input, output, finish) { - if (input.length() < this.blockSize && !(finish && input.length() > 0)) { - return true; - } - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = input.getInt32(); - } - this.cipher.encrypt(this._inBlock, this._outBlock); - for (var i = 0; i < this._ints; ++i) { - output.putInt32(this._outBlock[i]); - } - }; - modes.ecb.prototype.decrypt = function(input, output, finish) { - if (input.length() < this.blockSize && !(finish && input.length() > 0)) { - return true; - } - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = input.getInt32(); - } - this.cipher.decrypt(this._inBlock, this._outBlock); - for (var i = 0; i < this._ints; ++i) { - output.putInt32(this._outBlock[i]); - } - }; - modes.ecb.prototype.pad = function(input, options) { - var padding = input.length() === this.blockSize ? this.blockSize : this.blockSize - input.length(); - input.fillWithByte(padding, padding); - return true; - }; - modes.ecb.prototype.unpad = function(output, options) { - if (options.overflow > 0) { - return false; - } - var len = output.length(); - var count = output.at(len - 1); - if (count > this.blockSize << 2) { - return false; - } - output.truncate(count); - return true; - }; - modes.cbc = function(options) { - options = options || {}; - this.name = "CBC"; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = new Array(this._ints); - this._outBlock = new Array(this._ints); - }; - modes.cbc.prototype.start = function(options) { - if (options.iv === null) { - if (!this._prev) { - throw new Error("Invalid IV parameter."); - } - this._iv = this._prev.slice(0); - } else if (!("iv" in options)) { - throw new Error("Invalid IV parameter."); - } else { - this._iv = transformIV(options.iv, this.blockSize); - this._prev = this._iv.slice(0); - } - }; - modes.cbc.prototype.encrypt = function(input, output, finish) { - if (input.length() < this.blockSize && !(finish && input.length() > 0)) { - return true; - } - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = this._prev[i] ^ input.getInt32(); - } - this.cipher.encrypt(this._inBlock, this._outBlock); - for (var i = 0; i < this._ints; ++i) { - output.putInt32(this._outBlock[i]); - } - this._prev = this._outBlock; - }; - modes.cbc.prototype.decrypt = function(input, output, finish) { - if (input.length() < this.blockSize && !(finish && input.length() > 0)) { - return true; - } - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = input.getInt32(); - } - this.cipher.decrypt(this._inBlock, this._outBlock); - for (var i = 0; i < this._ints; ++i) { - output.putInt32(this._prev[i] ^ this._outBlock[i]); - } - this._prev = this._inBlock.slice(0); - }; - modes.cbc.prototype.pad = function(input, options) { - var padding = input.length() === this.blockSize ? this.blockSize : this.blockSize - input.length(); - input.fillWithByte(padding, padding); - return true; - }; - modes.cbc.prototype.unpad = function(output, options) { - if (options.overflow > 0) { - return false; - } - var len = output.length(); - var count = output.at(len - 1); - if (count > this.blockSize << 2) { - return false; - } - output.truncate(count); - return true; - }; - modes.cfb = function(options) { - options = options || {}; - this.name = "CFB"; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = null; - this._outBlock = new Array(this._ints); - this._partialBlock = new Array(this._ints); - this._partialOutput = forge.util.createBuffer(); - this._partialBytes = 0; - }; - modes.cfb.prototype.start = function(options) { - if (!("iv" in options)) { - throw new Error("Invalid IV parameter."); - } - this._iv = transformIV(options.iv, this.blockSize); - this._inBlock = this._iv.slice(0); - this._partialBytes = 0; - }; - modes.cfb.prototype.encrypt = function(input, output, finish) { - var inputLength = input.length(); - if (inputLength === 0) { - return true; - } - this.cipher.encrypt(this._inBlock, this._outBlock); - if (this._partialBytes === 0 && inputLength >= this.blockSize) { - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = input.getInt32() ^ this._outBlock[i]; - output.putInt32(this._inBlock[i]); - } - return; - } - var partialBytes = (this.blockSize - inputLength) % this.blockSize; - if (partialBytes > 0) { - partialBytes = this.blockSize - partialBytes; - } - this._partialOutput.clear(); - for (var i = 0; i < this._ints; ++i) { - this._partialBlock[i] = input.getInt32() ^ this._outBlock[i]; - this._partialOutput.putInt32(this._partialBlock[i]); - } - if (partialBytes > 0) { - input.read -= this.blockSize; - } else { - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = this._partialBlock[i]; - } - } - if (this._partialBytes > 0) { - this._partialOutput.getBytes(this._partialBytes); - } - if (partialBytes > 0 && !finish) { - output.putBytes(this._partialOutput.getBytes( - partialBytes - this._partialBytes - )); - this._partialBytes = partialBytes; - return true; - } - output.putBytes(this._partialOutput.getBytes( - inputLength - this._partialBytes - )); - this._partialBytes = 0; - }; - modes.cfb.prototype.decrypt = function(input, output, finish) { - var inputLength = input.length(); - if (inputLength === 0) { - return true; - } - this.cipher.encrypt(this._inBlock, this._outBlock); - if (this._partialBytes === 0 && inputLength >= this.blockSize) { - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = input.getInt32(); - output.putInt32(this._inBlock[i] ^ this._outBlock[i]); - } - return; - } - var partialBytes = (this.blockSize - inputLength) % this.blockSize; - if (partialBytes > 0) { - partialBytes = this.blockSize - partialBytes; - } - this._partialOutput.clear(); - for (var i = 0; i < this._ints; ++i) { - this._partialBlock[i] = input.getInt32(); - this._partialOutput.putInt32(this._partialBlock[i] ^ this._outBlock[i]); - } - if (partialBytes > 0) { - input.read -= this.blockSize; - } else { - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = this._partialBlock[i]; - } - } - if (this._partialBytes > 0) { - this._partialOutput.getBytes(this._partialBytes); - } - if (partialBytes > 0 && !finish) { - output.putBytes(this._partialOutput.getBytes( - partialBytes - this._partialBytes - )); - this._partialBytes = partialBytes; - return true; - } - output.putBytes(this._partialOutput.getBytes( - inputLength - this._partialBytes - )); - this._partialBytes = 0; - }; - modes.ofb = function(options) { - options = options || {}; - this.name = "OFB"; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = null; - this._outBlock = new Array(this._ints); - this._partialOutput = forge.util.createBuffer(); - this._partialBytes = 0; - }; - modes.ofb.prototype.start = function(options) { - if (!("iv" in options)) { - throw new Error("Invalid IV parameter."); - } - this._iv = transformIV(options.iv, this.blockSize); - this._inBlock = this._iv.slice(0); - this._partialBytes = 0; - }; - modes.ofb.prototype.encrypt = function(input, output, finish) { - var inputLength = input.length(); - if (input.length() === 0) { - return true; - } - this.cipher.encrypt(this._inBlock, this._outBlock); - if (this._partialBytes === 0 && inputLength >= this.blockSize) { - for (var i = 0; i < this._ints; ++i) { - output.putInt32(input.getInt32() ^ this._outBlock[i]); - this._inBlock[i] = this._outBlock[i]; - } - return; - } - var partialBytes = (this.blockSize - inputLength) % this.blockSize; - if (partialBytes > 0) { - partialBytes = this.blockSize - partialBytes; - } - this._partialOutput.clear(); - for (var i = 0; i < this._ints; ++i) { - this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); - } - if (partialBytes > 0) { - input.read -= this.blockSize; - } else { - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = this._outBlock[i]; - } - } - if (this._partialBytes > 0) { - this._partialOutput.getBytes(this._partialBytes); - } - if (partialBytes > 0 && !finish) { - output.putBytes(this._partialOutput.getBytes( - partialBytes - this._partialBytes - )); - this._partialBytes = partialBytes; - return true; - } - output.putBytes(this._partialOutput.getBytes( - inputLength - this._partialBytes - )); - this._partialBytes = 0; - }; - modes.ofb.prototype.decrypt = modes.ofb.prototype.encrypt; - modes.ctr = function(options) { - options = options || {}; - this.name = "CTR"; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = null; - this._outBlock = new Array(this._ints); - this._partialOutput = forge.util.createBuffer(); - this._partialBytes = 0; - }; - modes.ctr.prototype.start = function(options) { - if (!("iv" in options)) { - throw new Error("Invalid IV parameter."); - } - this._iv = transformIV(options.iv, this.blockSize); - this._inBlock = this._iv.slice(0); - this._partialBytes = 0; - }; - modes.ctr.prototype.encrypt = function(input, output, finish) { - var inputLength = input.length(); - if (inputLength === 0) { - return true; - } - this.cipher.encrypt(this._inBlock, this._outBlock); - if (this._partialBytes === 0 && inputLength >= this.blockSize) { - for (var i = 0; i < this._ints; ++i) { - output.putInt32(input.getInt32() ^ this._outBlock[i]); - } - } else { - var partialBytes = (this.blockSize - inputLength) % this.blockSize; - if (partialBytes > 0) { - partialBytes = this.blockSize - partialBytes; - } - this._partialOutput.clear(); - for (var i = 0; i < this._ints; ++i) { - this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); - } - if (partialBytes > 0) { - input.read -= this.blockSize; - } - if (this._partialBytes > 0) { - this._partialOutput.getBytes(this._partialBytes); - } - if (partialBytes > 0 && !finish) { - output.putBytes(this._partialOutput.getBytes( - partialBytes - this._partialBytes - )); - this._partialBytes = partialBytes; - return true; - } - output.putBytes(this._partialOutput.getBytes( - inputLength - this._partialBytes - )); - this._partialBytes = 0; - } - inc32(this._inBlock); - }; - modes.ctr.prototype.decrypt = modes.ctr.prototype.encrypt; - modes.gcm = function(options) { - options = options || {}; - this.name = "GCM"; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = new Array(this._ints); - this._outBlock = new Array(this._ints); - this._partialOutput = forge.util.createBuffer(); - this._partialBytes = 0; - this._R = 3774873600; - }; - modes.gcm.prototype.start = function(options) { - if (!("iv" in options)) { - throw new Error("Invalid IV parameter."); - } - var iv = forge.util.createBuffer(options.iv); - this._cipherLength = 0; - var additionalData; - if ("additionalData" in options) { - additionalData = forge.util.createBuffer(options.additionalData); - } else { - additionalData = forge.util.createBuffer(); - } - if ("tagLength" in options) { - this._tagLength = options.tagLength; - } else { - this._tagLength = 128; - } - this._tag = null; - if (options.decrypt) { - this._tag = forge.util.createBuffer(options.tag).getBytes(); - if (this._tag.length !== this._tagLength / 8) { - throw new Error("Authentication tag does not match tag length."); - } - } - this._hashBlock = new Array(this._ints); - this.tag = null; - this._hashSubkey = new Array(this._ints); - this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey); - this.componentBits = 4; - this._m = this.generateHashTable(this._hashSubkey, this.componentBits); - var ivLength = iv.length(); - if (ivLength === 12) { - this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1]; - } else { - this._j0 = [0, 0, 0, 0]; - while (iv.length() > 0) { - this._j0 = this.ghash( - this._hashSubkey, - this._j0, - [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()] - ); - } - this._j0 = this.ghash( - this._hashSubkey, - this._j0, - [0, 0].concat(from64To32(ivLength * 8)) - ); - } - this._inBlock = this._j0.slice(0); - inc32(this._inBlock); - this._partialBytes = 0; - additionalData = forge.util.createBuffer(additionalData); - this._aDataLength = from64To32(additionalData.length() * 8); - var overflow = additionalData.length() % this.blockSize; - if (overflow) { - additionalData.fillWithByte(0, this.blockSize - overflow); - } - this._s = [0, 0, 0, 0]; - while (additionalData.length() > 0) { - this._s = this.ghash(this._hashSubkey, this._s, [ - additionalData.getInt32(), - additionalData.getInt32(), - additionalData.getInt32(), - additionalData.getInt32() - ]); - } - }; - modes.gcm.prototype.encrypt = function(input, output, finish) { - var inputLength = input.length(); - if (inputLength === 0) { - return true; - } - this.cipher.encrypt(this._inBlock, this._outBlock); - if (this._partialBytes === 0 && inputLength >= this.blockSize) { - for (var i = 0; i < this._ints; ++i) { - output.putInt32(this._outBlock[i] ^= input.getInt32()); - } - this._cipherLength += this.blockSize; - } else { - var partialBytes = (this.blockSize - inputLength) % this.blockSize; - if (partialBytes > 0) { - partialBytes = this.blockSize - partialBytes; - } - this._partialOutput.clear(); - for (var i = 0; i < this._ints; ++i) { - this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); - } - if (partialBytes <= 0 || finish) { - if (finish) { - var overflow = inputLength % this.blockSize; - this._cipherLength += overflow; - this._partialOutput.truncate(this.blockSize - overflow); - } else { - this._cipherLength += this.blockSize; - } - for (var i = 0; i < this._ints; ++i) { - this._outBlock[i] = this._partialOutput.getInt32(); - } - this._partialOutput.read -= this.blockSize; - } - if (this._partialBytes > 0) { - this._partialOutput.getBytes(this._partialBytes); - } - if (partialBytes > 0 && !finish) { - input.read -= this.blockSize; - output.putBytes(this._partialOutput.getBytes( - partialBytes - this._partialBytes - )); - this._partialBytes = partialBytes; - return true; - } - output.putBytes(this._partialOutput.getBytes( - inputLength - this._partialBytes - )); - this._partialBytes = 0; - } - this._s = this.ghash(this._hashSubkey, this._s, this._outBlock); - inc32(this._inBlock); - }; - modes.gcm.prototype.decrypt = function(input, output, finish) { - var inputLength = input.length(); - if (inputLength < this.blockSize && !(finish && inputLength > 0)) { - return true; - } - this.cipher.encrypt(this._inBlock, this._outBlock); - inc32(this._inBlock); - this._hashBlock[0] = input.getInt32(); - this._hashBlock[1] = input.getInt32(); - this._hashBlock[2] = input.getInt32(); - this._hashBlock[3] = input.getInt32(); - this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock); - for (var i = 0; i < this._ints; ++i) { - output.putInt32(this._outBlock[i] ^ this._hashBlock[i]); - } - if (inputLength < this.blockSize) { - this._cipherLength += inputLength % this.blockSize; - } else { - this._cipherLength += this.blockSize; - } - }; - modes.gcm.prototype.afterFinish = function(output, options) { - var rval = true; - if (options.decrypt && options.overflow) { - output.truncate(this.blockSize - options.overflow); - } - this.tag = forge.util.createBuffer(); - var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8)); - this._s = this.ghash(this._hashSubkey, this._s, lengths); - var tag = []; - this.cipher.encrypt(this._j0, tag); - for (var i = 0; i < this._ints; ++i) { - this.tag.putInt32(this._s[i] ^ tag[i]); - } - this.tag.truncate(this.tag.length() % (this._tagLength / 8)); - if (options.decrypt && this.tag.bytes() !== this._tag) { - rval = false; - } - return rval; - }; - modes.gcm.prototype.multiply = function(x, y) { - var z_i = [0, 0, 0, 0]; - var v_i = y.slice(0); - for (var i = 0; i < 128; ++i) { - var x_i = x[i / 32 | 0] & 1 << 31 - i % 32; - if (x_i) { - z_i[0] ^= v_i[0]; - z_i[1] ^= v_i[1]; - z_i[2] ^= v_i[2]; - z_i[3] ^= v_i[3]; - } - this.pow(v_i, v_i); - } - return z_i; - }; - modes.gcm.prototype.pow = function(x, out) { - var lsb = x[3] & 1; - for (var i = 3; i > 0; --i) { - out[i] = x[i] >>> 1 | (x[i - 1] & 1) << 31; - } - out[0] = x[0] >>> 1; - if (lsb) { - out[0] ^= this._R; - } - }; - modes.gcm.prototype.tableMultiply = function(x) { - var z = [0, 0, 0, 0]; - for (var i = 0; i < 32; ++i) { - var idx = i / 8 | 0; - var x_i = x[idx] >>> (7 - i % 8) * 4 & 15; - var ah = this._m[i][x_i]; - z[0] ^= ah[0]; - z[1] ^= ah[1]; - z[2] ^= ah[2]; - z[3] ^= ah[3]; - } - return z; - }; - modes.gcm.prototype.ghash = function(h, y, x) { - y[0] ^= x[0]; - y[1] ^= x[1]; - y[2] ^= x[2]; - y[3] ^= x[3]; - return this.tableMultiply(y); - }; - modes.gcm.prototype.generateHashTable = function(h, bits) { - var multiplier = 8 / bits; - var perInt = 4 * multiplier; - var size = 16 * multiplier; - var m = new Array(size); - for (var i = 0; i < size; ++i) { - var tmp = [0, 0, 0, 0]; - var idx = i / perInt | 0; - var shft = (perInt - 1 - i % perInt) * bits; - tmp[idx] = 1 << bits - 1 << shft; - m[i] = this.generateSubHashTable(this.multiply(tmp, h), bits); - } - return m; - }; - modes.gcm.prototype.generateSubHashTable = function(mid, bits) { - var size = 1 << bits; - var half = size >>> 1; - var m = new Array(size); - m[half] = mid.slice(0); - var i = half >>> 1; - while (i > 0) { - this.pow(m[2 * i], m[i] = []); - i >>= 1; - } - i = 2; - while (i < half) { - for (var j = 1; j < i; ++j) { - var m_i = m[i]; - var m_j = m[j]; - m[i + j] = [ - m_i[0] ^ m_j[0], - m_i[1] ^ m_j[1], - m_i[2] ^ m_j[2], - m_i[3] ^ m_j[3] - ]; - } - i *= 2; - } - m[0] = [0, 0, 0, 0]; - for (i = half + 1; i < size; ++i) { - var c = m[i ^ half]; - m[i] = [mid[0] ^ c[0], mid[1] ^ c[1], mid[2] ^ c[2], mid[3] ^ c[3]]; - } - return m; - }; - function transformIV(iv, blockSize) { - if (typeof iv === "string") { - iv = forge.util.createBuffer(iv); - } - if (forge.util.isArray(iv) && iv.length > 4) { - var tmp = iv; - iv = forge.util.createBuffer(); - for (var i = 0; i < tmp.length; ++i) { - iv.putByte(tmp[i]); - } - } - if (iv.length() < blockSize) { - throw new Error( - "Invalid IV length; got " + iv.length() + " bytes and expected " + blockSize + " bytes." - ); - } - if (!forge.util.isArray(iv)) { - var ints = []; - var blocks = blockSize / 4; - for (var i = 0; i < blocks; ++i) { - ints.push(iv.getInt32()); - } - iv = ints; - } - return iv; - } - function inc32(block) { - block[block.length - 1] = block[block.length - 1] + 1 & 4294967295; - } - function from64To32(num) { - return [num / 4294967296 | 0, num & 4294967295]; - } - } -}); - -// node_modules/node-forge/lib/aes.js -var require_aes = __commonJS({ - "node_modules/node-forge/lib/aes.js"(exports2, module2) { - var forge = require_forge(); - require_cipher(); - require_cipherModes(); - require_util13(); - module2.exports = forge.aes = forge.aes || {}; - forge.aes.startEncrypting = function(key, iv, output, mode) { - var cipher = _createCipher({ - key, - output, - decrypt: false, - mode - }); - cipher.start(iv); - return cipher; - }; - forge.aes.createEncryptionCipher = function(key, mode) { - return _createCipher({ - key, - output: null, - decrypt: false, - mode - }); - }; - forge.aes.startDecrypting = function(key, iv, output, mode) { - var cipher = _createCipher({ - key, - output, - decrypt: true, - mode - }); - cipher.start(iv); - return cipher; - }; - forge.aes.createDecryptionCipher = function(key, mode) { - return _createCipher({ - key, - output: null, - decrypt: true, - mode - }); - }; - forge.aes.Algorithm = function(name, mode) { - if (!init) { - initialize(); - } - var self2 = this; - self2.name = name; - self2.mode = new mode({ - blockSize: 16, - cipher: { - encrypt: function(inBlock, outBlock) { - return _updateBlock(self2._w, inBlock, outBlock, false); - }, - decrypt: function(inBlock, outBlock) { - return _updateBlock(self2._w, inBlock, outBlock, true); - } - } - }); - self2._init = false; - }; - forge.aes.Algorithm.prototype.initialize = function(options) { - if (this._init) { - return; - } - var key = options.key; - var tmp; - if (typeof key === "string" && (key.length === 16 || key.length === 24 || key.length === 32)) { - key = forge.util.createBuffer(key); - } else if (forge.util.isArray(key) && (key.length === 16 || key.length === 24 || key.length === 32)) { - tmp = key; - key = forge.util.createBuffer(); - for (var i = 0; i < tmp.length; ++i) { - key.putByte(tmp[i]); - } - } - if (!forge.util.isArray(key)) { - tmp = key; - key = []; - var len = tmp.length(); - if (len === 16 || len === 24 || len === 32) { - len = len >>> 2; - for (var i = 0; i < len; ++i) { - key.push(tmp.getInt32()); - } - } - } - if (!forge.util.isArray(key) || !(key.length === 4 || key.length === 6 || key.length === 8)) { - throw new Error("Invalid key parameter."); - } - var mode = this.mode.name; - var encryptOp = ["CFB", "OFB", "CTR", "GCM"].indexOf(mode) !== -1; - this._w = _expandKey(key, options.decrypt && !encryptOp); - this._init = true; - }; - forge.aes._expandKey = function(key, decrypt) { - if (!init) { - initialize(); - } - return _expandKey(key, decrypt); - }; - forge.aes._updateBlock = _updateBlock; - registerAlgorithm("AES-ECB", forge.cipher.modes.ecb); - registerAlgorithm("AES-CBC", forge.cipher.modes.cbc); - registerAlgorithm("AES-CFB", forge.cipher.modes.cfb); - registerAlgorithm("AES-OFB", forge.cipher.modes.ofb); - registerAlgorithm("AES-CTR", forge.cipher.modes.ctr); - registerAlgorithm("AES-GCM", forge.cipher.modes.gcm); - function registerAlgorithm(name, mode) { - var factory = function() { - return new forge.aes.Algorithm(name, mode); - }; - forge.cipher.registerAlgorithm(name, factory); - } - var init = false; - var Nb = 4; - var sbox; - var isbox; - var rcon; - var mix; - var imix; - function initialize() { - init = true; - rcon = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54]; - var xtime = new Array(256); - for (var i = 0; i < 128; ++i) { - xtime[i] = i << 1; - xtime[i + 128] = i + 128 << 1 ^ 283; - } - sbox = new Array(256); - isbox = new Array(256); - mix = new Array(4); - imix = new Array(4); - for (var i = 0; i < 4; ++i) { - mix[i] = new Array(256); - imix[i] = new Array(256); - } - var e = 0, ei = 0, e2, e4, e8, sx, sx2, me, ime; - for (var i = 0; i < 256; ++i) { - sx = ei ^ ei << 1 ^ ei << 2 ^ ei << 3 ^ ei << 4; - sx = sx >> 8 ^ sx & 255 ^ 99; - sbox[e] = sx; - isbox[sx] = e; - sx2 = xtime[sx]; - e2 = xtime[e]; - e4 = xtime[e2]; - e8 = xtime[e4]; - me = sx2 << 24 ^ // 2 - sx << 16 ^ // 1 - sx << 8 ^ // 1 - (sx ^ sx2); - ime = (e2 ^ e4 ^ e8) << 24 ^ // E (14) - (e ^ e8) << 16 ^ // 9 - (e ^ e4 ^ e8) << 8 ^ // D (13) - (e ^ e2 ^ e8); - for (var n = 0; n < 4; ++n) { - mix[n][e] = me; - imix[n][sx] = ime; - me = me << 24 | me >>> 8; - ime = ime << 24 | ime >>> 8; - } - if (e === 0) { - e = ei = 1; - } else { - e = e2 ^ xtime[xtime[xtime[e2 ^ e8]]]; - ei ^= xtime[xtime[ei]]; - } - } - } - function _expandKey(key, decrypt) { - var w = key.slice(0); - var temp, iNk = 1; - var Nk = w.length; - var Nr1 = Nk + 6 + 1; - var end = Nb * Nr1; - for (var i = Nk; i < end; ++i) { - temp = w[i - 1]; - if (i % Nk === 0) { - temp = sbox[temp >>> 16 & 255] << 24 ^ sbox[temp >>> 8 & 255] << 16 ^ sbox[temp & 255] << 8 ^ sbox[temp >>> 24] ^ rcon[iNk] << 24; - iNk++; - } else if (Nk > 6 && i % Nk === 4) { - temp = sbox[temp >>> 24] << 24 ^ sbox[temp >>> 16 & 255] << 16 ^ sbox[temp >>> 8 & 255] << 8 ^ sbox[temp & 255]; - } - w[i] = w[i - Nk] ^ temp; - } - if (decrypt) { - var tmp; - var m0 = imix[0]; - var m1 = imix[1]; - var m2 = imix[2]; - var m3 = imix[3]; - var wnew = w.slice(0); - end = w.length; - for (var i = 0, wi = end - Nb; i < end; i += Nb, wi -= Nb) { - if (i === 0 || i === end - Nb) { - wnew[i] = w[wi]; - wnew[i + 1] = w[wi + 3]; - wnew[i + 2] = w[wi + 2]; - wnew[i + 3] = w[wi + 1]; - } else { - for (var n = 0; n < Nb; ++n) { - tmp = w[wi + n]; - wnew[i + (3 & -n)] = m0[sbox[tmp >>> 24]] ^ m1[sbox[tmp >>> 16 & 255]] ^ m2[sbox[tmp >>> 8 & 255]] ^ m3[sbox[tmp & 255]]; - } - } - } - w = wnew; - } - return w; - } - function _updateBlock(w, input, output, decrypt) { - var Nr = w.length / 4 - 1; - var m0, m1, m2, m3, sub; - if (decrypt) { - m0 = imix[0]; - m1 = imix[1]; - m2 = imix[2]; - m3 = imix[3]; - sub = isbox; - } else { - m0 = mix[0]; - m1 = mix[1]; - m2 = mix[2]; - m3 = mix[3]; - sub = sbox; - } - var a, b, c, d, a2, b2, c2; - a = input[0] ^ w[0]; - b = input[decrypt ? 3 : 1] ^ w[1]; - c = input[2] ^ w[2]; - d = input[decrypt ? 1 : 3] ^ w[3]; - var i = 3; - for (var round = 1; round < Nr; ++round) { - a2 = m0[a >>> 24] ^ m1[b >>> 16 & 255] ^ m2[c >>> 8 & 255] ^ m3[d & 255] ^ w[++i]; - b2 = m0[b >>> 24] ^ m1[c >>> 16 & 255] ^ m2[d >>> 8 & 255] ^ m3[a & 255] ^ w[++i]; - c2 = m0[c >>> 24] ^ m1[d >>> 16 & 255] ^ m2[a >>> 8 & 255] ^ m3[b & 255] ^ w[++i]; - d = m0[d >>> 24] ^ m1[a >>> 16 & 255] ^ m2[b >>> 8 & 255] ^ m3[c & 255] ^ w[++i]; - a = a2; - b = b2; - c = c2; - } - output[0] = sub[a >>> 24] << 24 ^ sub[b >>> 16 & 255] << 16 ^ sub[c >>> 8 & 255] << 8 ^ sub[d & 255] ^ w[++i]; - output[decrypt ? 3 : 1] = sub[b >>> 24] << 24 ^ sub[c >>> 16 & 255] << 16 ^ sub[d >>> 8 & 255] << 8 ^ sub[a & 255] ^ w[++i]; - output[2] = sub[c >>> 24] << 24 ^ sub[d >>> 16 & 255] << 16 ^ sub[a >>> 8 & 255] << 8 ^ sub[b & 255] ^ w[++i]; - output[decrypt ? 1 : 3] = sub[d >>> 24] << 24 ^ sub[a >>> 16 & 255] << 16 ^ sub[b >>> 8 & 255] << 8 ^ sub[c & 255] ^ w[++i]; - } - function _createCipher(options) { - options = options || {}; - var mode = (options.mode || "CBC").toUpperCase(); - var algorithm = "AES-" + mode; - var cipher; - if (options.decrypt) { - cipher = forge.cipher.createDecipher(algorithm, options.key); - } else { - cipher = forge.cipher.createCipher(algorithm, options.key); - } - var start = cipher.start; - cipher.start = function(iv, options2) { - var output = null; - if (options2 instanceof forge.util.ByteBuffer) { - output = options2; - options2 = {}; - } - options2 = options2 || {}; - options2.output = output; - options2.iv = iv; - start.call(cipher, options2); - }; - return cipher; - } - } -}); - -// node_modules/node-forge/lib/oids.js -var require_oids = __commonJS({ - "node_modules/node-forge/lib/oids.js"(exports2, module2) { - var forge = require_forge(); - forge.pki = forge.pki || {}; - var oids = module2.exports = forge.pki.oids = forge.oids = forge.oids || {}; - function _IN(id, name) { - oids[id] = name; - oids[name] = id; - } - function _I_(id, name) { - oids[id] = name; - } - _IN("1.2.840.113549.1.1.1", "rsaEncryption"); - _IN("1.2.840.113549.1.1.4", "md5WithRSAEncryption"); - _IN("1.2.840.113549.1.1.5", "sha1WithRSAEncryption"); - _IN("1.2.840.113549.1.1.7", "RSAES-OAEP"); - _IN("1.2.840.113549.1.1.8", "mgf1"); - _IN("1.2.840.113549.1.1.9", "pSpecified"); - _IN("1.2.840.113549.1.1.10", "RSASSA-PSS"); - _IN("1.2.840.113549.1.1.11", "sha256WithRSAEncryption"); - _IN("1.2.840.113549.1.1.12", "sha384WithRSAEncryption"); - _IN("1.2.840.113549.1.1.13", "sha512WithRSAEncryption"); - _IN("1.3.101.112", "EdDSA25519"); - _IN("1.2.840.10040.4.3", "dsa-with-sha1"); - _IN("1.3.14.3.2.7", "desCBC"); - _IN("1.3.14.3.2.26", "sha1"); - _IN("1.3.14.3.2.29", "sha1WithRSASignature"); - _IN("2.16.840.1.101.3.4.2.1", "sha256"); - _IN("2.16.840.1.101.3.4.2.2", "sha384"); - _IN("2.16.840.1.101.3.4.2.3", "sha512"); - _IN("2.16.840.1.101.3.4.2.4", "sha224"); - _IN("2.16.840.1.101.3.4.2.5", "sha512-224"); - _IN("2.16.840.1.101.3.4.2.6", "sha512-256"); - _IN("1.2.840.113549.2.2", "md2"); - _IN("1.2.840.113549.2.5", "md5"); - _IN("1.2.840.113549.1.7.1", "data"); - _IN("1.2.840.113549.1.7.2", "signedData"); - _IN("1.2.840.113549.1.7.3", "envelopedData"); - _IN("1.2.840.113549.1.7.4", "signedAndEnvelopedData"); - _IN("1.2.840.113549.1.7.5", "digestedData"); - _IN("1.2.840.113549.1.7.6", "encryptedData"); - _IN("1.2.840.113549.1.9.1", "emailAddress"); - _IN("1.2.840.113549.1.9.2", "unstructuredName"); - _IN("1.2.840.113549.1.9.3", "contentType"); - _IN("1.2.840.113549.1.9.4", "messageDigest"); - _IN("1.2.840.113549.1.9.5", "signingTime"); - _IN("1.2.840.113549.1.9.6", "counterSignature"); - _IN("1.2.840.113549.1.9.7", "challengePassword"); - _IN("1.2.840.113549.1.9.8", "unstructuredAddress"); - _IN("1.2.840.113549.1.9.14", "extensionRequest"); - _IN("1.2.840.113549.1.9.20", "friendlyName"); - _IN("1.2.840.113549.1.9.21", "localKeyId"); - _IN("1.2.840.113549.1.9.22.1", "x509Certificate"); - _IN("1.2.840.113549.1.12.10.1.1", "keyBag"); - _IN("1.2.840.113549.1.12.10.1.2", "pkcs8ShroudedKeyBag"); - _IN("1.2.840.113549.1.12.10.1.3", "certBag"); - _IN("1.2.840.113549.1.12.10.1.4", "crlBag"); - _IN("1.2.840.113549.1.12.10.1.5", "secretBag"); - _IN("1.2.840.113549.1.12.10.1.6", "safeContentsBag"); - _IN("1.2.840.113549.1.5.13", "pkcs5PBES2"); - _IN("1.2.840.113549.1.5.12", "pkcs5PBKDF2"); - _IN("1.2.840.113549.1.12.1.1", "pbeWithSHAAnd128BitRC4"); - _IN("1.2.840.113549.1.12.1.2", "pbeWithSHAAnd40BitRC4"); - _IN("1.2.840.113549.1.12.1.3", "pbeWithSHAAnd3-KeyTripleDES-CBC"); - _IN("1.2.840.113549.1.12.1.4", "pbeWithSHAAnd2-KeyTripleDES-CBC"); - _IN("1.2.840.113549.1.12.1.5", "pbeWithSHAAnd128BitRC2-CBC"); - _IN("1.2.840.113549.1.12.1.6", "pbewithSHAAnd40BitRC2-CBC"); - _IN("1.2.840.113549.2.7", "hmacWithSHA1"); - _IN("1.2.840.113549.2.8", "hmacWithSHA224"); - _IN("1.2.840.113549.2.9", "hmacWithSHA256"); - _IN("1.2.840.113549.2.10", "hmacWithSHA384"); - _IN("1.2.840.113549.2.11", "hmacWithSHA512"); - _IN("1.2.840.113549.3.7", "des-EDE3-CBC"); - _IN("2.16.840.1.101.3.4.1.2", "aes128-CBC"); - _IN("2.16.840.1.101.3.4.1.22", "aes192-CBC"); - _IN("2.16.840.1.101.3.4.1.42", "aes256-CBC"); - _IN("2.5.4.3", "commonName"); - _IN("2.5.4.4", "surname"); - _IN("2.5.4.5", "serialNumber"); - _IN("2.5.4.6", "countryName"); - _IN("2.5.4.7", "localityName"); - _IN("2.5.4.8", "stateOrProvinceName"); - _IN("2.5.4.9", "streetAddress"); - _IN("2.5.4.10", "organizationName"); - _IN("2.5.4.11", "organizationalUnitName"); - _IN("2.5.4.12", "title"); - _IN("2.5.4.13", "description"); - _IN("2.5.4.15", "businessCategory"); - _IN("2.5.4.17", "postalCode"); - _IN("2.5.4.42", "givenName"); - _IN("2.5.4.65", "pseudonym"); - _IN("1.3.6.1.4.1.311.60.2.1.2", "jurisdictionOfIncorporationStateOrProvinceName"); - _IN("1.3.6.1.4.1.311.60.2.1.3", "jurisdictionOfIncorporationCountryName"); - _IN("2.16.840.1.113730.1.1", "nsCertType"); - _IN("2.16.840.1.113730.1.13", "nsComment"); - _I_("2.5.29.1", "authorityKeyIdentifier"); - _I_("2.5.29.2", "keyAttributes"); - _I_("2.5.29.3", "certificatePolicies"); - _I_("2.5.29.4", "keyUsageRestriction"); - _I_("2.5.29.5", "policyMapping"); - _I_("2.5.29.6", "subtreesConstraint"); - _I_("2.5.29.7", "subjectAltName"); - _I_("2.5.29.8", "issuerAltName"); - _I_("2.5.29.9", "subjectDirectoryAttributes"); - _I_("2.5.29.10", "basicConstraints"); - _I_("2.5.29.11", "nameConstraints"); - _I_("2.5.29.12", "policyConstraints"); - _I_("2.5.29.13", "basicConstraints"); - _IN("2.5.29.14", "subjectKeyIdentifier"); - _IN("2.5.29.15", "keyUsage"); - _I_("2.5.29.16", "privateKeyUsagePeriod"); - _IN("2.5.29.17", "subjectAltName"); - _IN("2.5.29.18", "issuerAltName"); - _IN("2.5.29.19", "basicConstraints"); - _I_("2.5.29.20", "cRLNumber"); - _I_("2.5.29.21", "cRLReason"); - _I_("2.5.29.22", "expirationDate"); - _I_("2.5.29.23", "instructionCode"); - _I_("2.5.29.24", "invalidityDate"); - _I_("2.5.29.25", "cRLDistributionPoints"); - _I_("2.5.29.26", "issuingDistributionPoint"); - _I_("2.5.29.27", "deltaCRLIndicator"); - _I_("2.5.29.28", "issuingDistributionPoint"); - _I_("2.5.29.29", "certificateIssuer"); - _I_("2.5.29.30", "nameConstraints"); - _IN("2.5.29.31", "cRLDistributionPoints"); - _IN("2.5.29.32", "certificatePolicies"); - _I_("2.5.29.33", "policyMappings"); - _I_("2.5.29.34", "policyConstraints"); - _IN("2.5.29.35", "authorityKeyIdentifier"); - _I_("2.5.29.36", "policyConstraints"); - _IN("2.5.29.37", "extKeyUsage"); - _I_("2.5.29.46", "freshestCRL"); - _I_("2.5.29.54", "inhibitAnyPolicy"); - _IN("1.3.6.1.4.1.11129.2.4.2", "timestampList"); - _IN("1.3.6.1.5.5.7.1.1", "authorityInfoAccess"); - _IN("1.3.6.1.5.5.7.3.1", "serverAuth"); - _IN("1.3.6.1.5.5.7.3.2", "clientAuth"); - _IN("1.3.6.1.5.5.7.3.3", "codeSigning"); - _IN("1.3.6.1.5.5.7.3.4", "emailProtection"); - _IN("1.3.6.1.5.5.7.3.8", "timeStamping"); - } -}); - -// node_modules/node-forge/lib/asn1.js -var require_asn1 = __commonJS({ - "node_modules/node-forge/lib/asn1.js"(exports2, module2) { - var forge = require_forge(); - require_util13(); - require_oids(); - var asn1 = module2.exports = forge.asn1 = forge.asn1 || {}; - asn1.Class = { - UNIVERSAL: 0, - APPLICATION: 64, - CONTEXT_SPECIFIC: 128, - PRIVATE: 192 - }; - asn1.Type = { - NONE: 0, - BOOLEAN: 1, - INTEGER: 2, - BITSTRING: 3, - OCTETSTRING: 4, - NULL: 5, - OID: 6, - ODESC: 7, - EXTERNAL: 8, - REAL: 9, - ENUMERATED: 10, - EMBEDDED: 11, - UTF8: 12, - ROID: 13, - SEQUENCE: 16, - SET: 17, - PRINTABLESTRING: 19, - IA5STRING: 22, - UTCTIME: 23, - GENERALIZEDTIME: 24, - BMPSTRING: 30 - }; - asn1.maxDepth = 256; - asn1.create = function(tagClass, type, constructed, value, options) { - if (forge.util.isArray(value)) { - var tmp = []; - for (var i = 0; i < value.length; ++i) { - if (value[i] !== void 0) { - tmp.push(value[i]); - } - } - value = tmp; - } - var obj = { - tagClass, - type, - constructed, - composed: constructed || forge.util.isArray(value), - value - }; - if (options && "bitStringContents" in options) { - obj.bitStringContents = options.bitStringContents; - obj.original = asn1.copy(obj); - } - return obj; - }; - asn1.copy = function(obj, options) { - var copy; - if (forge.util.isArray(obj)) { - copy = []; - for (var i = 0; i < obj.length; ++i) { - copy.push(asn1.copy(obj[i], options)); - } - return copy; - } - if (typeof obj === "string") { - return obj; - } - copy = { - tagClass: obj.tagClass, - type: obj.type, - constructed: obj.constructed, - composed: obj.composed, - value: asn1.copy(obj.value, options) - }; - if (options && !options.excludeBitStringContents) { - copy.bitStringContents = obj.bitStringContents; - } - return copy; - }; - asn1.equals = function(obj1, obj2, options) { - if (forge.util.isArray(obj1)) { - if (!forge.util.isArray(obj2)) { - return false; - } - if (obj1.length !== obj2.length) { - return false; - } - for (var i = 0; i < obj1.length; ++i) { - if (!asn1.equals(obj1[i], obj2[i])) { - return false; - } - } - return true; - } - if (typeof obj1 !== typeof obj2) { - return false; - } - if (typeof obj1 === "string") { - return obj1 === obj2; - } - var equal = obj1.tagClass === obj2.tagClass && obj1.type === obj2.type && obj1.constructed === obj2.constructed && obj1.composed === obj2.composed && asn1.equals(obj1.value, obj2.value); - if (options && options.includeBitStringContents) { - equal = equal && obj1.bitStringContents === obj2.bitStringContents; - } - return equal; - }; - asn1.getBerValueLength = function(b) { - var b2 = b.getByte(); - if (b2 === 128) { - return void 0; - } - var length; - var longForm = b2 & 128; - if (!longForm) { - length = b2; - } else { - length = b.getInt((b2 & 127) << 3); - } - return length; - }; - function _checkBufferLength(bytes, remaining, n) { - if (n > remaining) { - var error3 = new Error("Too few bytes to parse DER."); - error3.available = bytes.length(); - error3.remaining = remaining; - error3.requested = n; - throw error3; - } - } - var _getValueLength = function(bytes, remaining) { - var b2 = bytes.getByte(); - remaining--; - if (b2 === 128) { - return void 0; - } - var length; - var longForm = b2 & 128; - if (!longForm) { - length = b2; - } else { - var longFormBytes = b2 & 127; - _checkBufferLength(bytes, remaining, longFormBytes); - length = bytes.getInt(longFormBytes << 3); - } - if (length < 0) { - throw new Error("Negative length: " + length); - } - return length; - }; - asn1.fromDer = function(bytes, options) { - if (options === void 0) { - options = { - strict: true, - parseAllBytes: true, - decodeBitStrings: true - }; - } - if (typeof options === "boolean") { - options = { - strict: options, - parseAllBytes: true, - decodeBitStrings: true - }; - } - if (!("strict" in options)) { - options.strict = true; - } - if (!("parseAllBytes" in options)) { - options.parseAllBytes = true; - } - if (!("decodeBitStrings" in options)) { - options.decodeBitStrings = true; - } - if (!("maxDepth" in options)) { - options.maxDepth = asn1.maxDepth; - } - if (typeof bytes === "string") { - bytes = forge.util.createBuffer(bytes); - } - var byteCount = bytes.length(); - var value = _fromDer(bytes, bytes.length(), 0, options); - if (options.parseAllBytes && bytes.length() !== 0) { - var error3 = new Error("Unparsed DER bytes remain after ASN.1 parsing."); - error3.byteCount = byteCount; - error3.remaining = bytes.length(); - throw error3; - } - return value; - }; - function _fromDer(bytes, remaining, depth, options) { - if (depth >= options.maxDepth) { - throw new Error("ASN.1 parsing error: Max depth exceeded."); - } - var start; - _checkBufferLength(bytes, remaining, 2); - var b1 = bytes.getByte(); - remaining--; - var tagClass = b1 & 192; - var type = b1 & 31; - start = bytes.length(); - var length = _getValueLength(bytes, remaining); - remaining -= start - bytes.length(); - if (length !== void 0 && length > remaining) { - if (options.strict) { - var error3 = new Error("Too few bytes to read ASN.1 value."); - error3.available = bytes.length(); - error3.remaining = remaining; - error3.requested = length; - throw error3; - } - length = remaining; - } - var value; - var bitStringContents; - var constructed = (b1 & 32) === 32; - if (constructed) { - value = []; - if (length === void 0) { - for (; ; ) { - _checkBufferLength(bytes, remaining, 2); - if (bytes.bytes(2) === String.fromCharCode(0, 0)) { - bytes.getBytes(2); - remaining -= 2; - break; - } - start = bytes.length(); - value.push(_fromDer(bytes, remaining, depth + 1, options)); - remaining -= start - bytes.length(); - } - } else { - while (length > 0) { - start = bytes.length(); - value.push(_fromDer(bytes, length, depth + 1, options)); - remaining -= start - bytes.length(); - length -= start - bytes.length(); - } - } - } - if (value === void 0 && tagClass === asn1.Class.UNIVERSAL && type === asn1.Type.BITSTRING) { - bitStringContents = bytes.bytes(length); - } - if (value === void 0 && options.decodeBitStrings && tagClass === asn1.Class.UNIVERSAL && // FIXME: OCTET STRINGs not yet supported here - // .. other parts of forge expect to decode OCTET STRINGs manually - type === asn1.Type.BITSTRING && length > 1) { - var savedRead = bytes.read; - var savedRemaining = remaining; - var unused = 0; - if (type === asn1.Type.BITSTRING) { - _checkBufferLength(bytes, remaining, 1); - unused = bytes.getByte(); - remaining--; - } - if (unused === 0) { - try { - start = bytes.length(); - var subOptions = { - // enforce strict mode to avoid parsing ASN.1 from plain data - strict: true, - decodeBitStrings: true - }; - var composed = _fromDer(bytes, remaining, depth + 1, subOptions); - var used = start - bytes.length(); - remaining -= used; - if (type == asn1.Type.BITSTRING) { - used++; - } - var tc = composed.tagClass; - if (used === length && (tc === asn1.Class.UNIVERSAL || tc === asn1.Class.CONTEXT_SPECIFIC)) { - value = [composed]; - } - } catch (ex) { - } - } - if (value === void 0) { - bytes.read = savedRead; - remaining = savedRemaining; - } - } - if (value === void 0) { - if (length === void 0) { - if (options.strict) { - throw new Error("Non-constructed ASN.1 object of indefinite length."); - } - length = remaining; - } - if (type === asn1.Type.BMPSTRING) { - value = ""; - for (; length > 0; length -= 2) { - _checkBufferLength(bytes, remaining, 2); - value += String.fromCharCode(bytes.getInt16()); - remaining -= 2; - } - } else { - value = bytes.getBytes(length); - remaining -= length; - } - } - var asn1Options = bitStringContents === void 0 ? null : { - bitStringContents - }; - return asn1.create(tagClass, type, constructed, value, asn1Options); - } - asn1.toDer = function(obj) { - var bytes = forge.util.createBuffer(); - var b1 = obj.tagClass | obj.type; - var value = forge.util.createBuffer(); - var useBitStringContents = false; - if ("bitStringContents" in obj) { - useBitStringContents = true; - if (obj.original) { - useBitStringContents = asn1.equals(obj, obj.original); - } - } - if (useBitStringContents) { - value.putBytes(obj.bitStringContents); - } else if (obj.composed) { - if (obj.constructed) { - b1 |= 32; - } else { - value.putByte(0); - } - for (var i = 0; i < obj.value.length; ++i) { - if (obj.value[i] !== void 0) { - value.putBuffer(asn1.toDer(obj.value[i])); - } - } - } else { - if (obj.type === asn1.Type.BMPSTRING) { - for (var i = 0; i < obj.value.length; ++i) { - value.putInt16(obj.value.charCodeAt(i)); - } - } else { - if (obj.type === asn1.Type.INTEGER && obj.value.length > 1 && // leading 0x00 for positive integer - (obj.value.charCodeAt(0) === 0 && (obj.value.charCodeAt(1) & 128) === 0 || // leading 0xFF for negative integer - obj.value.charCodeAt(0) === 255 && (obj.value.charCodeAt(1) & 128) === 128)) { - value.putBytes(obj.value.substr(1)); - } else { - value.putBytes(obj.value); - } - } - } - bytes.putByte(b1); - if (value.length() <= 127) { - bytes.putByte(value.length() & 127); - } else { - var len = value.length(); - var lenBytes = ""; - do { - lenBytes += String.fromCharCode(len & 255); - len = len >>> 8; - } while (len > 0); - bytes.putByte(lenBytes.length | 128); - for (var i = lenBytes.length - 1; i >= 0; --i) { - bytes.putByte(lenBytes.charCodeAt(i)); - } - } - bytes.putBuffer(value); - return bytes; - }; - asn1.oidToDer = function(oid) { - var values = oid.split("."); - var bytes = forge.util.createBuffer(); - bytes.putByte(40 * parseInt(values[0], 10) + parseInt(values[1], 10)); - var last, valueBytes, value, b; - for (var i = 2; i < values.length; ++i) { - last = true; - valueBytes = []; - value = parseInt(values[i], 10); - if (value > 4294967295) { - throw new Error("OID value too large; max is 32-bits."); - } - do { - b = value & 127; - value = value >>> 7; - if (!last) { - b |= 128; - } - valueBytes.push(b); - last = false; - } while (value > 0); - for (var n = valueBytes.length - 1; n >= 0; --n) { - bytes.putByte(valueBytes[n]); - } - } - return bytes; - }; - asn1.derToOid = function(bytes) { - var oid; - if (typeof bytes === "string") { - bytes = forge.util.createBuffer(bytes); - } - var b = bytes.getByte(); - oid = Math.floor(b / 40) + "." + b % 40; - var value = 0; - while (bytes.length() > 0) { - if (value > 70368744177663) { - throw new Error("OID value too large; max is 53-bits."); - } - b = bytes.getByte(); - value = value * 128; - if (b & 128) { - value += b & 127; - } else { - oid += "." + (value + b); - value = 0; - } - } - return oid; - }; - asn1.utcTimeToDate = function(utc) { - var date = /* @__PURE__ */ new Date(); - var year = parseInt(utc.substr(0, 2), 10); - year = year >= 50 ? 1900 + year : 2e3 + year; - var MM = parseInt(utc.substr(2, 2), 10) - 1; - var DD = parseInt(utc.substr(4, 2), 10); - var hh = parseInt(utc.substr(6, 2), 10); - var mm = parseInt(utc.substr(8, 2), 10); - var ss = 0; - if (utc.length > 11) { - var c = utc.charAt(10); - var end = 10; - if (c !== "+" && c !== "-") { - ss = parseInt(utc.substr(10, 2), 10); - end += 2; - } - } - date.setUTCFullYear(year, MM, DD); - date.setUTCHours(hh, mm, ss, 0); - if (end) { - c = utc.charAt(end); - if (c === "+" || c === "-") { - var hhoffset = parseInt(utc.substr(end + 1, 2), 10); - var mmoffset = parseInt(utc.substr(end + 4, 2), 10); - var offset = hhoffset * 60 + mmoffset; - offset *= 6e4; - if (c === "+") { - date.setTime(+date - offset); - } else { - date.setTime(+date + offset); - } - } - } - return date; - }; - asn1.generalizedTimeToDate = function(gentime) { - var date = /* @__PURE__ */ new Date(); - var YYYY = parseInt(gentime.substr(0, 4), 10); - var MM = parseInt(gentime.substr(4, 2), 10) - 1; - var DD = parseInt(gentime.substr(6, 2), 10); - var hh = parseInt(gentime.substr(8, 2), 10); - var mm = parseInt(gentime.substr(10, 2), 10); - var ss = parseInt(gentime.substr(12, 2), 10); - var fff = 0; - var offset = 0; - var isUTC = false; - if (gentime.charAt(gentime.length - 1) === "Z") { - isUTC = true; - } - var end = gentime.length - 5, c = gentime.charAt(end); - if (c === "+" || c === "-") { - var hhoffset = parseInt(gentime.substr(end + 1, 2), 10); - var mmoffset = parseInt(gentime.substr(end + 4, 2), 10); - offset = hhoffset * 60 + mmoffset; - offset *= 6e4; - if (c === "+") { - offset *= -1; - } - isUTC = true; - } - if (gentime.charAt(14) === ".") { - fff = parseFloat(gentime.substr(14), 10) * 1e3; - } - if (isUTC) { - date.setUTCFullYear(YYYY, MM, DD); - date.setUTCHours(hh, mm, ss, fff); - date.setTime(+date + offset); - } else { - date.setFullYear(YYYY, MM, DD); - date.setHours(hh, mm, ss, fff); - } - return date; - }; - asn1.dateToUtcTime = function(date) { - if (typeof date === "string") { - return date; - } - var rval = ""; - var format = []; - format.push(("" + date.getUTCFullYear()).substr(2)); - format.push("" + (date.getUTCMonth() + 1)); - format.push("" + date.getUTCDate()); - format.push("" + date.getUTCHours()); - format.push("" + date.getUTCMinutes()); - format.push("" + date.getUTCSeconds()); - for (var i = 0; i < format.length; ++i) { - if (format[i].length < 2) { - rval += "0"; - } - rval += format[i]; - } - rval += "Z"; - return rval; - }; - asn1.dateToGeneralizedTime = function(date) { - if (typeof date === "string") { - return date; - } - var rval = ""; - var format = []; - format.push("" + date.getUTCFullYear()); - format.push("" + (date.getUTCMonth() + 1)); - format.push("" + date.getUTCDate()); - format.push("" + date.getUTCHours()); - format.push("" + date.getUTCMinutes()); - format.push("" + date.getUTCSeconds()); - for (var i = 0; i < format.length; ++i) { - if (format[i].length < 2) { - rval += "0"; - } - rval += format[i]; - } - rval += "Z"; - return rval; - }; - asn1.integerToDer = function(x) { - var rval = forge.util.createBuffer(); - if (x >= -128 && x < 128) { - return rval.putSignedInt(x, 8); - } - if (x >= -32768 && x < 32768) { - return rval.putSignedInt(x, 16); - } - if (x >= -8388608 && x < 8388608) { - return rval.putSignedInt(x, 24); - } - if (x >= -2147483648 && x < 2147483648) { - return rval.putSignedInt(x, 32); - } - var error3 = new Error("Integer too large; max is 32-bits."); - error3.integer = x; - throw error3; - }; - asn1.derToInteger = function(bytes) { - if (typeof bytes === "string") { - bytes = forge.util.createBuffer(bytes); - } - var n = bytes.length() * 8; - if (n > 32) { - throw new Error("Integer too large; max is 32-bits."); - } - return bytes.getSignedInt(n); - }; - asn1.validate = function(obj, v, capture, errors) { - var rval = false; - if ((obj.tagClass === v.tagClass || typeof v.tagClass === "undefined") && (obj.type === v.type || typeof v.type === "undefined")) { - if (obj.constructed === v.constructed || typeof v.constructed === "undefined") { - rval = true; - if (v.value && forge.util.isArray(v.value)) { - var j = 0; - for (var i = 0; rval && i < v.value.length; ++i) { - var schemaItem = v.value[i]; - rval = !!schemaItem.optional; - var objChild = obj.value[j]; - if (!objChild) { - if (!schemaItem.optional) { - rval = false; - if (errors) { - errors.push("[" + v.name + '] Missing required element. Expected tag class "' + schemaItem.tagClass + '", type "' + schemaItem.type + '"'); - } - } - continue; - } - var schemaHasTag = typeof schemaItem.tagClass !== "undefined" && typeof schemaItem.type !== "undefined"; - if (schemaHasTag && (objChild.tagClass !== schemaItem.tagClass || objChild.type !== schemaItem.type)) { - if (schemaItem.optional) { - rval = true; - continue; - } else { - rval = false; - if (errors) { - errors.push("[" + v.name + "] Tag mismatch. Expected (" + schemaItem.tagClass + "," + schemaItem.type + "), got (" + objChild.tagClass + "," + objChild.type + ")"); - } - break; - } - } - var childRval = asn1.validate(objChild, schemaItem, capture, errors); - if (childRval) { - ++j; - rval = true; - } else if (schemaItem.optional) { - rval = true; - } else { - rval = false; - break; - } - } - } - if (rval && capture) { - if (v.capture) { - capture[v.capture] = obj.value; - } - if (v.captureAsn1) { - capture[v.captureAsn1] = obj; - } - if (v.captureBitStringContents && "bitStringContents" in obj) { - capture[v.captureBitStringContents] = obj.bitStringContents; - } - if (v.captureBitStringValue && "bitStringContents" in obj) { - var value; - if (obj.bitStringContents.length < 2) { - capture[v.captureBitStringValue] = ""; - } else { - var unused = obj.bitStringContents.charCodeAt(0); - if (unused !== 0) { - throw new Error( - "captureBitStringValue only supported for zero unused bits" - ); - } - capture[v.captureBitStringValue] = obj.bitStringContents.slice(1); - } - } - } - } else if (errors) { - errors.push( - "[" + v.name + '] Expected constructed "' + v.constructed + '", got "' + obj.constructed + '"' - ); - } - } else if (errors) { - if (obj.tagClass !== v.tagClass) { - errors.push( - "[" + v.name + '] Expected tag class "' + v.tagClass + '", got "' + obj.tagClass + '"' - ); - } - if (obj.type !== v.type) { - errors.push( - "[" + v.name + '] Expected type "' + v.type + '", got "' + obj.type + '"' - ); - } - } - return rval; - }; - var _nonLatinRegex = /[^\\u0000-\\u00ff]/; - asn1.prettyPrint = function(obj, level, indentation) { - var rval = ""; - level = level || 0; - indentation = indentation || 2; - if (level > 0) { - rval += "\n"; - } - var indent = ""; - for (var i = 0; i < level * indentation; ++i) { - indent += " "; - } - rval += indent + "Tag: "; - switch (obj.tagClass) { - case asn1.Class.UNIVERSAL: - rval += "Universal:"; - break; - case asn1.Class.APPLICATION: - rval += "Application:"; - break; - case asn1.Class.CONTEXT_SPECIFIC: - rval += "Context-Specific:"; - break; - case asn1.Class.PRIVATE: - rval += "Private:"; - break; - } - if (obj.tagClass === asn1.Class.UNIVERSAL) { - rval += obj.type; - switch (obj.type) { - case asn1.Type.NONE: - rval += " (None)"; - break; - case asn1.Type.BOOLEAN: - rval += " (Boolean)"; - break; - case asn1.Type.INTEGER: - rval += " (Integer)"; - break; - case asn1.Type.BITSTRING: - rval += " (Bit string)"; - break; - case asn1.Type.OCTETSTRING: - rval += " (Octet string)"; - break; - case asn1.Type.NULL: - rval += " (Null)"; - break; - case asn1.Type.OID: - rval += " (Object Identifier)"; - break; - case asn1.Type.ODESC: - rval += " (Object Descriptor)"; - break; - case asn1.Type.EXTERNAL: - rval += " (External or Instance of)"; - break; - case asn1.Type.REAL: - rval += " (Real)"; - break; - case asn1.Type.ENUMERATED: - rval += " (Enumerated)"; - break; - case asn1.Type.EMBEDDED: - rval += " (Embedded PDV)"; - break; - case asn1.Type.UTF8: - rval += " (UTF8)"; - break; - case asn1.Type.ROID: - rval += " (Relative Object Identifier)"; - break; - case asn1.Type.SEQUENCE: - rval += " (Sequence)"; - break; - case asn1.Type.SET: - rval += " (Set)"; - break; - case asn1.Type.PRINTABLESTRING: - rval += " (Printable String)"; - break; - case asn1.Type.IA5String: - rval += " (IA5String (ASCII))"; - break; - case asn1.Type.UTCTIME: - rval += " (UTC time)"; - break; - case asn1.Type.GENERALIZEDTIME: - rval += " (Generalized time)"; - break; - case asn1.Type.BMPSTRING: - rval += " (BMP String)"; - break; - } - } else { - rval += obj.type; - } - rval += "\n"; - rval += indent + "Constructed: " + obj.constructed + "\n"; - if (obj.composed) { - var subvalues = 0; - var sub = ""; - for (var i = 0; i < obj.value.length; ++i) { - if (obj.value[i] !== void 0) { - subvalues += 1; - sub += asn1.prettyPrint(obj.value[i], level + 1, indentation); - if (i + 1 < obj.value.length) { - sub += ","; - } - } - } - rval += indent + "Sub values: " + subvalues + sub; - } else { - rval += indent + "Value: "; - if (obj.type === asn1.Type.OID) { - var oid = asn1.derToOid(obj.value); - rval += oid; - if (forge.pki && forge.pki.oids) { - if (oid in forge.pki.oids) { - rval += " (" + forge.pki.oids[oid] + ") "; - } - } - } - if (obj.type === asn1.Type.INTEGER) { - try { - rval += asn1.derToInteger(obj.value); - } catch (ex) { - rval += "0x" + forge.util.bytesToHex(obj.value); - } - } else if (obj.type === asn1.Type.BITSTRING) { - if (obj.value.length > 1) { - rval += "0x" + forge.util.bytesToHex(obj.value.slice(1)); - } else { - rval += "(none)"; - } - if (obj.value.length > 0) { - var unused = obj.value.charCodeAt(0); - if (unused == 1) { - rval += " (1 unused bit shown)"; - } else if (unused > 1) { - rval += " (" + unused + " unused bits shown)"; - } - } - } else if (obj.type === asn1.Type.OCTETSTRING) { - if (!_nonLatinRegex.test(obj.value)) { - rval += "(" + obj.value + ") "; - } - rval += "0x" + forge.util.bytesToHex(obj.value); - } else if (obj.type === asn1.Type.UTF8) { - try { - rval += forge.util.decodeUtf8(obj.value); - } catch (e) { - if (e.message === "URI malformed") { - rval += "0x" + forge.util.bytesToHex(obj.value) + " (malformed UTF8)"; - } else { - throw e; - } - } - } else if (obj.type === asn1.Type.PRINTABLESTRING || obj.type === asn1.Type.IA5String) { - rval += obj.value; - } else if (_nonLatinRegex.test(obj.value)) { - rval += "0x" + forge.util.bytesToHex(obj.value); - } else if (obj.value.length === 0) { - rval += "[null]"; - } else { - rval += obj.value; - } - } - return rval; - }; - } -}); - -// node_modules/node-forge/lib/md.js -var require_md = __commonJS({ - "node_modules/node-forge/lib/md.js"(exports2, module2) { - var forge = require_forge(); - module2.exports = forge.md = forge.md || {}; - forge.md.algorithms = forge.md.algorithms || {}; - } -}); - -// node_modules/node-forge/lib/hmac.js -var require_hmac = __commonJS({ - "node_modules/node-forge/lib/hmac.js"(exports2, module2) { - var forge = require_forge(); - require_md(); - require_util13(); - var hmac = module2.exports = forge.hmac = forge.hmac || {}; - hmac.create = function() { - var _key = null; - var _md = null; - var _ipadding = null; - var _opadding = null; - var ctx = {}; - ctx.start = function(md2, key) { - if (md2 !== null) { - if (typeof md2 === "string") { - md2 = md2.toLowerCase(); - if (md2 in forge.md.algorithms) { - _md = forge.md.algorithms[md2].create(); - } else { - throw new Error('Unknown hash algorithm "' + md2 + '"'); - } - } else { - _md = md2; - } - } - if (key === null) { - key = _key; - } else { - if (typeof key === "string") { - key = forge.util.createBuffer(key); - } else if (forge.util.isArray(key)) { - var tmp = key; - key = forge.util.createBuffer(); - for (var i = 0; i < tmp.length; ++i) { - key.putByte(tmp[i]); - } - } - var keylen = key.length(); - if (keylen > _md.blockLength) { - _md.start(); - _md.update(key.bytes()); - key = _md.digest(); - } - _ipadding = forge.util.createBuffer(); - _opadding = forge.util.createBuffer(); - keylen = key.length(); - for (var i = 0; i < keylen; ++i) { - var tmp = key.at(i); - _ipadding.putByte(54 ^ tmp); - _opadding.putByte(92 ^ tmp); - } - if (keylen < _md.blockLength) { - var tmp = _md.blockLength - keylen; - for (var i = 0; i < tmp; ++i) { - _ipadding.putByte(54); - _opadding.putByte(92); - } - } - _key = key; - _ipadding = _ipadding.bytes(); - _opadding = _opadding.bytes(); - } - _md.start(); - _md.update(_ipadding); - }; - ctx.update = function(bytes) { - _md.update(bytes); - }; - ctx.getMac = function() { - var inner = _md.digest().bytes(); - _md.start(); - _md.update(_opadding); - _md.update(inner); - return _md.digest(); - }; - ctx.digest = ctx.getMac; - return ctx; - }; - } -}); - -// node_modules/node-forge/lib/md5.js -var require_md5 = __commonJS({ - "node_modules/node-forge/lib/md5.js"(exports2, module2) { - var forge = require_forge(); - require_md(); - require_util13(); - var md5 = module2.exports = forge.md5 = forge.md5 || {}; - forge.md.md5 = forge.md.algorithms.md5 = md5; - md5.create = function() { - if (!_initialized) { - _init(); - } - var _state = null; - var _input = forge.util.createBuffer(); - var _w = new Array(16); - var md2 = { - algorithm: "md5", - blockLength: 64, - digestLength: 16, - // 56-bit length of message so far (does not including padding) - messageLength: 0, - // true message length - fullMessageLength: null, - // size of message length in bytes - messageLengthSize: 8 - }; - md2.start = function() { - md2.messageLength = 0; - md2.fullMessageLength = md2.messageLength64 = []; - var int32s = md2.messageLengthSize / 4; - for (var i = 0; i < int32s; ++i) { - md2.fullMessageLength.push(0); - } - _input = forge.util.createBuffer(); - _state = { - h0: 1732584193, - h1: 4023233417, - h2: 2562383102, - h3: 271733878 - }; - return md2; - }; - md2.start(); - md2.update = function(msg, encoding) { - if (encoding === "utf8") { - msg = forge.util.encodeUtf8(msg); - } - var len = msg.length; - md2.messageLength += len; - len = [len / 4294967296 >>> 0, len >>> 0]; - for (var i = md2.fullMessageLength.length - 1; i >= 0; --i) { - md2.fullMessageLength[i] += len[1]; - len[1] = len[0] + (md2.fullMessageLength[i] / 4294967296 >>> 0); - md2.fullMessageLength[i] = md2.fullMessageLength[i] >>> 0; - len[0] = len[1] / 4294967296 >>> 0; - } - _input.putBytes(msg); - _update(_state, _w, _input); - if (_input.read > 2048 || _input.length() === 0) { - _input.compact(); - } - return md2; - }; - md2.digest = function() { - var finalBlock = forge.util.createBuffer(); - finalBlock.putBytes(_input.bytes()); - var remaining = md2.fullMessageLength[md2.fullMessageLength.length - 1] + md2.messageLengthSize; - var overflow = remaining & md2.blockLength - 1; - finalBlock.putBytes(_padding.substr(0, md2.blockLength - overflow)); - var bits, carry = 0; - for (var i = md2.fullMessageLength.length - 1; i >= 0; --i) { - bits = md2.fullMessageLength[i] * 8 + carry; - carry = bits / 4294967296 >>> 0; - finalBlock.putInt32Le(bits >>> 0); - } - var s2 = { - h0: _state.h0, - h1: _state.h1, - h2: _state.h2, - h3: _state.h3 - }; - _update(s2, _w, finalBlock); - var rval = forge.util.createBuffer(); - rval.putInt32Le(s2.h0); - rval.putInt32Le(s2.h1); - rval.putInt32Le(s2.h2); - rval.putInt32Le(s2.h3); - return rval; - }; - return md2; - }; - var _padding = null; - var _g = null; - var _r = null; - var _k = null; - var _initialized = false; - function _init() { - _padding = String.fromCharCode(128); - _padding += forge.util.fillString(String.fromCharCode(0), 64); - _g = [ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - 1, - 6, - 11, - 0, - 5, - 10, - 15, - 4, - 9, - 14, - 3, - 8, - 13, - 2, - 7, - 12, - 5, - 8, - 11, - 14, - 1, - 4, - 7, - 10, - 13, - 0, - 3, - 6, - 9, - 12, - 15, - 2, - 0, - 7, - 14, - 5, - 12, - 3, - 10, - 1, - 8, - 15, - 6, - 13, - 4, - 11, - 2, - 9 - ]; - _r = [ - 7, - 12, - 17, - 22, - 7, - 12, - 17, - 22, - 7, - 12, - 17, - 22, - 7, - 12, - 17, - 22, - 5, - 9, - 14, - 20, - 5, - 9, - 14, - 20, - 5, - 9, - 14, - 20, - 5, - 9, - 14, - 20, - 4, - 11, - 16, - 23, - 4, - 11, - 16, - 23, - 4, - 11, - 16, - 23, - 4, - 11, - 16, - 23, - 6, - 10, - 15, - 21, - 6, - 10, - 15, - 21, - 6, - 10, - 15, - 21, - 6, - 10, - 15, - 21 - ]; - _k = new Array(64); - for (var i = 0; i < 64; ++i) { - _k[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296); - } - _initialized = true; - } - function _update(s, w, bytes) { - var t, a, b, c, d, f, r, i; - var len = bytes.length(); - while (len >= 64) { - a = s.h0; - b = s.h1; - c = s.h2; - d = s.h3; - for (i = 0; i < 16; ++i) { - w[i] = bytes.getInt32Le(); - f = d ^ b & (c ^ d); - t = a + f + _k[i] + w[i]; - r = _r[i]; - a = d; - d = c; - c = b; - b += t << r | t >>> 32 - r; - } - for (; i < 32; ++i) { - f = c ^ d & (b ^ c); - t = a + f + _k[i] + w[_g[i]]; - r = _r[i]; - a = d; - d = c; - c = b; - b += t << r | t >>> 32 - r; - } - for (; i < 48; ++i) { - f = b ^ c ^ d; - t = a + f + _k[i] + w[_g[i]]; - r = _r[i]; - a = d; - d = c; - c = b; - b += t << r | t >>> 32 - r; - } - for (; i < 64; ++i) { - f = c ^ (b | ~d); - t = a + f + _k[i] + w[_g[i]]; - r = _r[i]; - a = d; - d = c; - c = b; - b += t << r | t >>> 32 - r; - } - s.h0 = s.h0 + a | 0; - s.h1 = s.h1 + b | 0; - s.h2 = s.h2 + c | 0; - s.h3 = s.h3 + d | 0; - len -= 64; - } - } - } -}); - -// node_modules/node-forge/lib/pem.js -var require_pem = __commonJS({ - "node_modules/node-forge/lib/pem.js"(exports2, module2) { - var forge = require_forge(); - require_util13(); - var pem = module2.exports = forge.pem = forge.pem || {}; - pem.encode = function(msg, options) { - options = options || {}; - var rval = "-----BEGIN " + msg.type + "-----\r\n"; - var header; - if (msg.procType) { - header = { - name: "Proc-Type", - values: [String(msg.procType.version), msg.procType.type] - }; - rval += foldHeader(header); - } - if (msg.contentDomain) { - header = { name: "Content-Domain", values: [msg.contentDomain] }; - rval += foldHeader(header); - } - if (msg.dekInfo) { - header = { name: "DEK-Info", values: [msg.dekInfo.algorithm] }; - if (msg.dekInfo.parameters) { - header.values.push(msg.dekInfo.parameters); - } - rval += foldHeader(header); - } - if (msg.headers) { - for (var i = 0; i < msg.headers.length; ++i) { - rval += foldHeader(msg.headers[i]); - } - } - if (msg.procType) { - rval += "\r\n"; - } - rval += forge.util.encode64(msg.body, options.maxline || 64) + "\r\n"; - rval += "-----END " + msg.type + "-----\r\n"; - return rval; - }; - pem.decode = function(str) { - var rval = []; - var rMessage = /\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g; - var rHeader = /([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/; - var rCRLF = /\r?\n/; - var match; - while (true) { - match = rMessage.exec(str); - if (!match) { - break; - } - var type = match[1]; - if (type === "NEW CERTIFICATE REQUEST") { - type = "CERTIFICATE REQUEST"; - } - var msg = { - type, - procType: null, - contentDomain: null, - dekInfo: null, - headers: [], - body: forge.util.decode64(match[3]) - }; - rval.push(msg); - if (!match[2]) { - continue; - } - var lines = match[2].split(rCRLF); - var li = 0; - while (match && li < lines.length) { - var line = lines[li].replace(/\s+$/, ""); - for (var nl = li + 1; nl < lines.length; ++nl) { - var next = lines[nl]; - if (!/\s/.test(next[0])) { - break; - } - line += next; - li = nl; - } - match = line.match(rHeader); - if (match) { - var header = { name: match[1], values: [] }; - var values = match[2].split(","); - for (var vi = 0; vi < values.length; ++vi) { - header.values.push(ltrim(values[vi])); - } - if (!msg.procType) { - if (header.name !== "Proc-Type") { - throw new Error('Invalid PEM formatted message. The first encapsulated header must be "Proc-Type".'); - } else if (header.values.length !== 2) { - throw new Error('Invalid PEM formatted message. The "Proc-Type" header must have two subfields.'); - } - msg.procType = { version: values[0], type: values[1] }; - } else if (!msg.contentDomain && header.name === "Content-Domain") { - msg.contentDomain = values[0] || ""; - } else if (!msg.dekInfo && header.name === "DEK-Info") { - if (header.values.length === 0) { - throw new Error('Invalid PEM formatted message. The "DEK-Info" header must have at least one subfield.'); - } - msg.dekInfo = { algorithm: values[0], parameters: values[1] || null }; - } else { - msg.headers.push(header); - } - } - ++li; - } - if (msg.procType === "ENCRYPTED" && !msg.dekInfo) { - throw new Error('Invalid PEM formatted message. The "DEK-Info" header must be present if "Proc-Type" is "ENCRYPTED".'); - } - } - if (rval.length === 0) { - throw new Error("Invalid PEM formatted message."); - } - return rval; - }; - function foldHeader(header) { - var rval = header.name + ": "; - var values = []; - var insertSpace = function(match, $1) { - return " " + $1; - }; - for (var i = 0; i < header.values.length; ++i) { - values.push(header.values[i].replace(/^(\S+\r\n)/, insertSpace)); - } - rval += values.join(",") + "\r\n"; - var length = 0; - var candidate = -1; - for (var i = 0; i < rval.length; ++i, ++length) { - if (length > 65 && candidate !== -1) { - var insert = rval[candidate]; - if (insert === ",") { - ++candidate; - rval = rval.substr(0, candidate) + "\r\n " + rval.substr(candidate); - } else { - rval = rval.substr(0, candidate) + "\r\n" + insert + rval.substr(candidate + 1); - } - length = i - candidate - 1; - candidate = -1; - ++i; - } else if (rval[i] === " " || rval[i] === " " || rval[i] === ",") { - candidate = i; - } - } - return rval; - } - function ltrim(str) { - return str.replace(/^\s+/, ""); - } - } -}); - -// node_modules/node-forge/lib/des.js -var require_des = __commonJS({ - "node_modules/node-forge/lib/des.js"(exports2, module2) { - var forge = require_forge(); - require_cipher(); - require_cipherModes(); - require_util13(); - module2.exports = forge.des = forge.des || {}; - forge.des.startEncrypting = function(key, iv, output, mode) { - var cipher = _createCipher({ - key, - output, - decrypt: false, - mode: mode || (iv === null ? "ECB" : "CBC") - }); - cipher.start(iv); - return cipher; - }; - forge.des.createEncryptionCipher = function(key, mode) { - return _createCipher({ - key, - output: null, - decrypt: false, - mode - }); - }; - forge.des.startDecrypting = function(key, iv, output, mode) { - var cipher = _createCipher({ - key, - output, - decrypt: true, - mode: mode || (iv === null ? "ECB" : "CBC") - }); - cipher.start(iv); - return cipher; - }; - forge.des.createDecryptionCipher = function(key, mode) { - return _createCipher({ - key, - output: null, - decrypt: true, - mode - }); - }; - forge.des.Algorithm = function(name, mode) { - var self2 = this; - self2.name = name; - self2.mode = new mode({ - blockSize: 8, - cipher: { - encrypt: function(inBlock, outBlock) { - return _updateBlock(self2._keys, inBlock, outBlock, false); - }, - decrypt: function(inBlock, outBlock) { - return _updateBlock(self2._keys, inBlock, outBlock, true); - } - } - }); - self2._init = false; - }; - forge.des.Algorithm.prototype.initialize = function(options) { - if (this._init) { - return; - } - var key = forge.util.createBuffer(options.key); - if (this.name.indexOf("3DES") === 0) { - if (key.length() !== 24) { - throw new Error("Invalid Triple-DES key size: " + key.length() * 8); - } - } - this._keys = _createKeys(key); - this._init = true; - }; - registerAlgorithm("DES-ECB", forge.cipher.modes.ecb); - registerAlgorithm("DES-CBC", forge.cipher.modes.cbc); - registerAlgorithm("DES-CFB", forge.cipher.modes.cfb); - registerAlgorithm("DES-OFB", forge.cipher.modes.ofb); - registerAlgorithm("DES-CTR", forge.cipher.modes.ctr); - registerAlgorithm("3DES-ECB", forge.cipher.modes.ecb); - registerAlgorithm("3DES-CBC", forge.cipher.modes.cbc); - registerAlgorithm("3DES-CFB", forge.cipher.modes.cfb); - registerAlgorithm("3DES-OFB", forge.cipher.modes.ofb); - registerAlgorithm("3DES-CTR", forge.cipher.modes.ctr); - function registerAlgorithm(name, mode) { - var factory = function() { - return new forge.des.Algorithm(name, mode); - }; - forge.cipher.registerAlgorithm(name, factory); - } - var spfunction1 = [16843776, 0, 65536, 16843780, 16842756, 66564, 4, 65536, 1024, 16843776, 16843780, 1024, 16778244, 16842756, 16777216, 4, 1028, 16778240, 16778240, 66560, 66560, 16842752, 16842752, 16778244, 65540, 16777220, 16777220, 65540, 0, 1028, 66564, 16777216, 65536, 16843780, 4, 16842752, 16843776, 16777216, 16777216, 1024, 16842756, 65536, 66560, 16777220, 1024, 4, 16778244, 66564, 16843780, 65540, 16842752, 16778244, 16777220, 1028, 66564, 16843776, 1028, 16778240, 16778240, 0, 65540, 66560, 0, 16842756]; - var spfunction2 = [-2146402272, -2147450880, 32768, 1081376, 1048576, 32, -2146435040, -2147450848, -2147483616, -2146402272, -2146402304, -2147483648, -2147450880, 1048576, 32, -2146435040, 1081344, 1048608, -2147450848, 0, -2147483648, 32768, 1081376, -2146435072, 1048608, -2147483616, 0, 1081344, 32800, -2146402304, -2146435072, 32800, 0, 1081376, -2146435040, 1048576, -2147450848, -2146435072, -2146402304, 32768, -2146435072, -2147450880, 32, -2146402272, 1081376, 32, 32768, -2147483648, 32800, -2146402304, 1048576, -2147483616, 1048608, -2147450848, -2147483616, 1048608, 1081344, 0, -2147450880, 32800, -2147483648, -2146435040, -2146402272, 1081344]; - var spfunction3 = [520, 134349312, 0, 134348808, 134218240, 0, 131592, 134218240, 131080, 134217736, 134217736, 131072, 134349320, 131080, 134348800, 520, 134217728, 8, 134349312, 512, 131584, 134348800, 134348808, 131592, 134218248, 131584, 131072, 134218248, 8, 134349320, 512, 134217728, 134349312, 134217728, 131080, 520, 131072, 134349312, 134218240, 0, 512, 131080, 134349320, 134218240, 134217736, 512, 0, 134348808, 134218248, 131072, 134217728, 134349320, 8, 131592, 131584, 134217736, 134348800, 134218248, 520, 134348800, 131592, 8, 134348808, 131584]; - var spfunction4 = [8396801, 8321, 8321, 128, 8396928, 8388737, 8388609, 8193, 0, 8396800, 8396800, 8396929, 129, 0, 8388736, 8388609, 1, 8192, 8388608, 8396801, 128, 8388608, 8193, 8320, 8388737, 1, 8320, 8388736, 8192, 8396928, 8396929, 129, 8388736, 8388609, 8396800, 8396929, 129, 0, 0, 8396800, 8320, 8388736, 8388737, 1, 8396801, 8321, 8321, 128, 8396929, 129, 1, 8192, 8388609, 8193, 8396928, 8388737, 8193, 8320, 8388608, 8396801, 128, 8388608, 8192, 8396928]; - var spfunction5 = [256, 34078976, 34078720, 1107296512, 524288, 256, 1073741824, 34078720, 1074266368, 524288, 33554688, 1074266368, 1107296512, 1107820544, 524544, 1073741824, 33554432, 1074266112, 1074266112, 0, 1073742080, 1107820800, 1107820800, 33554688, 1107820544, 1073742080, 0, 1107296256, 34078976, 33554432, 1107296256, 524544, 524288, 1107296512, 256, 33554432, 1073741824, 34078720, 1107296512, 1074266368, 33554688, 1073741824, 1107820544, 34078976, 1074266368, 256, 33554432, 1107820544, 1107820800, 524544, 1107296256, 1107820800, 34078720, 0, 1074266112, 1107296256, 524544, 33554688, 1073742080, 524288, 0, 1074266112, 34078976, 1073742080]; - var spfunction6 = [536870928, 541065216, 16384, 541081616, 541065216, 16, 541081616, 4194304, 536887296, 4210704, 4194304, 536870928, 4194320, 536887296, 536870912, 16400, 0, 4194320, 536887312, 16384, 4210688, 536887312, 16, 541065232, 541065232, 0, 4210704, 541081600, 16400, 4210688, 541081600, 536870912, 536887296, 16, 541065232, 4210688, 541081616, 4194304, 16400, 536870928, 4194304, 536887296, 536870912, 16400, 536870928, 541081616, 4210688, 541065216, 4210704, 541081600, 0, 541065232, 16, 16384, 541065216, 4210704, 16384, 4194320, 536887312, 0, 541081600, 536870912, 4194320, 536887312]; - var spfunction7 = [2097152, 69206018, 67110914, 0, 2048, 67110914, 2099202, 69208064, 69208066, 2097152, 0, 67108866, 2, 67108864, 69206018, 2050, 67110912, 2099202, 2097154, 67110912, 67108866, 69206016, 69208064, 2097154, 69206016, 2048, 2050, 69208066, 2099200, 2, 67108864, 2099200, 67108864, 2099200, 2097152, 67110914, 67110914, 69206018, 69206018, 2, 2097154, 67108864, 67110912, 2097152, 69208064, 2050, 2099202, 69208064, 2050, 67108866, 69208066, 69206016, 2099200, 0, 2, 69208066, 0, 2099202, 69206016, 2048, 67108866, 67110912, 2048, 2097154]; - var spfunction8 = [268439616, 4096, 262144, 268701760, 268435456, 268439616, 64, 268435456, 262208, 268697600, 268701760, 266240, 268701696, 266304, 4096, 64, 268697600, 268435520, 268439552, 4160, 266240, 262208, 268697664, 268701696, 4160, 0, 0, 268697664, 268435520, 268439552, 266304, 262144, 266304, 262144, 268701696, 4096, 64, 268697664, 4096, 266304, 268439552, 64, 268435520, 268697600, 268697664, 268435456, 262144, 268439616, 0, 268701760, 262208, 268435520, 268697600, 268439552, 268439616, 0, 268701760, 266240, 266240, 4160, 4160, 262208, 268435456, 268701696]; - function _createKeys(key) { - var pc2bytes0 = [0, 4, 536870912, 536870916, 65536, 65540, 536936448, 536936452, 512, 516, 536871424, 536871428, 66048, 66052, 536936960, 536936964], pc2bytes1 = [0, 1, 1048576, 1048577, 67108864, 67108865, 68157440, 68157441, 256, 257, 1048832, 1048833, 67109120, 67109121, 68157696, 68157697], pc2bytes2 = [0, 8, 2048, 2056, 16777216, 16777224, 16779264, 16779272, 0, 8, 2048, 2056, 16777216, 16777224, 16779264, 16779272], pc2bytes3 = [0, 2097152, 134217728, 136314880, 8192, 2105344, 134225920, 136323072, 131072, 2228224, 134348800, 136445952, 139264, 2236416, 134356992, 136454144], pc2bytes4 = [0, 262144, 16, 262160, 0, 262144, 16, 262160, 4096, 266240, 4112, 266256, 4096, 266240, 4112, 266256], pc2bytes5 = [0, 1024, 32, 1056, 0, 1024, 32, 1056, 33554432, 33555456, 33554464, 33555488, 33554432, 33555456, 33554464, 33555488], pc2bytes6 = [0, 268435456, 524288, 268959744, 2, 268435458, 524290, 268959746, 0, 268435456, 524288, 268959744, 2, 268435458, 524290, 268959746], pc2bytes7 = [0, 65536, 2048, 67584, 536870912, 536936448, 536872960, 536938496, 131072, 196608, 133120, 198656, 537001984, 537067520, 537004032, 537069568], pc2bytes8 = [0, 262144, 0, 262144, 2, 262146, 2, 262146, 33554432, 33816576, 33554432, 33816576, 33554434, 33816578, 33554434, 33816578], pc2bytes9 = [0, 268435456, 8, 268435464, 0, 268435456, 8, 268435464, 1024, 268436480, 1032, 268436488, 1024, 268436480, 1032, 268436488], pc2bytes10 = [0, 32, 0, 32, 1048576, 1048608, 1048576, 1048608, 8192, 8224, 8192, 8224, 1056768, 1056800, 1056768, 1056800], pc2bytes11 = [0, 16777216, 512, 16777728, 2097152, 18874368, 2097664, 18874880, 67108864, 83886080, 67109376, 83886592, 69206016, 85983232, 69206528, 85983744], pc2bytes12 = [0, 4096, 134217728, 134221824, 524288, 528384, 134742016, 134746112, 16, 4112, 134217744, 134221840, 524304, 528400, 134742032, 134746128], pc2bytes13 = [0, 4, 256, 260, 0, 4, 256, 260, 1, 5, 257, 261, 1, 5, 257, 261]; - var iterations = key.length() > 8 ? 3 : 1; - var keys = []; - var shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0]; - var n = 0, tmp; - for (var j = 0; j < iterations; j++) { - var left = key.getInt32(); - var right = key.getInt32(); - tmp = (left >>> 4 ^ right) & 252645135; - right ^= tmp; - left ^= tmp << 4; - tmp = (right >>> -16 ^ left) & 65535; - left ^= tmp; - right ^= tmp << -16; - tmp = (left >>> 2 ^ right) & 858993459; - right ^= tmp; - left ^= tmp << 2; - tmp = (right >>> -16 ^ left) & 65535; - left ^= tmp; - right ^= tmp << -16; - tmp = (left >>> 1 ^ right) & 1431655765; - right ^= tmp; - left ^= tmp << 1; - tmp = (right >>> 8 ^ left) & 16711935; - left ^= tmp; - right ^= tmp << 8; - tmp = (left >>> 1 ^ right) & 1431655765; - right ^= tmp; - left ^= tmp << 1; - tmp = left << 8 | right >>> 20 & 240; - left = right << 24 | right << 8 & 16711680 | right >>> 8 & 65280 | right >>> 24 & 240; - right = tmp; - for (var i = 0; i < shifts.length; ++i) { - if (shifts[i]) { - left = left << 2 | left >>> 26; - right = right << 2 | right >>> 26; - } else { - left = left << 1 | left >>> 27; - right = right << 1 | right >>> 27; - } - left &= -15; - right &= -15; - var lefttmp = pc2bytes0[left >>> 28] | pc2bytes1[left >>> 24 & 15] | pc2bytes2[left >>> 20 & 15] | pc2bytes3[left >>> 16 & 15] | pc2bytes4[left >>> 12 & 15] | pc2bytes5[left >>> 8 & 15] | pc2bytes6[left >>> 4 & 15]; - var righttmp = pc2bytes7[right >>> 28] | pc2bytes8[right >>> 24 & 15] | pc2bytes9[right >>> 20 & 15] | pc2bytes10[right >>> 16 & 15] | pc2bytes11[right >>> 12 & 15] | pc2bytes12[right >>> 8 & 15] | pc2bytes13[right >>> 4 & 15]; - tmp = (righttmp >>> 16 ^ lefttmp) & 65535; - keys[n++] = lefttmp ^ tmp; - keys[n++] = righttmp ^ tmp << 16; - } - } - return keys; - } - function _updateBlock(keys, input, output, decrypt) { - var iterations = keys.length === 32 ? 3 : 9; - var looping; - if (iterations === 3) { - looping = decrypt ? [30, -2, -2] : [0, 32, 2]; - } else { - looping = decrypt ? [94, 62, -2, 32, 64, 2, 30, -2, -2] : [0, 32, 2, 62, 30, -2, 64, 96, 2]; - } - var tmp; - var left = input[0]; - var right = input[1]; - tmp = (left >>> 4 ^ right) & 252645135; - right ^= tmp; - left ^= tmp << 4; - tmp = (left >>> 16 ^ right) & 65535; - right ^= tmp; - left ^= tmp << 16; - tmp = (right >>> 2 ^ left) & 858993459; - left ^= tmp; - right ^= tmp << 2; - tmp = (right >>> 8 ^ left) & 16711935; - left ^= tmp; - right ^= tmp << 8; - tmp = (left >>> 1 ^ right) & 1431655765; - right ^= tmp; - left ^= tmp << 1; - left = left << 1 | left >>> 31; - right = right << 1 | right >>> 31; - for (var j = 0; j < iterations; j += 3) { - var endloop = looping[j + 1]; - var loopinc = looping[j + 2]; - for (var i = looping[j]; i != endloop; i += loopinc) { - var right1 = right ^ keys[i]; - var right2 = (right >>> 4 | right << 28) ^ keys[i + 1]; - tmp = left; - left = right; - right = tmp ^ (spfunction2[right1 >>> 24 & 63] | spfunction4[right1 >>> 16 & 63] | spfunction6[right1 >>> 8 & 63] | spfunction8[right1 & 63] | spfunction1[right2 >>> 24 & 63] | spfunction3[right2 >>> 16 & 63] | spfunction5[right2 >>> 8 & 63] | spfunction7[right2 & 63]); - } - tmp = left; - left = right; - right = tmp; - } - left = left >>> 1 | left << 31; - right = right >>> 1 | right << 31; - tmp = (left >>> 1 ^ right) & 1431655765; - right ^= tmp; - left ^= tmp << 1; - tmp = (right >>> 8 ^ left) & 16711935; - left ^= tmp; - right ^= tmp << 8; - tmp = (right >>> 2 ^ left) & 858993459; - left ^= tmp; - right ^= tmp << 2; - tmp = (left >>> 16 ^ right) & 65535; - right ^= tmp; - left ^= tmp << 16; - tmp = (left >>> 4 ^ right) & 252645135; - right ^= tmp; - left ^= tmp << 4; - output[0] = left; - output[1] = right; - } - function _createCipher(options) { - options = options || {}; - var mode = (options.mode || "CBC").toUpperCase(); - var algorithm = "DES-" + mode; - var cipher; - if (options.decrypt) { - cipher = forge.cipher.createDecipher(algorithm, options.key); - } else { - cipher = forge.cipher.createCipher(algorithm, options.key); - } - var start = cipher.start; - cipher.start = function(iv, options2) { - var output = null; - if (options2 instanceof forge.util.ByteBuffer) { - output = options2; - options2 = {}; - } - options2 = options2 || {}; - options2.output = output; - options2.iv = iv; - start.call(cipher, options2); - }; - return cipher; - } - } -}); - -// node_modules/node-forge/lib/pbkdf2.js -var require_pbkdf2 = __commonJS({ - "node_modules/node-forge/lib/pbkdf2.js"(exports2, module2) { - var forge = require_forge(); - require_hmac(); - require_md(); - require_util13(); - var pkcs5 = forge.pkcs5 = forge.pkcs5 || {}; - var crypto; - if (forge.util.isNodejs && !forge.options.usePureJavaScript) { - crypto = require("crypto"); - } - module2.exports = forge.pbkdf2 = pkcs5.pbkdf2 = function(p, s, c, dkLen, md2, callback) { - if (typeof md2 === "function") { - callback = md2; - md2 = null; - } - if (forge.util.isNodejs && !forge.options.usePureJavaScript && crypto.pbkdf2 && (md2 === null || typeof md2 !== "object") && (crypto.pbkdf2Sync.length > 4 || (!md2 || md2 === "sha1"))) { - if (typeof md2 !== "string") { - md2 = "sha1"; - } - p = Buffer.from(p, "binary"); - s = Buffer.from(s, "binary"); - if (!callback) { - if (crypto.pbkdf2Sync.length === 4) { - return crypto.pbkdf2Sync(p, s, c, dkLen).toString("binary"); - } - return crypto.pbkdf2Sync(p, s, c, dkLen, md2).toString("binary"); - } - if (crypto.pbkdf2Sync.length === 4) { - return crypto.pbkdf2(p, s, c, dkLen, function(err2, key) { - if (err2) { - return callback(err2); - } - callback(null, key.toString("binary")); - }); - } - return crypto.pbkdf2(p, s, c, dkLen, md2, function(err2, key) { - if (err2) { - return callback(err2); - } - callback(null, key.toString("binary")); - }); - } - if (typeof md2 === "undefined" || md2 === null) { - md2 = "sha1"; - } - if (typeof md2 === "string") { - if (!(md2 in forge.md.algorithms)) { - throw new Error("Unknown hash algorithm: " + md2); - } - md2 = forge.md[md2].create(); - } - var hLen = md2.digestLength; - if (dkLen > 4294967295 * hLen) { - var err = new Error("Derived key is too long."); - if (callback) { - return callback(err); - } - throw err; - } - var len = Math.ceil(dkLen / hLen); - var r = dkLen - (len - 1) * hLen; - var prf = forge.hmac.create(); - prf.start(md2, p); - var dk = ""; - var xor, u_c, u_c1; - if (!callback) { - for (var i = 1; i <= len; ++i) { - prf.start(null, null); - prf.update(s); - prf.update(forge.util.int32ToBytes(i)); - xor = u_c1 = prf.digest().getBytes(); - for (var j = 2; j <= c; ++j) { - prf.start(null, null); - prf.update(u_c1); - u_c = prf.digest().getBytes(); - xor = forge.util.xorBytes(xor, u_c, hLen); - u_c1 = u_c; - } - dk += i < len ? xor : xor.substr(0, r); - } - return dk; - } - var i = 1, j; - function outer() { - if (i > len) { - return callback(null, dk); - } - prf.start(null, null); - prf.update(s); - prf.update(forge.util.int32ToBytes(i)); - xor = u_c1 = prf.digest().getBytes(); - j = 2; - inner(); - } - function inner() { - if (j <= c) { - prf.start(null, null); - prf.update(u_c1); - u_c = prf.digest().getBytes(); - xor = forge.util.xorBytes(xor, u_c, hLen); - u_c1 = u_c; - ++j; - return forge.util.setImmediate(inner); - } - dk += i < len ? xor : xor.substr(0, r); - ++i; - outer(); - } - outer(); - }; - } -}); - -// node_modules/node-forge/lib/sha256.js -var require_sha256 = __commonJS({ - "node_modules/node-forge/lib/sha256.js"(exports2, module2) { - var forge = require_forge(); - require_md(); - require_util13(); - var sha256 = module2.exports = forge.sha256 = forge.sha256 || {}; - forge.md.sha256 = forge.md.algorithms.sha256 = sha256; - sha256.create = function() { - if (!_initialized) { - _init(); - } - var _state = null; - var _input = forge.util.createBuffer(); - var _w = new Array(64); - var md2 = { - algorithm: "sha256", - blockLength: 64, - digestLength: 32, - // 56-bit length of message so far (does not including padding) - messageLength: 0, - // true message length - fullMessageLength: null, - // size of message length in bytes - messageLengthSize: 8 - }; - md2.start = function() { - md2.messageLength = 0; - md2.fullMessageLength = md2.messageLength64 = []; - var int32s = md2.messageLengthSize / 4; - for (var i = 0; i < int32s; ++i) { - md2.fullMessageLength.push(0); - } - _input = forge.util.createBuffer(); - _state = { - h0: 1779033703, - h1: 3144134277, - h2: 1013904242, - h3: 2773480762, - h4: 1359893119, - h5: 2600822924, - h6: 528734635, - h7: 1541459225 - }; - return md2; - }; - md2.start(); - md2.update = function(msg, encoding) { - if (encoding === "utf8") { - msg = forge.util.encodeUtf8(msg); - } - var len = msg.length; - md2.messageLength += len; - len = [len / 4294967296 >>> 0, len >>> 0]; - for (var i = md2.fullMessageLength.length - 1; i >= 0; --i) { - md2.fullMessageLength[i] += len[1]; - len[1] = len[0] + (md2.fullMessageLength[i] / 4294967296 >>> 0); - md2.fullMessageLength[i] = md2.fullMessageLength[i] >>> 0; - len[0] = len[1] / 4294967296 >>> 0; - } - _input.putBytes(msg); - _update(_state, _w, _input); - if (_input.read > 2048 || _input.length() === 0) { - _input.compact(); - } - return md2; - }; - md2.digest = function() { - var finalBlock = forge.util.createBuffer(); - finalBlock.putBytes(_input.bytes()); - var remaining = md2.fullMessageLength[md2.fullMessageLength.length - 1] + md2.messageLengthSize; - var overflow = remaining & md2.blockLength - 1; - finalBlock.putBytes(_padding.substr(0, md2.blockLength - overflow)); - var next, carry; - var bits = md2.fullMessageLength[0] * 8; - for (var i = 0; i < md2.fullMessageLength.length - 1; ++i) { - next = md2.fullMessageLength[i + 1] * 8; - carry = next / 4294967296 >>> 0; - bits += carry; - finalBlock.putInt32(bits >>> 0); - bits = next >>> 0; - } - finalBlock.putInt32(bits); - var s2 = { - h0: _state.h0, - h1: _state.h1, - h2: _state.h2, - h3: _state.h3, - h4: _state.h4, - h5: _state.h5, - h6: _state.h6, - h7: _state.h7 - }; - _update(s2, _w, finalBlock); - var rval = forge.util.createBuffer(); - rval.putInt32(s2.h0); - rval.putInt32(s2.h1); - rval.putInt32(s2.h2); - rval.putInt32(s2.h3); - rval.putInt32(s2.h4); - rval.putInt32(s2.h5); - rval.putInt32(s2.h6); - rval.putInt32(s2.h7); - return rval; - }; - return md2; - }; - var _padding = null; - var _initialized = false; - var _k = null; - function _init() { - _padding = String.fromCharCode(128); - _padding += forge.util.fillString(String.fromCharCode(0), 64); - _k = [ - 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 - ]; - _initialized = true; - } - function _update(s, w, bytes) { - var t1, t2, s0, s1, ch, maj, i, a, b, c, d, e, f, g, h; - var len = bytes.length(); - while (len >= 64) { - for (i = 0; i < 16; ++i) { - w[i] = bytes.getInt32(); - } - for (; i < 64; ++i) { - t1 = w[i - 2]; - t1 = (t1 >>> 17 | t1 << 15) ^ (t1 >>> 19 | t1 << 13) ^ t1 >>> 10; - t2 = w[i - 15]; - t2 = (t2 >>> 7 | t2 << 25) ^ (t2 >>> 18 | t2 << 14) ^ t2 >>> 3; - w[i] = t1 + w[i - 7] + t2 + w[i - 16] | 0; - } - a = s.h0; - b = s.h1; - c = s.h2; - d = s.h3; - e = s.h4; - f = s.h5; - g = s.h6; - h = s.h7; - for (i = 0; i < 64; ++i) { - s1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7); - ch = g ^ e & (f ^ g); - s0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10); - maj = a & b | c & (a ^ b); - t1 = h + s1 + ch + _k[i] + w[i]; - t2 = s0 + maj; - h = g; - g = f; - f = e; - e = d + t1 >>> 0; - d = c; - c = b; - b = a; - a = t1 + t2 >>> 0; - } - s.h0 = s.h0 + a | 0; - s.h1 = s.h1 + b | 0; - s.h2 = s.h2 + c | 0; - s.h3 = s.h3 + d | 0; - s.h4 = s.h4 + e | 0; - s.h5 = s.h5 + f | 0; - s.h6 = s.h6 + g | 0; - s.h7 = s.h7 + h | 0; - len -= 64; - } - } - } -}); - -// node_modules/node-forge/lib/prng.js -var require_prng = __commonJS({ - "node_modules/node-forge/lib/prng.js"(exports2, module2) { - var forge = require_forge(); - require_util13(); - var _crypto = null; - if (forge.util.isNodejs && !forge.options.usePureJavaScript && !process.versions["node-webkit"]) { - _crypto = require("crypto"); - } - var prng = module2.exports = forge.prng = forge.prng || {}; - prng.create = function(plugin) { - var ctx = { - plugin, - key: null, - seed: null, - time: null, - // number of reseeds so far - reseeds: 0, - // amount of data generated so far - generated: 0, - // no initial key bytes - keyBytes: "" - }; - var md2 = plugin.md; - var pools = new Array(32); - for (var i = 0; i < 32; ++i) { - pools[i] = md2.create(); - } - ctx.pools = pools; - ctx.pool = 0; - ctx.generate = function(count, callback) { - if (!callback) { - return ctx.generateSync(count); - } - var cipher = ctx.plugin.cipher; - var increment = ctx.plugin.increment; - var formatKey = ctx.plugin.formatKey; - var formatSeed = ctx.plugin.formatSeed; - var b = forge.util.createBuffer(); - ctx.key = null; - generate(); - function generate(err) { - if (err) { - return callback(err); - } - if (b.length() >= count) { - return callback(null, b.getBytes(count)); - } - if (ctx.generated > 1048575) { - ctx.key = null; - } - if (ctx.key === null) { - return forge.util.nextTick(function() { - _reseed(generate); - }); - } - var bytes = cipher(ctx.key, ctx.seed); - ctx.generated += bytes.length; - b.putBytes(bytes); - ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed))); - ctx.seed = formatSeed(cipher(ctx.key, ctx.seed)); - forge.util.setImmediate(generate); - } - }; - ctx.generateSync = function(count) { - var cipher = ctx.plugin.cipher; - var increment = ctx.plugin.increment; - var formatKey = ctx.plugin.formatKey; - var formatSeed = ctx.plugin.formatSeed; - ctx.key = null; - var b = forge.util.createBuffer(); - while (b.length() < count) { - if (ctx.generated > 1048575) { - ctx.key = null; - } - if (ctx.key === null) { - _reseedSync(); - } - var bytes = cipher(ctx.key, ctx.seed); - ctx.generated += bytes.length; - b.putBytes(bytes); - ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed))); - ctx.seed = formatSeed(cipher(ctx.key, ctx.seed)); - } - return b.getBytes(count); - }; - function _reseed(callback) { - if (ctx.pools[0].messageLength >= 32) { - _seed(); - return callback(); - } - var needed = 32 - ctx.pools[0].messageLength << 5; - ctx.seedFile(needed, function(err, bytes) { - if (err) { - return callback(err); - } - ctx.collect(bytes); - _seed(); - callback(); - }); - } - function _reseedSync() { - if (ctx.pools[0].messageLength >= 32) { - return _seed(); - } - var needed = 32 - ctx.pools[0].messageLength << 5; - ctx.collect(ctx.seedFileSync(needed)); - _seed(); - } - function _seed() { - ctx.reseeds = ctx.reseeds === 4294967295 ? 0 : ctx.reseeds + 1; - var md3 = ctx.plugin.md.create(); - md3.update(ctx.keyBytes); - var _2powK = 1; - for (var k = 0; k < 32; ++k) { - if (ctx.reseeds % _2powK === 0) { - md3.update(ctx.pools[k].digest().getBytes()); - ctx.pools[k].start(); - } - _2powK = _2powK << 1; - } - ctx.keyBytes = md3.digest().getBytes(); - md3.start(); - md3.update(ctx.keyBytes); - var seedBytes = md3.digest().getBytes(); - ctx.key = ctx.plugin.formatKey(ctx.keyBytes); - ctx.seed = ctx.plugin.formatSeed(seedBytes); - ctx.generated = 0; - } - function defaultSeedFile(needed) { - var getRandomValues = null; - var globalScope = forge.util.globalScope; - var _crypto2 = globalScope.crypto || globalScope.msCrypto; - if (_crypto2 && _crypto2.getRandomValues) { - getRandomValues = function(arr) { - return _crypto2.getRandomValues(arr); - }; - } - var b = forge.util.createBuffer(); - if (getRandomValues) { - while (b.length() < needed) { - var count = Math.max(1, Math.min(needed - b.length(), 65536) / 4); - var entropy = new Uint32Array(Math.floor(count)); - try { - getRandomValues(entropy); - for (var i2 = 0; i2 < entropy.length; ++i2) { - b.putInt32(entropy[i2]); - } - } catch (e) { - if (!(typeof QuotaExceededError !== "undefined" && e instanceof QuotaExceededError)) { - throw e; - } - } - } - } - if (b.length() < needed) { - var hi, lo, next; - var seed = Math.floor(Math.random() * 65536); - while (b.length() < needed) { - lo = 16807 * (seed & 65535); - hi = 16807 * (seed >> 16); - lo += (hi & 32767) << 16; - lo += hi >> 15; - lo = (lo & 2147483647) + (lo >> 31); - seed = lo & 4294967295; - for (var i2 = 0; i2 < 3; ++i2) { - next = seed >>> (i2 << 3); - next ^= Math.floor(Math.random() * 256); - b.putByte(next & 255); - } - } - } - return b.getBytes(needed); - } - if (_crypto) { - ctx.seedFile = function(needed, callback) { - _crypto.randomBytes(needed, function(err, bytes) { - if (err) { - return callback(err); - } - callback(null, bytes.toString()); - }); - }; - ctx.seedFileSync = function(needed) { - return _crypto.randomBytes(needed).toString(); - }; - } else { - ctx.seedFile = function(needed, callback) { - try { - callback(null, defaultSeedFile(needed)); - } catch (e) { - callback(e); - } - }; - ctx.seedFileSync = defaultSeedFile; - } - ctx.collect = function(bytes) { - var count = bytes.length; - for (var i2 = 0; i2 < count; ++i2) { - ctx.pools[ctx.pool].update(bytes.substr(i2, 1)); - ctx.pool = ctx.pool === 31 ? 0 : ctx.pool + 1; - } - }; - ctx.collectInt = function(i2, n) { - var bytes = ""; - for (var x = 0; x < n; x += 8) { - bytes += String.fromCharCode(i2 >> x & 255); - } - ctx.collect(bytes); - }; - ctx.registerWorker = function(worker) { - if (worker === self) { - ctx.seedFile = function(needed, callback) { - function listener2(e) { - var data = e.data; - if (data.forge && data.forge.prng) { - self.removeEventListener("message", listener2); - callback(data.forge.prng.err, data.forge.prng.bytes); - } - } - self.addEventListener("message", listener2); - self.postMessage({ forge: { prng: { needed } } }); - }; - } else { - var listener = function(e) { - var data = e.data; - if (data.forge && data.forge.prng) { - ctx.seedFile(data.forge.prng.needed, function(err, bytes) { - worker.postMessage({ forge: { prng: { err, bytes } } }); - }); - } - }; - worker.addEventListener("message", listener); - } - }; - return ctx; - }; - } -}); - -// node_modules/node-forge/lib/random.js -var require_random = __commonJS({ - "node_modules/node-forge/lib/random.js"(exports2, module2) { - var forge = require_forge(); - require_aes(); - require_sha256(); - require_prng(); - require_util13(); - (function() { - if (forge.random && forge.random.getBytes) { - module2.exports = forge.random; - return; - } - (function(jQuery2) { - var prng_aes = {}; - var _prng_aes_output = new Array(4); - var _prng_aes_buffer = forge.util.createBuffer(); - prng_aes.formatKey = function(key2) { - var tmp = forge.util.createBuffer(key2); - key2 = new Array(4); - key2[0] = tmp.getInt32(); - key2[1] = tmp.getInt32(); - key2[2] = tmp.getInt32(); - key2[3] = tmp.getInt32(); - return forge.aes._expandKey(key2, false); - }; - prng_aes.formatSeed = function(seed) { - var tmp = forge.util.createBuffer(seed); - seed = new Array(4); - seed[0] = tmp.getInt32(); - seed[1] = tmp.getInt32(); - seed[2] = tmp.getInt32(); - seed[3] = tmp.getInt32(); - return seed; - }; - prng_aes.cipher = function(key2, seed) { - forge.aes._updateBlock(key2, seed, _prng_aes_output, false); - _prng_aes_buffer.putInt32(_prng_aes_output[0]); - _prng_aes_buffer.putInt32(_prng_aes_output[1]); - _prng_aes_buffer.putInt32(_prng_aes_output[2]); - _prng_aes_buffer.putInt32(_prng_aes_output[3]); - return _prng_aes_buffer.getBytes(); - }; - prng_aes.increment = function(seed) { - ++seed[3]; - return seed; - }; - prng_aes.md = forge.md.sha256; - function spawnPrng() { - var ctx = forge.prng.create(prng_aes); - ctx.getBytes = function(count, callback) { - return ctx.generate(count, callback); - }; - ctx.getBytesSync = function(count) { - return ctx.generate(count); - }; - return ctx; - } - var _ctx = spawnPrng(); - var getRandomValues = null; - var globalScope = forge.util.globalScope; - var _crypto = globalScope.crypto || globalScope.msCrypto; - if (_crypto && _crypto.getRandomValues) { - getRandomValues = function(arr) { - return _crypto.getRandomValues(arr); - }; - } - if (forge.options.usePureJavaScript || !forge.util.isNodejs && !getRandomValues) { - if (typeof window === "undefined" || window.document === void 0) { - } - _ctx.collectInt(+/* @__PURE__ */ new Date(), 32); - if (typeof navigator !== "undefined") { - var _navBytes = ""; - for (var key in navigator) { - try { - if (typeof navigator[key] == "string") { - _navBytes += navigator[key]; - } - } catch (e) { - } - } - _ctx.collect(_navBytes); - _navBytes = null; - } - if (jQuery2) { - jQuery2().mousemove(function(e) { - _ctx.collectInt(e.clientX, 16); - _ctx.collectInt(e.clientY, 16); - }); - jQuery2().keypress(function(e) { - _ctx.collectInt(e.charCode, 8); - }); - } - } - if (!forge.random) { - forge.random = _ctx; - } else { - for (var key in _ctx) { - forge.random[key] = _ctx[key]; - } - } - forge.random.createInstance = spawnPrng; - module2.exports = forge.random; - })(typeof jQuery !== "undefined" ? jQuery : null); - })(); - } -}); - -// node_modules/node-forge/lib/rc2.js -var require_rc2 = __commonJS({ - "node_modules/node-forge/lib/rc2.js"(exports2, module2) { - var forge = require_forge(); - require_util13(); - var piTable = [ - 217, - 120, - 249, - 196, - 25, - 221, - 181, - 237, - 40, - 233, - 253, - 121, - 74, - 160, - 216, - 157, - 198, - 126, - 55, - 131, - 43, - 118, - 83, - 142, - 98, - 76, - 100, - 136, - 68, - 139, - 251, - 162, - 23, - 154, - 89, - 245, - 135, - 179, - 79, - 19, - 97, - 69, - 109, - 141, - 9, - 129, - 125, - 50, - 189, - 143, - 64, - 235, - 134, - 183, - 123, - 11, - 240, - 149, - 33, - 34, - 92, - 107, - 78, - 130, - 84, - 214, - 101, - 147, - 206, - 96, - 178, - 28, - 115, - 86, - 192, - 20, - 167, - 140, - 241, - 220, - 18, - 117, - 202, - 31, - 59, - 190, - 228, - 209, - 66, - 61, - 212, - 48, - 163, - 60, - 182, - 38, - 111, - 191, - 14, - 218, - 70, - 105, - 7, - 87, - 39, - 242, - 29, - 155, - 188, - 148, - 67, - 3, - 248, - 17, - 199, - 246, - 144, - 239, - 62, - 231, - 6, - 195, - 213, - 47, - 200, - 102, - 30, - 215, - 8, - 232, - 234, - 222, - 128, - 82, - 238, - 247, - 132, - 170, - 114, - 172, - 53, - 77, - 106, - 42, - 150, - 26, - 210, - 113, - 90, - 21, - 73, - 116, - 75, - 159, - 208, - 94, - 4, - 24, - 164, - 236, - 194, - 224, - 65, - 110, - 15, - 81, - 203, - 204, - 36, - 145, - 175, - 80, - 161, - 244, - 112, - 57, - 153, - 124, - 58, - 133, - 35, - 184, - 180, - 122, - 252, - 2, - 54, - 91, - 37, - 85, - 151, - 49, - 45, - 93, - 250, - 152, - 227, - 138, - 146, - 174, - 5, - 223, - 41, - 16, - 103, - 108, - 186, - 201, - 211, - 0, - 230, - 207, - 225, - 158, - 168, - 44, - 99, - 22, - 1, - 63, - 88, - 226, - 137, - 169, - 13, - 56, - 52, - 27, - 171, - 51, - 255, - 176, - 187, - 72, - 12, - 95, - 185, - 177, - 205, - 46, - 197, - 243, - 219, - 71, - 229, - 165, - 156, - 119, - 10, - 166, - 32, - 104, - 254, - 127, - 193, - 173 - ]; - var s = [1, 2, 3, 5]; - var rol = function(word, bits) { - return word << bits & 65535 | (word & 65535) >> 16 - bits; - }; - var ror = function(word, bits) { - return (word & 65535) >> bits | word << 16 - bits & 65535; - }; - module2.exports = forge.rc2 = forge.rc2 || {}; - forge.rc2.expandKey = function(key, effKeyBits) { - if (typeof key === "string") { - key = forge.util.createBuffer(key); - } - effKeyBits = effKeyBits || 128; - var L = key; - var T = key.length(); - var T1 = effKeyBits; - var T8 = Math.ceil(T1 / 8); - var TM = 255 >> (T1 & 7); - var i; - for (i = T; i < 128; i++) { - L.putByte(piTable[L.at(i - 1) + L.at(i - T) & 255]); - } - L.setAt(128 - T8, piTable[L.at(128 - T8) & TM]); - for (i = 127 - T8; i >= 0; i--) { - L.setAt(i, piTable[L.at(i + 1) ^ L.at(i + T8)]); - } - return L; - }; - var createCipher = function(key, bits, encrypt) { - var _finish = false, _input = null, _output = null, _iv = null; - var mixRound, mashRound; - var i, j, K = []; - key = forge.rc2.expandKey(key, bits); - for (i = 0; i < 64; i++) { - K.push(key.getInt16Le()); - } - if (encrypt) { - mixRound = function(R) { - for (i = 0; i < 4; i++) { - R[i] += K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) + (~R[(i + 3) % 4] & R[(i + 1) % 4]); - R[i] = rol(R[i], s[i]); - j++; - } - }; - mashRound = function(R) { - for (i = 0; i < 4; i++) { - R[i] += K[R[(i + 3) % 4] & 63]; - } - }; - } else { - mixRound = function(R) { - for (i = 3; i >= 0; i--) { - R[i] = ror(R[i], s[i]); - R[i] -= K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) + (~R[(i + 3) % 4] & R[(i + 1) % 4]); - j--; - } - }; - mashRound = function(R) { - for (i = 3; i >= 0; i--) { - R[i] -= K[R[(i + 3) % 4] & 63]; - } - }; - } - var runPlan = function(plan) { - var R = []; - for (i = 0; i < 4; i++) { - var val = _input.getInt16Le(); - if (_iv !== null) { - if (encrypt) { - val ^= _iv.getInt16Le(); - } else { - _iv.putInt16Le(val); - } - } - R.push(val & 65535); - } - j = encrypt ? 0 : 63; - for (var ptr = 0; ptr < plan.length; ptr++) { - for (var ctr = 0; ctr < plan[ptr][0]; ctr++) { - plan[ptr][1](R); - } - } - for (i = 0; i < 4; i++) { - if (_iv !== null) { - if (encrypt) { - _iv.putInt16Le(R[i]); - } else { - R[i] ^= _iv.getInt16Le(); - } - } - _output.putInt16Le(R[i]); - } - }; - var cipher = null; - cipher = { - /** - * Starts or restarts the encryption or decryption process, whichever - * was previously configured. - * - * To use the cipher in CBC mode, iv may be given either as a string - * of bytes, or as a byte buffer. For ECB mode, give null as iv. - * - * @param iv the initialization vector to use, null for ECB mode. - * @param output the output the buffer to write to, null to create one. - */ - start: function(iv, output) { - if (iv) { - if (typeof iv === "string") { - iv = forge.util.createBuffer(iv); - } - } - _finish = false; - _input = forge.util.createBuffer(); - _output = output || new forge.util.createBuffer(); - _iv = iv; - cipher.output = _output; - }, - /** - * Updates the next block. - * - * @param input the buffer to read from. - */ - update: function(input) { - if (!_finish) { - _input.putBuffer(input); - } - while (_input.length() >= 8) { - runPlan([ - [5, mixRound], - [1, mashRound], - [6, mixRound], - [1, mashRound], - [5, mixRound] - ]); - } - }, - /** - * Finishes encrypting or decrypting. - * - * @param pad a padding function to use, null for PKCS#7 padding, - * signature(blockSize, buffer, decrypt). - * - * @return true if successful, false on error. - */ - finish: function(pad) { - var rval = true; - if (encrypt) { - if (pad) { - rval = pad(8, _input, !encrypt); - } else { - var padding = _input.length() === 8 ? 8 : 8 - _input.length(); - _input.fillWithByte(padding, padding); - } - } - if (rval) { - _finish = true; - cipher.update(); - } - if (!encrypt) { - rval = _input.length() === 0; - if (rval) { - if (pad) { - rval = pad(8, _output, !encrypt); - } else { - var len = _output.length(); - var count = _output.at(len - 1); - if (count > len) { - rval = false; - } else { - _output.truncate(count); - } - } - } - } - return rval; - } - }; - return cipher; - }; - forge.rc2.startEncrypting = function(key, iv, output) { - var cipher = forge.rc2.createEncryptionCipher(key, 128); - cipher.start(iv, output); - return cipher; - }; - forge.rc2.createEncryptionCipher = function(key, bits) { - return createCipher(key, bits, true); - }; - forge.rc2.startDecrypting = function(key, iv, output) { - var cipher = forge.rc2.createDecryptionCipher(key, 128); - cipher.start(iv, output); - return cipher; - }; - forge.rc2.createDecryptionCipher = function(key, bits) { - return createCipher(key, bits, false); - }; - } -}); - -// node_modules/node-forge/lib/jsbn.js -var require_jsbn = __commonJS({ - "node_modules/node-forge/lib/jsbn.js"(exports2, module2) { - var forge = require_forge(); - module2.exports = forge.jsbn = forge.jsbn || {}; - var dbits; - var canary = 244837814094590; - var j_lm = (canary & 16777215) == 15715070; - function BigInteger(a, b, c) { - this.data = []; - if (a != null) - if ("number" == typeof a) this.fromNumber(a, b, c); - else if (b == null && "string" != typeof a) this.fromString(a, 256); - else this.fromString(a, b); - } - forge.jsbn.BigInteger = BigInteger; - function nbi() { - return new BigInteger(null); - } - function am1(i, x, w, j, c, n) { - while (--n >= 0) { - var v = x * this.data[i++] + w.data[j] + c; - c = Math.floor(v / 67108864); - w.data[j++] = v & 67108863; - } - return c; - } - function am2(i, x, w, j, c, n) { - var xl = x & 32767, xh = x >> 15; - while (--n >= 0) { - var l = this.data[i] & 32767; - var h = this.data[i++] >> 15; - var m = xh * l + h * xl; - l = xl * l + ((m & 32767) << 15) + w.data[j] + (c & 1073741823); - c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30); - w.data[j++] = l & 1073741823; - } - return c; - } - function am3(i, x, w, j, c, n) { - var xl = x & 16383, xh = x >> 14; - while (--n >= 0) { - var l = this.data[i] & 16383; - var h = this.data[i++] >> 14; - var m = xh * l + h * xl; - l = xl * l + ((m & 16383) << 14) + w.data[j] + c; - c = (l >> 28) + (m >> 14) + xh * h; - w.data[j++] = l & 268435455; - } - return c; - } - if (typeof navigator === "undefined") { - BigInteger.prototype.am = am3; - dbits = 28; - } else if (j_lm && navigator.appName == "Microsoft Internet Explorer") { - BigInteger.prototype.am = am2; - dbits = 30; - } else if (j_lm && navigator.appName != "Netscape") { - BigInteger.prototype.am = am1; - dbits = 26; - } else { - BigInteger.prototype.am = am3; - dbits = 28; - } - BigInteger.prototype.DB = dbits; - BigInteger.prototype.DM = (1 << dbits) - 1; - BigInteger.prototype.DV = 1 << dbits; - var BI_FP = 52; - BigInteger.prototype.FV = Math.pow(2, BI_FP); - BigInteger.prototype.F1 = BI_FP - dbits; - BigInteger.prototype.F2 = 2 * dbits - BI_FP; - var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; - var BI_RC = new Array(); - var rr; - var vv; - rr = "0".charCodeAt(0); - for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; - rr = "a".charCodeAt(0); - for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; - rr = "A".charCodeAt(0); - for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; - function int2char(n) { - return BI_RM.charAt(n); - } - function intAt(s, i) { - var c = BI_RC[s.charCodeAt(i)]; - return c == null ? -1 : c; - } - function bnpCopyTo(r) { - for (var i = this.t - 1; i >= 0; --i) r.data[i] = this.data[i]; - r.t = this.t; - r.s = this.s; - } - function bnpFromInt(x) { - this.t = 1; - this.s = x < 0 ? -1 : 0; - if (x > 0) this.data[0] = x; - else if (x < -1) this.data[0] = x + this.DV; - else this.t = 0; - } - function nbv(i) { - var r = nbi(); - r.fromInt(i); - return r; - } - function bnpFromString(s, b) { - var k; - if (b == 16) k = 4; - else if (b == 8) k = 3; - else if (b == 256) k = 8; - else if (b == 2) k = 1; - else if (b == 32) k = 5; - else if (b == 4) k = 2; - else { - this.fromRadix(s, b); - return; - } - this.t = 0; - this.s = 0; - var i = s.length, mi = false, sh = 0; - while (--i >= 0) { - var x = k == 8 ? s[i] & 255 : intAt(s, i); - if (x < 0) { - if (s.charAt(i) == "-") mi = true; - continue; - } - mi = false; - if (sh == 0) - this.data[this.t++] = x; - else if (sh + k > this.DB) { - this.data[this.t - 1] |= (x & (1 << this.DB - sh) - 1) << sh; - this.data[this.t++] = x >> this.DB - sh; - } else - this.data[this.t - 1] |= x << sh; - sh += k; - if (sh >= this.DB) sh -= this.DB; - } - if (k == 8 && (s[0] & 128) != 0) { - this.s = -1; - if (sh > 0) this.data[this.t - 1] |= (1 << this.DB - sh) - 1 << sh; - } - this.clamp(); - if (mi) BigInteger.ZERO.subTo(this, this); - } - function bnpClamp() { - var c = this.s & this.DM; - while (this.t > 0 && this.data[this.t - 1] == c) --this.t; - } - function bnToString(b) { - if (this.s < 0) return "-" + this.negate().toString(b); - var k; - if (b == 16) k = 4; - else if (b == 8) k = 3; - else if (b == 2) k = 1; - else if (b == 32) k = 5; - else if (b == 4) k = 2; - else return this.toRadix(b); - var km = (1 << k) - 1, d, m = false, r = "", i = this.t; - var p = this.DB - i * this.DB % k; - if (i-- > 0) { - if (p < this.DB && (d = this.data[i] >> p) > 0) { - m = true; - r = int2char(d); - } - while (i >= 0) { - if (p < k) { - d = (this.data[i] & (1 << p) - 1) << k - p; - d |= this.data[--i] >> (p += this.DB - k); - } else { - d = this.data[i] >> (p -= k) & km; - if (p <= 0) { - p += this.DB; - --i; - } - } - if (d > 0) m = true; - if (m) r += int2char(d); - } - } - return m ? r : "0"; - } - function bnNegate() { - var r = nbi(); - BigInteger.ZERO.subTo(this, r); - return r; - } - function bnAbs() { - return this.s < 0 ? this.negate() : this; - } - function bnCompareTo(a) { - var r = this.s - a.s; - if (r != 0) return r; - var i = this.t; - r = i - a.t; - if (r != 0) return this.s < 0 ? -r : r; - while (--i >= 0) if ((r = this.data[i] - a.data[i]) != 0) return r; - return 0; - } - function nbits(x) { - var r = 1, t; - if ((t = x >>> 16) != 0) { - x = t; - r += 16; - } - if ((t = x >> 8) != 0) { - x = t; - r += 8; - } - if ((t = x >> 4) != 0) { - x = t; - r += 4; - } - if ((t = x >> 2) != 0) { - x = t; - r += 2; - } - if ((t = x >> 1) != 0) { - x = t; - r += 1; - } - return r; - } - function bnBitLength() { - if (this.t <= 0) return 0; - return this.DB * (this.t - 1) + nbits(this.data[this.t - 1] ^ this.s & this.DM); - } - function bnpDLShiftTo(n, r) { - var i; - for (i = this.t - 1; i >= 0; --i) r.data[i + n] = this.data[i]; - for (i = n - 1; i >= 0; --i) r.data[i] = 0; - r.t = this.t + n; - r.s = this.s; - } - function bnpDRShiftTo(n, r) { - for (var i = n; i < this.t; ++i) r.data[i - n] = this.data[i]; - r.t = Math.max(this.t - n, 0); - r.s = this.s; - } - function bnpLShiftTo(n, r) { - var bs = n % this.DB; - var cbs = this.DB - bs; - var bm = (1 << cbs) - 1; - var ds = Math.floor(n / this.DB), c = this.s << bs & this.DM, i; - for (i = this.t - 1; i >= 0; --i) { - r.data[i + ds + 1] = this.data[i] >> cbs | c; - c = (this.data[i] & bm) << bs; - } - for (i = ds - 1; i >= 0; --i) r.data[i] = 0; - r.data[ds] = c; - r.t = this.t + ds + 1; - r.s = this.s; - r.clamp(); - } - function bnpRShiftTo(n, r) { - r.s = this.s; - var ds = Math.floor(n / this.DB); - if (ds >= this.t) { - r.t = 0; - return; - } - var bs = n % this.DB; - var cbs = this.DB - bs; - var bm = (1 << bs) - 1; - r.data[0] = this.data[ds] >> bs; - for (var i = ds + 1; i < this.t; ++i) { - r.data[i - ds - 1] |= (this.data[i] & bm) << cbs; - r.data[i - ds] = this.data[i] >> bs; - } - if (bs > 0) r.data[this.t - ds - 1] |= (this.s & bm) << cbs; - r.t = this.t - ds; - r.clamp(); - } - function bnpSubTo(a, r) { - var i = 0, c = 0, m = Math.min(a.t, this.t); - while (i < m) { - c += this.data[i] - a.data[i]; - r.data[i++] = c & this.DM; - c >>= this.DB; - } - if (a.t < this.t) { - c -= a.s; - while (i < this.t) { - c += this.data[i]; - r.data[i++] = c & this.DM; - c >>= this.DB; - } - c += this.s; - } else { - c += this.s; - while (i < a.t) { - c -= a.data[i]; - r.data[i++] = c & this.DM; - c >>= this.DB; - } - c -= a.s; - } - r.s = c < 0 ? -1 : 0; - if (c < -1) r.data[i++] = this.DV + c; - else if (c > 0) r.data[i++] = c; - r.t = i; - r.clamp(); - } - function bnpMultiplyTo(a, r) { - var x = this.abs(), y = a.abs(); - var i = x.t; - r.t = i + y.t; - while (--i >= 0) r.data[i] = 0; - for (i = 0; i < y.t; ++i) r.data[i + x.t] = x.am(0, y.data[i], r, i, 0, x.t); - r.s = 0; - r.clamp(); - if (this.s != a.s) BigInteger.ZERO.subTo(r, r); - } - function bnpSquareTo(r) { - var x = this.abs(); - var i = r.t = 2 * x.t; - while (--i >= 0) r.data[i] = 0; - for (i = 0; i < x.t - 1; ++i) { - var c = x.am(i, x.data[i], r, 2 * i, 0, 1); - if ((r.data[i + x.t] += x.am(i + 1, 2 * x.data[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { - r.data[i + x.t] -= x.DV; - r.data[i + x.t + 1] = 1; - } - } - if (r.t > 0) r.data[r.t - 1] += x.am(i, x.data[i], r, 2 * i, 0, 1); - r.s = 0; - r.clamp(); - } - function bnpDivRemTo(m, q, r) { - var pm = m.abs(); - if (pm.t <= 0) return; - var pt = this.abs(); - if (pt.t < pm.t) { - if (q != null) q.fromInt(0); - if (r != null) this.copyTo(r); - return; - } - if (r == null) r = nbi(); - var y = nbi(), ts = this.s, ms = m.s; - var nsh = this.DB - nbits(pm.data[pm.t - 1]); - if (nsh > 0) { - pm.lShiftTo(nsh, y); - pt.lShiftTo(nsh, r); - } else { - pm.copyTo(y); - pt.copyTo(r); - } - var ys = y.t; - var y0 = y.data[ys - 1]; - if (y0 == 0) return; - var yt = y0 * (1 << this.F1) + (ys > 1 ? y.data[ys - 2] >> this.F2 : 0); - var d1 = this.FV / yt, d2 = (1 << this.F1) / yt, e = 1 << this.F2; - var i = r.t, j = i - ys, t = q == null ? nbi() : q; - y.dlShiftTo(j, t); - if (r.compareTo(t) >= 0) { - r.data[r.t++] = 1; - r.subTo(t, r); - } - BigInteger.ONE.dlShiftTo(ys, t); - t.subTo(y, y); - while (y.t < ys) y.data[y.t++] = 0; - while (--j >= 0) { - var qd = r.data[--i] == y0 ? this.DM : Math.floor(r.data[i] * d1 + (r.data[i - 1] + e) * d2); - if ((r.data[i] += y.am(0, qd, r, j, 0, ys)) < qd) { - y.dlShiftTo(j, t); - r.subTo(t, r); - while (r.data[i] < --qd) r.subTo(t, r); - } - } - if (q != null) { - r.drShiftTo(ys, q); - if (ts != ms) BigInteger.ZERO.subTo(q, q); - } - r.t = ys; - r.clamp(); - if (nsh > 0) r.rShiftTo(nsh, r); - if (ts < 0) BigInteger.ZERO.subTo(r, r); - } - function bnMod(a) { - var r = nbi(); - this.abs().divRemTo(a, null, r); - if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r); - return r; - } - function Classic(m) { - this.m = m; - } - function cConvert(x) { - if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); - else return x; - } - function cRevert(x) { - return x; - } - function cReduce(x) { - x.divRemTo(this.m, null, x); - } - function cMulTo(x, y, r) { - x.multiplyTo(y, r); - this.reduce(r); - } - function cSqrTo(x, r) { - x.squareTo(r); - this.reduce(r); - } - Classic.prototype.convert = cConvert; - Classic.prototype.revert = cRevert; - Classic.prototype.reduce = cReduce; - Classic.prototype.mulTo = cMulTo; - Classic.prototype.sqrTo = cSqrTo; - function bnpInvDigit() { - if (this.t < 1) return 0; - var x = this.data[0]; - if ((x & 1) == 0) return 0; - var y = x & 3; - y = y * (2 - (x & 15) * y) & 15; - y = y * (2 - (x & 255) * y) & 255; - y = y * (2 - ((x & 65535) * y & 65535)) & 65535; - y = y * (2 - x * y % this.DV) % this.DV; - return y > 0 ? this.DV - y : -y; - } - function Montgomery(m) { - this.m = m; - this.mp = m.invDigit(); - this.mpl = this.mp & 32767; - this.mph = this.mp >> 15; - this.um = (1 << m.DB - 15) - 1; - this.mt2 = 2 * m.t; - } - function montConvert(x) { - var r = nbi(); - x.abs().dlShiftTo(this.m.t, r); - r.divRemTo(this.m, null, r); - if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r); - return r; - } - function montRevert(x) { - var r = nbi(); - x.copyTo(r); - this.reduce(r); - return r; - } - function montReduce(x) { - while (x.t <= this.mt2) - x.data[x.t++] = 0; - for (var i = 0; i < this.m.t; ++i) { - var j = x.data[i] & 32767; - var u0 = j * this.mpl + ((j * this.mph + (x.data[i] >> 15) * this.mpl & this.um) << 15) & x.DM; - j = i + this.m.t; - x.data[j] += this.m.am(0, u0, x, i, 0, this.m.t); - while (x.data[j] >= x.DV) { - x.data[j] -= x.DV; - x.data[++j]++; - } - } - x.clamp(); - x.drShiftTo(this.m.t, x); - if (x.compareTo(this.m) >= 0) x.subTo(this.m, x); - } - function montSqrTo(x, r) { - x.squareTo(r); - this.reduce(r); - } - function montMulTo(x, y, r) { - x.multiplyTo(y, r); - this.reduce(r); - } - Montgomery.prototype.convert = montConvert; - Montgomery.prototype.revert = montRevert; - Montgomery.prototype.reduce = montReduce; - Montgomery.prototype.mulTo = montMulTo; - Montgomery.prototype.sqrTo = montSqrTo; - function bnpIsEven() { - return (this.t > 0 ? this.data[0] & 1 : this.s) == 0; - } - function bnpExp(e, z) { - if (e > 4294967295 || e < 1) return BigInteger.ONE; - var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e) - 1; - g.copyTo(r); - while (--i >= 0) { - z.sqrTo(r, r2); - if ((e & 1 << i) > 0) z.mulTo(r2, g, r); - else { - var t = r; - r = r2; - r2 = t; - } - } - return z.revert(r); - } - function bnModPowInt(e, m) { - var z; - if (e < 256 || m.isEven()) z = new Classic(m); - else z = new Montgomery(m); - return this.exp(e, z); - } - BigInteger.prototype.copyTo = bnpCopyTo; - BigInteger.prototype.fromInt = bnpFromInt; - BigInteger.prototype.fromString = bnpFromString; - BigInteger.prototype.clamp = bnpClamp; - BigInteger.prototype.dlShiftTo = bnpDLShiftTo; - BigInteger.prototype.drShiftTo = bnpDRShiftTo; - BigInteger.prototype.lShiftTo = bnpLShiftTo; - BigInteger.prototype.rShiftTo = bnpRShiftTo; - BigInteger.prototype.subTo = bnpSubTo; - BigInteger.prototype.multiplyTo = bnpMultiplyTo; - BigInteger.prototype.squareTo = bnpSquareTo; - BigInteger.prototype.divRemTo = bnpDivRemTo; - BigInteger.prototype.invDigit = bnpInvDigit; - BigInteger.prototype.isEven = bnpIsEven; - BigInteger.prototype.exp = bnpExp; - BigInteger.prototype.toString = bnToString; - BigInteger.prototype.negate = bnNegate; - BigInteger.prototype.abs = bnAbs; - BigInteger.prototype.compareTo = bnCompareTo; - BigInteger.prototype.bitLength = bnBitLength; - BigInteger.prototype.mod = bnMod; - BigInteger.prototype.modPowInt = bnModPowInt; - BigInteger.ZERO = nbv(0); - BigInteger.ONE = nbv(1); - function bnClone() { - var r = nbi(); - this.copyTo(r); - return r; - } - function bnIntValue() { - if (this.s < 0) { - if (this.t == 1) return this.data[0] - this.DV; - else if (this.t == 0) return -1; - } else if (this.t == 1) return this.data[0]; - else if (this.t == 0) return 0; - return (this.data[1] & (1 << 32 - this.DB) - 1) << this.DB | this.data[0]; - } - function bnByteValue() { - return this.t == 0 ? this.s : this.data[0] << 24 >> 24; - } - function bnShortValue() { - return this.t == 0 ? this.s : this.data[0] << 16 >> 16; - } - function bnpChunkSize(r) { - return Math.floor(Math.LN2 * this.DB / Math.log(r)); - } - function bnSigNum() { - if (this.s < 0) return -1; - else if (this.t <= 0 || this.t == 1 && this.data[0] <= 0) return 0; - else return 1; - } - function bnpToRadix(b) { - if (b == null) b = 10; - if (this.signum() == 0 || b < 2 || b > 36) return "0"; - var cs = this.chunkSize(b); - var a = Math.pow(b, cs); - var d = nbv(a), y = nbi(), z = nbi(), r = ""; - this.divRemTo(d, y, z); - while (y.signum() > 0) { - r = (a + z.intValue()).toString(b).substr(1) + r; - y.divRemTo(d, y, z); - } - return z.intValue().toString(b) + r; - } - function bnpFromRadix(s, b) { - this.fromInt(0); - if (b == null) b = 10; - var cs = this.chunkSize(b); - var d = Math.pow(b, cs), mi = false, j = 0, w = 0; - for (var i = 0; i < s.length; ++i) { - var x = intAt(s, i); - if (x < 0) { - if (s.charAt(i) == "-" && this.signum() == 0) mi = true; - continue; - } - w = b * w + x; - if (++j >= cs) { - this.dMultiply(d); - this.dAddOffset(w, 0); - j = 0; - w = 0; - } - } - if (j > 0) { - this.dMultiply(Math.pow(b, j)); - this.dAddOffset(w, 0); - } - if (mi) BigInteger.ZERO.subTo(this, this); - } - function bnpFromNumber(a, b, c) { - if ("number" == typeof b) { - if (a < 2) this.fromInt(1); - else { - this.fromNumber(a, c); - if (!this.testBit(a - 1)) - this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this); - if (this.isEven()) this.dAddOffset(1, 0); - while (!this.isProbablePrime(b)) { - this.dAddOffset(2, 0); - if (this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a - 1), this); - } - } - } else { - var x = new Array(), t = a & 7; - x.length = (a >> 3) + 1; - b.nextBytes(x); - if (t > 0) x[0] &= (1 << t) - 1; - else x[0] = 0; - this.fromString(x, 256); - } - } - function bnToByteArray() { - var i = this.t, r = new Array(); - r[0] = this.s; - var p = this.DB - i * this.DB % 8, d, k = 0; - if (i-- > 0) { - if (p < this.DB && (d = this.data[i] >> p) != (this.s & this.DM) >> p) - r[k++] = d | this.s << this.DB - p; - while (i >= 0) { - if (p < 8) { - d = (this.data[i] & (1 << p) - 1) << 8 - p; - d |= this.data[--i] >> (p += this.DB - 8); - } else { - d = this.data[i] >> (p -= 8) & 255; - if (p <= 0) { - p += this.DB; - --i; - } - } - if ((d & 128) != 0) d |= -256; - if (k == 0 && (this.s & 128) != (d & 128)) ++k; - if (k > 0 || d != this.s) r[k++] = d; - } - } - return r; - } - function bnEquals(a) { - return this.compareTo(a) == 0; - } - function bnMin(a) { - return this.compareTo(a) < 0 ? this : a; - } - function bnMax(a) { - return this.compareTo(a) > 0 ? this : a; - } - function bnpBitwiseTo(a, op, r) { - var i, f, m = Math.min(a.t, this.t); - for (i = 0; i < m; ++i) r.data[i] = op(this.data[i], a.data[i]); - if (a.t < this.t) { - f = a.s & this.DM; - for (i = m; i < this.t; ++i) r.data[i] = op(this.data[i], f); - r.t = this.t; - } else { - f = this.s & this.DM; - for (i = m; i < a.t; ++i) r.data[i] = op(f, a.data[i]); - r.t = a.t; - } - r.s = op(this.s, a.s); - r.clamp(); - } - function op_and(x, y) { - return x & y; - } - function bnAnd(a) { - var r = nbi(); - this.bitwiseTo(a, op_and, r); - return r; - } - function op_or(x, y) { - return x | y; - } - function bnOr(a) { - var r = nbi(); - this.bitwiseTo(a, op_or, r); - return r; - } - function op_xor(x, y) { - return x ^ y; - } - function bnXor(a) { - var r = nbi(); - this.bitwiseTo(a, op_xor, r); - return r; - } - function op_andnot(x, y) { - return x & ~y; - } - function bnAndNot(a) { - var r = nbi(); - this.bitwiseTo(a, op_andnot, r); - return r; - } - function bnNot() { - var r = nbi(); - for (var i = 0; i < this.t; ++i) r.data[i] = this.DM & ~this.data[i]; - r.t = this.t; - r.s = ~this.s; - return r; - } - function bnShiftLeft(n) { - var r = nbi(); - if (n < 0) this.rShiftTo(-n, r); - else this.lShiftTo(n, r); - return r; - } - function bnShiftRight(n) { - var r = nbi(); - if (n < 0) this.lShiftTo(-n, r); - else this.rShiftTo(n, r); - return r; - } - function lbit(x) { - if (x == 0) return -1; - var r = 0; - if ((x & 65535) == 0) { - x >>= 16; - r += 16; - } - if ((x & 255) == 0) { - x >>= 8; - r += 8; - } - if ((x & 15) == 0) { - x >>= 4; - r += 4; - } - if ((x & 3) == 0) { - x >>= 2; - r += 2; - } - if ((x & 1) == 0) ++r; - return r; - } - function bnGetLowestSetBit() { - for (var i = 0; i < this.t; ++i) - if (this.data[i] != 0) return i * this.DB + lbit(this.data[i]); - if (this.s < 0) return this.t * this.DB; - return -1; - } - function cbit(x) { - var r = 0; - while (x != 0) { - x &= x - 1; - ++r; - } - return r; - } - function bnBitCount() { - var r = 0, x = this.s & this.DM; - for (var i = 0; i < this.t; ++i) r += cbit(this.data[i] ^ x); - return r; - } - function bnTestBit(n) { - var j = Math.floor(n / this.DB); - if (j >= this.t) return this.s != 0; - return (this.data[j] & 1 << n % this.DB) != 0; - } - function bnpChangeBit(n, op) { - var r = BigInteger.ONE.shiftLeft(n); - this.bitwiseTo(r, op, r); - return r; - } - function bnSetBit(n) { - return this.changeBit(n, op_or); - } - function bnClearBit(n) { - return this.changeBit(n, op_andnot); - } - function bnFlipBit(n) { - return this.changeBit(n, op_xor); - } - function bnpAddTo(a, r) { - var i = 0, c = 0, m = Math.min(a.t, this.t); - while (i < m) { - c += this.data[i] + a.data[i]; - r.data[i++] = c & this.DM; - c >>= this.DB; - } - if (a.t < this.t) { - c += a.s; - while (i < this.t) { - c += this.data[i]; - r.data[i++] = c & this.DM; - c >>= this.DB; - } - c += this.s; - } else { - c += this.s; - while (i < a.t) { - c += a.data[i]; - r.data[i++] = c & this.DM; - c >>= this.DB; - } - c += a.s; - } - r.s = c < 0 ? -1 : 0; - if (c > 0) r.data[i++] = c; - else if (c < -1) r.data[i++] = this.DV + c; - r.t = i; - r.clamp(); - } - function bnAdd(a) { - var r = nbi(); - this.addTo(a, r); - return r; - } - function bnSubtract(a) { - var r = nbi(); - this.subTo(a, r); - return r; - } - function bnMultiply(a) { - var r = nbi(); - this.multiplyTo(a, r); - return r; - } - function bnSquare() { - var r = nbi(); - this.squareTo(r); - return r; - } - function bnDivide(a) { - var r = nbi(); - this.divRemTo(a, r, null); - return r; - } - function bnRemainder(a) { - var r = nbi(); - this.divRemTo(a, null, r); - return r; - } - function bnDivideAndRemainder(a) { - var q = nbi(), r = nbi(); - this.divRemTo(a, q, r); - return new Array(q, r); - } - function bnpDMultiply(n) { - this.data[this.t] = this.am(0, n - 1, this, 0, 0, this.t); - ++this.t; - this.clamp(); - } - function bnpDAddOffset(n, w) { - if (n == 0) return; - while (this.t <= w) this.data[this.t++] = 0; - this.data[w] += n; - while (this.data[w] >= this.DV) { - this.data[w] -= this.DV; - if (++w >= this.t) this.data[this.t++] = 0; - ++this.data[w]; - } - } - function NullExp() { - } - function nNop(x) { - return x; - } - function nMulTo(x, y, r) { - x.multiplyTo(y, r); - } - function nSqrTo(x, r) { - x.squareTo(r); - } - NullExp.prototype.convert = nNop; - NullExp.prototype.revert = nNop; - NullExp.prototype.mulTo = nMulTo; - NullExp.prototype.sqrTo = nSqrTo; - function bnPow(e) { - return this.exp(e, new NullExp()); - } - function bnpMultiplyLowerTo(a, n, r) { - var i = Math.min(this.t + a.t, n); - r.s = 0; - r.t = i; - while (i > 0) r.data[--i] = 0; - var j; - for (j = r.t - this.t; i < j; ++i) r.data[i + this.t] = this.am(0, a.data[i], r, i, 0, this.t); - for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a.data[i], r, i, 0, n - i); - r.clamp(); - } - function bnpMultiplyUpperTo(a, n, r) { - --n; - var i = r.t = this.t + a.t - n; - r.s = 0; - while (--i >= 0) r.data[i] = 0; - for (i = Math.max(n - this.t, 0); i < a.t; ++i) - r.data[this.t + i - n] = this.am(n - i, a.data[i], r, 0, 0, this.t + i - n); - r.clamp(); - r.drShiftTo(1, r); - } - function Barrett(m) { - this.r2 = nbi(); - this.q3 = nbi(); - BigInteger.ONE.dlShiftTo(2 * m.t, this.r2); - this.mu = this.r2.divide(m); - this.m = m; - } - function barrettConvert(x) { - if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m); - else if (x.compareTo(this.m) < 0) return x; - else { - var r = nbi(); - x.copyTo(r); - this.reduce(r); - return r; - } - } - function barrettRevert(x) { - return x; - } - function barrettReduce(x) { - x.drShiftTo(this.m.t - 1, this.r2); - if (x.t > this.m.t + 1) { - x.t = this.m.t + 1; - x.clamp(); - } - this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3); - this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2); - while (x.compareTo(this.r2) < 0) x.dAddOffset(1, this.m.t + 1); - x.subTo(this.r2, x); - while (x.compareTo(this.m) >= 0) x.subTo(this.m, x); - } - function barrettSqrTo(x, r) { - x.squareTo(r); - this.reduce(r); - } - function barrettMulTo(x, y, r) { - x.multiplyTo(y, r); - this.reduce(r); - } - Barrett.prototype.convert = barrettConvert; - Barrett.prototype.revert = barrettRevert; - Barrett.prototype.reduce = barrettReduce; - Barrett.prototype.mulTo = barrettMulTo; - Barrett.prototype.sqrTo = barrettSqrTo; - function bnModPow(e, m) { - var i = e.bitLength(), k, r = nbv(1), z; - if (i <= 0) return r; - else if (i < 18) k = 1; - else if (i < 48) k = 3; - else if (i < 144) k = 4; - else if (i < 768) k = 5; - else k = 6; - if (i < 8) - z = new Classic(m); - else if (m.isEven()) - z = new Barrett(m); - else - z = new Montgomery(m); - var g = new Array(), n = 3, k1 = k - 1, km = (1 << k) - 1; - g[1] = z.convert(this); - if (k > 1) { - var g2 = nbi(); - z.sqrTo(g[1], g2); - while (n <= km) { - g[n] = nbi(); - z.mulTo(g2, g[n - 2], g[n]); - n += 2; - } - } - var j = e.t - 1, w, is1 = true, r2 = nbi(), t; - i = nbits(e.data[j]) - 1; - while (j >= 0) { - if (i >= k1) w = e.data[j] >> i - k1 & km; - else { - w = (e.data[j] & (1 << i + 1) - 1) << k1 - i; - if (j > 0) w |= e.data[j - 1] >> this.DB + i - k1; - } - n = k; - while ((w & 1) == 0) { - w >>= 1; - --n; - } - if ((i -= n) < 0) { - i += this.DB; - --j; - } - if (is1) { - g[w].copyTo(r); - is1 = false; - } else { - while (n > 1) { - z.sqrTo(r, r2); - z.sqrTo(r2, r); - n -= 2; - } - if (n > 0) z.sqrTo(r, r2); - else { - t = r; - r = r2; - r2 = t; - } - z.mulTo(r2, g[w], r); - } - while (j >= 0 && (e.data[j] & 1 << i) == 0) { - z.sqrTo(r, r2); - t = r; - r = r2; - r2 = t; - if (--i < 0) { - i = this.DB - 1; - --j; - } - } - } - return z.revert(r); - } - function bnGCD(a) { - var x = this.s < 0 ? this.negate() : this.clone(); - var y = a.s < 0 ? a.negate() : a.clone(); - if (x.compareTo(y) < 0) { - var t = x; - x = y; - y = t; - } - var i = x.getLowestSetBit(), g = y.getLowestSetBit(); - if (g < 0) return x; - if (i < g) g = i; - if (g > 0) { - x.rShiftTo(g, x); - y.rShiftTo(g, y); - } - while (x.signum() > 0) { - if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x); - if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y); - if (x.compareTo(y) >= 0) { - x.subTo(y, x); - x.rShiftTo(1, x); - } else { - y.subTo(x, y); - y.rShiftTo(1, y); - } - } - if (g > 0) y.lShiftTo(g, y); - return y; - } - function bnpModInt(n) { - if (n <= 0) return 0; - var d = this.DV % n, r = this.s < 0 ? n - 1 : 0; - if (this.t > 0) - if (d == 0) r = this.data[0] % n; - else for (var i = this.t - 1; i >= 0; --i) r = (d * r + this.data[i]) % n; - return r; - } - function bnModInverse(m) { - if (this.signum() == 0) { - return BigInteger.ZERO; - } - var ac = m.isEven(); - if (this.isEven() && ac || m.signum() == 0) return BigInteger.ZERO; - var u = m.clone(), v = this.clone(); - var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); - while (u.signum() != 0) { - while (u.isEven()) { - u.rShiftTo(1, u); - if (ac) { - if (!a.isEven() || !b.isEven()) { - a.addTo(this, a); - b.subTo(m, b); - } - a.rShiftTo(1, a); - } else if (!b.isEven()) b.subTo(m, b); - b.rShiftTo(1, b); - } - while (v.isEven()) { - v.rShiftTo(1, v); - if (ac) { - if (!c.isEven() || !d.isEven()) { - c.addTo(this, c); - d.subTo(m, d); - } - c.rShiftTo(1, c); - } else if (!d.isEven()) d.subTo(m, d); - d.rShiftTo(1, d); - } - if (u.compareTo(v) >= 0) { - u.subTo(v, u); - if (ac) a.subTo(c, a); - b.subTo(d, b); - } else { - v.subTo(u, v); - if (ac) c.subTo(a, c); - d.subTo(b, d); - } - } - if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; - if (d.compareTo(m) >= 0) return d.subtract(m); - if (d.signum() < 0) d.addTo(m, d); - else return d; - if (d.signum() < 0) return d.add(m); - else return d; - } - var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]; - var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]; - function bnIsProbablePrime(t) { - var i, x = this.abs(); - if (x.t == 1 && x.data[0] <= lowprimes[lowprimes.length - 1]) { - for (i = 0; i < lowprimes.length; ++i) - if (x.data[0] == lowprimes[i]) return true; - return false; - } - if (x.isEven()) return false; - i = 1; - while (i < lowprimes.length) { - var m = lowprimes[i], j = i + 1; - while (j < lowprimes.length && m < lplim) m *= lowprimes[j++]; - m = x.modInt(m); - while (i < j) if (m % lowprimes[i++] == 0) return false; - } - return x.millerRabin(t); - } - function bnpMillerRabin(t) { - var n1 = this.subtract(BigInteger.ONE); - var k = n1.getLowestSetBit(); - if (k <= 0) return false; - var r = n1.shiftRight(k); - var prng = bnGetPrng(); - var a; - for (var i = 0; i < t; ++i) { - do { - a = new BigInteger(this.bitLength(), prng); - } while (a.compareTo(BigInteger.ONE) <= 0 || a.compareTo(n1) >= 0); - var y = a.modPow(r, this); - if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { - var j = 1; - while (j++ < k && y.compareTo(n1) != 0) { - y = y.modPowInt(2, this); - if (y.compareTo(BigInteger.ONE) == 0) return false; - } - if (y.compareTo(n1) != 0) return false; - } - } - return true; - } - function bnGetPrng() { - return { - // x is an array to fill with bytes - nextBytes: function(x) { - for (var i = 0; i < x.length; ++i) { - x[i] = Math.floor(Math.random() * 256); - } - } - }; - } - BigInteger.prototype.chunkSize = bnpChunkSize; - BigInteger.prototype.toRadix = bnpToRadix; - BigInteger.prototype.fromRadix = bnpFromRadix; - BigInteger.prototype.fromNumber = bnpFromNumber; - BigInteger.prototype.bitwiseTo = bnpBitwiseTo; - BigInteger.prototype.changeBit = bnpChangeBit; - BigInteger.prototype.addTo = bnpAddTo; - BigInteger.prototype.dMultiply = bnpDMultiply; - BigInteger.prototype.dAddOffset = bnpDAddOffset; - BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; - BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; - BigInteger.prototype.modInt = bnpModInt; - BigInteger.prototype.millerRabin = bnpMillerRabin; - BigInteger.prototype.clone = bnClone; - BigInteger.prototype.intValue = bnIntValue; - BigInteger.prototype.byteValue = bnByteValue; - BigInteger.prototype.shortValue = bnShortValue; - BigInteger.prototype.signum = bnSigNum; - BigInteger.prototype.toByteArray = bnToByteArray; - BigInteger.prototype.equals = bnEquals; - BigInteger.prototype.min = bnMin; - BigInteger.prototype.max = bnMax; - BigInteger.prototype.and = bnAnd; - BigInteger.prototype.or = bnOr; - BigInteger.prototype.xor = bnXor; - BigInteger.prototype.andNot = bnAndNot; - BigInteger.prototype.not = bnNot; - BigInteger.prototype.shiftLeft = bnShiftLeft; - BigInteger.prototype.shiftRight = bnShiftRight; - BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; - BigInteger.prototype.bitCount = bnBitCount; - BigInteger.prototype.testBit = bnTestBit; - BigInteger.prototype.setBit = bnSetBit; - BigInteger.prototype.clearBit = bnClearBit; - BigInteger.prototype.flipBit = bnFlipBit; - BigInteger.prototype.add = bnAdd; - BigInteger.prototype.subtract = bnSubtract; - BigInteger.prototype.multiply = bnMultiply; - BigInteger.prototype.divide = bnDivide; - BigInteger.prototype.remainder = bnRemainder; - BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; - BigInteger.prototype.modPow = bnModPow; - BigInteger.prototype.modInverse = bnModInverse; - BigInteger.prototype.pow = bnPow; - BigInteger.prototype.gcd = bnGCD; - BigInteger.prototype.isProbablePrime = bnIsProbablePrime; - BigInteger.prototype.square = bnSquare; - } -}); - -// node_modules/node-forge/lib/sha1.js -var require_sha1 = __commonJS({ - "node_modules/node-forge/lib/sha1.js"(exports2, module2) { - var forge = require_forge(); - require_md(); - require_util13(); - var sha1 = module2.exports = forge.sha1 = forge.sha1 || {}; - forge.md.sha1 = forge.md.algorithms.sha1 = sha1; - sha1.create = function() { - if (!_initialized) { - _init(); - } - var _state = null; - var _input = forge.util.createBuffer(); - var _w = new Array(80); - var md2 = { - algorithm: "sha1", - blockLength: 64, - digestLength: 20, - // 56-bit length of message so far (does not including padding) - messageLength: 0, - // true message length - fullMessageLength: null, - // size of message length in bytes - messageLengthSize: 8 - }; - md2.start = function() { - md2.messageLength = 0; - md2.fullMessageLength = md2.messageLength64 = []; - var int32s = md2.messageLengthSize / 4; - for (var i = 0; i < int32s; ++i) { - md2.fullMessageLength.push(0); - } - _input = forge.util.createBuffer(); - _state = { - h0: 1732584193, - h1: 4023233417, - h2: 2562383102, - h3: 271733878, - h4: 3285377520 - }; - return md2; - }; - md2.start(); - md2.update = function(msg, encoding) { - if (encoding === "utf8") { - msg = forge.util.encodeUtf8(msg); - } - var len = msg.length; - md2.messageLength += len; - len = [len / 4294967296 >>> 0, len >>> 0]; - for (var i = md2.fullMessageLength.length - 1; i >= 0; --i) { - md2.fullMessageLength[i] += len[1]; - len[1] = len[0] + (md2.fullMessageLength[i] / 4294967296 >>> 0); - md2.fullMessageLength[i] = md2.fullMessageLength[i] >>> 0; - len[0] = len[1] / 4294967296 >>> 0; - } - _input.putBytes(msg); - _update(_state, _w, _input); - if (_input.read > 2048 || _input.length() === 0) { - _input.compact(); - } - return md2; - }; - md2.digest = function() { - var finalBlock = forge.util.createBuffer(); - finalBlock.putBytes(_input.bytes()); - var remaining = md2.fullMessageLength[md2.fullMessageLength.length - 1] + md2.messageLengthSize; - var overflow = remaining & md2.blockLength - 1; - finalBlock.putBytes(_padding.substr(0, md2.blockLength - overflow)); - var next, carry; - var bits = md2.fullMessageLength[0] * 8; - for (var i = 0; i < md2.fullMessageLength.length - 1; ++i) { - next = md2.fullMessageLength[i + 1] * 8; - carry = next / 4294967296 >>> 0; - bits += carry; - finalBlock.putInt32(bits >>> 0); - bits = next >>> 0; - } - finalBlock.putInt32(bits); - var s2 = { - h0: _state.h0, - h1: _state.h1, - h2: _state.h2, - h3: _state.h3, - h4: _state.h4 - }; - _update(s2, _w, finalBlock); - var rval = forge.util.createBuffer(); - rval.putInt32(s2.h0); - rval.putInt32(s2.h1); - rval.putInt32(s2.h2); - rval.putInt32(s2.h3); - rval.putInt32(s2.h4); - return rval; - }; - return md2; - }; - var _padding = null; - var _initialized = false; - function _init() { - _padding = String.fromCharCode(128); - _padding += forge.util.fillString(String.fromCharCode(0), 64); - _initialized = true; - } - function _update(s, w, bytes) { - var t, a, b, c, d, e, f, i; - var len = bytes.length(); - while (len >= 64) { - a = s.h0; - b = s.h1; - c = s.h2; - d = s.h3; - e = s.h4; - for (i = 0; i < 16; ++i) { - t = bytes.getInt32(); - w[i] = t; - f = d ^ b & (c ^ d); - t = (a << 5 | a >>> 27) + f + e + 1518500249 + t; - e = d; - d = c; - c = (b << 30 | b >>> 2) >>> 0; - b = a; - a = t; - } - for (; i < 20; ++i) { - t = w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]; - t = t << 1 | t >>> 31; - w[i] = t; - f = d ^ b & (c ^ d); - t = (a << 5 | a >>> 27) + f + e + 1518500249 + t; - e = d; - d = c; - c = (b << 30 | b >>> 2) >>> 0; - b = a; - a = t; - } - for (; i < 32; ++i) { - t = w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]; - t = t << 1 | t >>> 31; - w[i] = t; - f = b ^ c ^ d; - t = (a << 5 | a >>> 27) + f + e + 1859775393 + t; - e = d; - d = c; - c = (b << 30 | b >>> 2) >>> 0; - b = a; - a = t; - } - for (; i < 40; ++i) { - t = w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]; - t = t << 2 | t >>> 30; - w[i] = t; - f = b ^ c ^ d; - t = (a << 5 | a >>> 27) + f + e + 1859775393 + t; - e = d; - d = c; - c = (b << 30 | b >>> 2) >>> 0; - b = a; - a = t; - } - for (; i < 60; ++i) { - t = w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]; - t = t << 2 | t >>> 30; - w[i] = t; - f = b & c | d & (b ^ c); - t = (a << 5 | a >>> 27) + f + e + 2400959708 + t; - e = d; - d = c; - c = (b << 30 | b >>> 2) >>> 0; - b = a; - a = t; - } - for (; i < 80; ++i) { - t = w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]; - t = t << 2 | t >>> 30; - w[i] = t; - f = b ^ c ^ d; - t = (a << 5 | a >>> 27) + f + e + 3395469782 + t; - e = d; - d = c; - c = (b << 30 | b >>> 2) >>> 0; - b = a; - a = t; - } - s.h0 = s.h0 + a | 0; - s.h1 = s.h1 + b | 0; - s.h2 = s.h2 + c | 0; - s.h3 = s.h3 + d | 0; - s.h4 = s.h4 + e | 0; - len -= 64; - } - } - } -}); - -// node_modules/node-forge/lib/pkcs1.js -var require_pkcs1 = __commonJS({ - "node_modules/node-forge/lib/pkcs1.js"(exports2, module2) { - var forge = require_forge(); - require_util13(); - require_random(); - require_sha1(); - var pkcs1 = module2.exports = forge.pkcs1 = forge.pkcs1 || {}; - pkcs1.encode_rsa_oaep = function(key, message, options) { - var label; - var seed; - var md2; - var mgf1Md; - if (typeof options === "string") { - label = options; - seed = arguments[3] || void 0; - md2 = arguments[4] || void 0; - } else if (options) { - label = options.label || void 0; - seed = options.seed || void 0; - md2 = options.md || void 0; - if (options.mgf1 && options.mgf1.md) { - mgf1Md = options.mgf1.md; - } - } - if (!md2) { - md2 = forge.md.sha1.create(); - } else { - md2.start(); - } - if (!mgf1Md) { - mgf1Md = md2; - } - var keyLength = Math.ceil(key.n.bitLength() / 8); - var maxLength = keyLength - 2 * md2.digestLength - 2; - if (message.length > maxLength) { - var error3 = new Error("RSAES-OAEP input message length is too long."); - error3.length = message.length; - error3.maxLength = maxLength; - throw error3; - } - if (!label) { - label = ""; - } - md2.update(label, "raw"); - var lHash = md2.digest(); - var PS = ""; - var PS_length = maxLength - message.length; - for (var i = 0; i < PS_length; i++) { - PS += "\0"; - } - var DB = lHash.getBytes() + PS + "" + message; - if (!seed) { - seed = forge.random.getBytes(md2.digestLength); - } else if (seed.length !== md2.digestLength) { - var error3 = new Error("Invalid RSAES-OAEP seed. The seed length must match the digest length."); - error3.seedLength = seed.length; - error3.digestLength = md2.digestLength; - throw error3; - } - var dbMask = rsa_mgf1(seed, keyLength - md2.digestLength - 1, mgf1Md); - var maskedDB = forge.util.xorBytes(DB, dbMask, DB.length); - var seedMask = rsa_mgf1(maskedDB, md2.digestLength, mgf1Md); - var maskedSeed = forge.util.xorBytes(seed, seedMask, seed.length); - return "\0" + maskedSeed + maskedDB; - }; - pkcs1.decode_rsa_oaep = function(key, em, options) { - var label; - var md2; - var mgf1Md; - if (typeof options === "string") { - label = options; - md2 = arguments[3] || void 0; - } else if (options) { - label = options.label || void 0; - md2 = options.md || void 0; - if (options.mgf1 && options.mgf1.md) { - mgf1Md = options.mgf1.md; - } - } - var keyLength = Math.ceil(key.n.bitLength() / 8); - if (em.length !== keyLength) { - var error3 = new Error("RSAES-OAEP encoded message length is invalid."); - error3.length = em.length; - error3.expectedLength = keyLength; - throw error3; - } - if (md2 === void 0) { - md2 = forge.md.sha1.create(); - } else { - md2.start(); - } - if (!mgf1Md) { - mgf1Md = md2; - } - if (keyLength < 2 * md2.digestLength + 2) { - throw new Error("RSAES-OAEP key is too short for the hash function."); - } - if (!label) { - label = ""; - } - md2.update(label, "raw"); - var lHash = md2.digest().getBytes(); - var y = em.charAt(0); - var maskedSeed = em.substring(1, md2.digestLength + 1); - var maskedDB = em.substring(1 + md2.digestLength); - var seedMask = rsa_mgf1(maskedDB, md2.digestLength, mgf1Md); - var seed = forge.util.xorBytes(maskedSeed, seedMask, maskedSeed.length); - var dbMask = rsa_mgf1(seed, keyLength - md2.digestLength - 1, mgf1Md); - var db = forge.util.xorBytes(maskedDB, dbMask, maskedDB.length); - var lHashPrime = db.substring(0, md2.digestLength); - var error3 = y !== "\0"; - for (var i = 0; i < md2.digestLength; ++i) { - error3 |= lHash.charAt(i) !== lHashPrime.charAt(i); - } - var in_ps = 1; - var index = md2.digestLength; - for (var j = md2.digestLength; j < db.length; j++) { - var code = db.charCodeAt(j); - var is_0 = code & 1 ^ 1; - var error_mask = in_ps ? 65534 : 0; - error3 |= code & error_mask; - in_ps = in_ps & is_0; - index += in_ps; - } - if (error3 || db.charCodeAt(index) !== 1) { - throw new Error("Invalid RSAES-OAEP padding."); - } - return db.substring(index + 1); - }; - function rsa_mgf1(seed, maskLength, hash) { - if (!hash) { - hash = forge.md.sha1.create(); - } - var t = ""; - var count = Math.ceil(maskLength / hash.digestLength); - for (var i = 0; i < count; ++i) { - var c = String.fromCharCode( - i >> 24 & 255, - i >> 16 & 255, - i >> 8 & 255, - i & 255 - ); - hash.start(); - hash.update(seed + c); - t += hash.digest().getBytes(); - } - return t.substring(0, maskLength); - } - } -}); - -// node_modules/node-forge/lib/prime.js -var require_prime = __commonJS({ - "node_modules/node-forge/lib/prime.js"(exports2, module2) { - var forge = require_forge(); - require_util13(); - require_jsbn(); - require_random(); - (function() { - if (forge.prime) { - module2.exports = forge.prime; - return; - } - var prime = module2.exports = forge.prime = forge.prime || {}; - var BigInteger = forge.jsbn.BigInteger; - var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; - var THIRTY = new BigInteger(null); - THIRTY.fromInt(30); - var op_or = function(x, y) { - return x | y; - }; - prime.generateProbablePrime = function(bits, options, callback) { - if (typeof options === "function") { - callback = options; - options = {}; - } - options = options || {}; - var algorithm = options.algorithm || "PRIMEINC"; - if (typeof algorithm === "string") { - algorithm = { name: algorithm }; - } - algorithm.options = algorithm.options || {}; - var prng = options.prng || forge.random; - var rng = { - // x is an array to fill with bytes - nextBytes: function(x) { - var b = prng.getBytesSync(x.length); - for (var i = 0; i < x.length; ++i) { - x[i] = b.charCodeAt(i); - } - } - }; - if (algorithm.name === "PRIMEINC") { - return primeincFindPrime(bits, rng, algorithm.options, callback); - } - throw new Error("Invalid prime generation algorithm: " + algorithm.name); - }; - function primeincFindPrime(bits, rng, options, callback) { - if ("workers" in options) { - return primeincFindPrimeWithWorkers(bits, rng, options, callback); - } - return primeincFindPrimeWithoutWorkers(bits, rng, options, callback); - } - function primeincFindPrimeWithoutWorkers(bits, rng, options, callback) { - var num = generateRandom(bits, rng); - var deltaIdx = 0; - var mrTests = getMillerRabinTests(num.bitLength()); - if ("millerRabinTests" in options) { - mrTests = options.millerRabinTests; - } - var maxBlockTime = 10; - if ("maxBlockTime" in options) { - maxBlockTime = options.maxBlockTime; - } - _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback); - } - function _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback) { - var start = +/* @__PURE__ */ new Date(); - do { - if (num.bitLength() > bits) { - num = generateRandom(bits, rng); - } - if (num.isProbablePrime(mrTests)) { - return callback(null, num); - } - num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); - } while (maxBlockTime < 0 || +/* @__PURE__ */ new Date() - start < maxBlockTime); - forge.util.setImmediate(function() { - _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback); - }); - } - function primeincFindPrimeWithWorkers(bits, rng, options, callback) { - if (typeof Worker === "undefined") { - return primeincFindPrimeWithoutWorkers(bits, rng, options, callback); - } - var num = generateRandom(bits, rng); - var numWorkers = options.workers; - var workLoad = options.workLoad || 100; - var range = workLoad * 30 / 8; - var workerScript = options.workerScript || "forge/prime.worker.js"; - if (numWorkers === -1) { - return forge.util.estimateCores(function(err, cores) { - if (err) { - cores = 2; - } - numWorkers = cores - 1; - generate(); - }); - } - generate(); - function generate() { - numWorkers = Math.max(1, numWorkers); - var workers = []; - for (var i = 0; i < numWorkers; ++i) { - workers[i] = new Worker(workerScript); - } - var running = numWorkers; - for (var i = 0; i < numWorkers; ++i) { - workers[i].addEventListener("message", workerMessage); - } - var found = false; - function workerMessage(e) { - if (found) { - return; - } - --running; - var data = e.data; - if (data.found) { - for (var i2 = 0; i2 < workers.length; ++i2) { - workers[i2].terminate(); - } - found = true; - return callback(null, new BigInteger(data.prime, 16)); - } - if (num.bitLength() > bits) { - num = generateRandom(bits, rng); - } - var hex = num.toString(16); - e.target.postMessage({ - hex, - workLoad - }); - num.dAddOffset(range, 0); - } - } - } - function generateRandom(bits, rng) { - var num = new BigInteger(bits, rng); - var bits1 = bits - 1; - if (!num.testBit(bits1)) { - num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num); - } - num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0); - return num; - } - function getMillerRabinTests(bits) { - if (bits <= 100) return 27; - if (bits <= 150) return 18; - if (bits <= 200) return 15; - if (bits <= 250) return 12; - if (bits <= 300) return 9; - if (bits <= 350) return 8; - if (bits <= 400) return 7; - if (bits <= 500) return 6; - if (bits <= 600) return 5; - if (bits <= 800) return 4; - if (bits <= 1250) return 3; - return 2; - } - })(); - } -}); - -// node_modules/node-forge/lib/rsa.js -var require_rsa = __commonJS({ - "node_modules/node-forge/lib/rsa.js"(exports2, module2) { - var forge = require_forge(); - require_asn1(); - require_jsbn(); - require_oids(); - require_pkcs1(); - require_prime(); - require_random(); - require_util13(); - if (typeof BigInteger === "undefined") { - BigInteger = forge.jsbn.BigInteger; - } - var BigInteger; - var _crypto = forge.util.isNodejs ? require("crypto") : null; - var asn1 = forge.asn1; - var util = forge.util; - forge.pki = forge.pki || {}; - module2.exports = forge.pki.rsa = forge.rsa = forge.rsa || {}; - var pki2 = forge.pki; - var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; - var privateKeyValidator = { - // PrivateKeyInfo - name: "PrivateKeyInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - // Version (INTEGER) - name: "PrivateKeyInfo.version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyVersion" - }, { - // privateKeyAlgorithm - name: "PrivateKeyInfo.privateKeyAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "AlgorithmIdentifier.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "privateKeyOid" - }] - }, { - // PrivateKey - name: "PrivateKeyInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "privateKey" - }] - }; - var rsaPrivateKeyValidator = { - // RSAPrivateKey - name: "RSAPrivateKey", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - // Version (INTEGER) - name: "RSAPrivateKey.version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyVersion" - }, { - // modulus (n) - name: "RSAPrivateKey.modulus", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyModulus" - }, { - // publicExponent (e) - name: "RSAPrivateKey.publicExponent", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyPublicExponent" - }, { - // privateExponent (d) - name: "RSAPrivateKey.privateExponent", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyPrivateExponent" - }, { - // prime1 (p) - name: "RSAPrivateKey.prime1", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyPrime1" - }, { - // prime2 (q) - name: "RSAPrivateKey.prime2", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyPrime2" - }, { - // exponent1 (d mod (p-1)) - name: "RSAPrivateKey.exponent1", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyExponent1" - }, { - // exponent2 (d mod (q-1)) - name: "RSAPrivateKey.exponent2", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyExponent2" - }, { - // coefficient ((inverse of q) mod p) - name: "RSAPrivateKey.coefficient", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyCoefficient" - }] - }; - var rsaPublicKeyValidator = { - // RSAPublicKey - name: "RSAPublicKey", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - // modulus (n) - name: "RSAPublicKey.modulus", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "publicKeyModulus" - }, { - // publicExponent (e) - name: "RSAPublicKey.exponent", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "publicKeyExponent" - }] - }; - var publicKeyValidator = forge.pki.rsa.publicKeyValidator = { - name: "SubjectPublicKeyInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "subjectPublicKeyInfo", - value: [{ - name: "SubjectPublicKeyInfo.AlgorithmIdentifier", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "AlgorithmIdentifier.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "publicKeyOid" - }] - }, { - // subjectPublicKey - name: "SubjectPublicKeyInfo.subjectPublicKey", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - value: [{ - // RSAPublicKey - name: "SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - optional: true, - captureAsn1: "rsaPublicKey" - }] - }] - }; - var digestInfoValidator = { - name: "DigestInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "DigestInfo.DigestAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "DigestInfo.DigestAlgorithm.algorithmIdentifier", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "algorithmIdentifier" - }, { - // NULL parameters - name: "DigestInfo.DigestAlgorithm.parameters", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.NULL, - // captured only to check existence for md2 and md5 - capture: "parameters", - optional: true, - constructed: false - }] - }, { - // digest - name: "DigestInfo.digest", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "digest" - }] - }; - var emsaPkcs1v15encode = function(md2) { - var oid; - if (md2.algorithm in pki2.oids) { - oid = pki2.oids[md2.algorithm]; - } else { - var error3 = new Error("Unknown message digest algorithm."); - error3.algorithm = md2.algorithm; - throw error3; - } - var oidBytes = asn1.oidToDer(oid).getBytes(); - var digestInfo = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [] - ); - var digestAlgorithm = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [] - ); - digestAlgorithm.value.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - oidBytes - )); - digestAlgorithm.value.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.NULL, - false, - "" - )); - var digest = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - md2.digest().getBytes() - ); - digestInfo.value.push(digestAlgorithm); - digestInfo.value.push(digest); - return asn1.toDer(digestInfo).getBytes(); - }; - var _modPow = function(x, key, pub) { - if (pub) { - return x.modPow(key.e, key.n); - } - if (!key.p || !key.q) { - return x.modPow(key.d, key.n); - } - if (!key.dP) { - key.dP = key.d.mod(key.p.subtract(BigInteger.ONE)); - } - if (!key.dQ) { - key.dQ = key.d.mod(key.q.subtract(BigInteger.ONE)); - } - if (!key.qInv) { - key.qInv = key.q.modInverse(key.p); - } - var r; - do { - r = new BigInteger( - forge.util.bytesToHex(forge.random.getBytes(key.n.bitLength() / 8)), - 16 - ); - } while (r.compareTo(key.n) >= 0 || !r.gcd(key.n).equals(BigInteger.ONE)); - x = x.multiply(r.modPow(key.e, key.n)).mod(key.n); - var xp = x.mod(key.p).modPow(key.dP, key.p); - var xq = x.mod(key.q).modPow(key.dQ, key.q); - while (xp.compareTo(xq) < 0) { - xp = xp.add(key.p); - } - var y = xp.subtract(xq).multiply(key.qInv).mod(key.p).multiply(key.q).add(xq); - y = y.multiply(r.modInverse(key.n)).mod(key.n); - return y; - }; - pki2.rsa.encrypt = function(m, key, bt) { - var pub = bt; - var eb; - var k = Math.ceil(key.n.bitLength() / 8); - if (bt !== false && bt !== true) { - pub = bt === 2; - eb = _encodePkcs1_v1_5(m, key, bt); - } else { - eb = forge.util.createBuffer(); - eb.putBytes(m); - } - var x = new BigInteger(eb.toHex(), 16); - var y = _modPow(x, key, pub); - var yhex = y.toString(16); - var ed = forge.util.createBuffer(); - var zeros = k - Math.ceil(yhex.length / 2); - while (zeros > 0) { - ed.putByte(0); - --zeros; - } - ed.putBytes(forge.util.hexToBytes(yhex)); - return ed.getBytes(); - }; - pki2.rsa.decrypt = function(ed, key, pub, ml) { - var k = Math.ceil(key.n.bitLength() / 8); - if (ed.length !== k) { - var error3 = new Error("Encrypted message length is invalid."); - error3.length = ed.length; - error3.expected = k; - throw error3; - } - var y = new BigInteger(forge.util.createBuffer(ed).toHex(), 16); - if (y.compareTo(key.n) >= 0) { - throw new Error("Encrypted message is invalid."); - } - var x = _modPow(y, key, pub); - var xhex = x.toString(16); - var eb = forge.util.createBuffer(); - var zeros = k - Math.ceil(xhex.length / 2); - while (zeros > 0) { - eb.putByte(0); - --zeros; - } - eb.putBytes(forge.util.hexToBytes(xhex)); - if (ml !== false) { - return _decodePkcs1_v1_5(eb.getBytes(), key, pub); - } - return eb.getBytes(); - }; - pki2.rsa.createKeyPairGenerationState = function(bits, e, options) { - if (typeof bits === "string") { - bits = parseInt(bits, 10); - } - bits = bits || 2048; - options = options || {}; - var prng = options.prng || forge.random; - var rng = { - // x is an array to fill with bytes - nextBytes: function(x) { - var b = prng.getBytesSync(x.length); - for (var i = 0; i < x.length; ++i) { - x[i] = b.charCodeAt(i); - } - } - }; - var algorithm = options.algorithm || "PRIMEINC"; - var rval; - if (algorithm === "PRIMEINC") { - rval = { - algorithm, - state: 0, - bits, - rng, - eInt: e || 65537, - e: new BigInteger(null), - p: null, - q: null, - qBits: bits >> 1, - pBits: bits - (bits >> 1), - pqState: 0, - num: null, - keys: null - }; - rval.e.fromInt(rval.eInt); - } else { - throw new Error("Invalid key generation algorithm: " + algorithm); - } - return rval; - }; - pki2.rsa.stepKeyPairGenerationState = function(state, n) { - if (!("algorithm" in state)) { - state.algorithm = "PRIMEINC"; - } - var THIRTY = new BigInteger(null); - THIRTY.fromInt(30); - var deltaIdx = 0; - var op_or = function(x, y) { - return x | y; - }; - var t1 = +/* @__PURE__ */ new Date(); - var t2; - var total = 0; - while (state.keys === null && (n <= 0 || total < n)) { - if (state.state === 0) { - var bits = state.p === null ? state.pBits : state.qBits; - var bits1 = bits - 1; - if (state.pqState === 0) { - state.num = new BigInteger(bits, state.rng); - if (!state.num.testBit(bits1)) { - state.num.bitwiseTo( - BigInteger.ONE.shiftLeft(bits1), - op_or, - state.num - ); - } - state.num.dAddOffset(31 - state.num.mod(THIRTY).byteValue(), 0); - deltaIdx = 0; - ++state.pqState; - } else if (state.pqState === 1) { - if (state.num.bitLength() > bits) { - state.pqState = 0; - } else if (state.num.isProbablePrime( - _getMillerRabinTests(state.num.bitLength()) - )) { - ++state.pqState; - } else { - state.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); - } - } else if (state.pqState === 2) { - state.pqState = state.num.subtract(BigInteger.ONE).gcd(state.e).compareTo(BigInteger.ONE) === 0 ? 3 : 0; - } else if (state.pqState === 3) { - state.pqState = 0; - if (state.p === null) { - state.p = state.num; - } else { - state.q = state.num; - } - if (state.p !== null && state.q !== null) { - ++state.state; - } - state.num = null; - } - } else if (state.state === 1) { - if (state.p.compareTo(state.q) < 0) { - state.num = state.p; - state.p = state.q; - state.q = state.num; - } - ++state.state; - } else if (state.state === 2) { - state.p1 = state.p.subtract(BigInteger.ONE); - state.q1 = state.q.subtract(BigInteger.ONE); - state.phi = state.p1.multiply(state.q1); - ++state.state; - } else if (state.state === 3) { - if (state.phi.gcd(state.e).compareTo(BigInteger.ONE) === 0) { - ++state.state; - } else { - state.p = null; - state.q = null; - state.state = 0; - } - } else if (state.state === 4) { - state.n = state.p.multiply(state.q); - if (state.n.bitLength() === state.bits) { - ++state.state; - } else { - state.q = null; - state.state = 0; - } - } else if (state.state === 5) { - var d = state.e.modInverse(state.phi); - state.keys = { - privateKey: pki2.rsa.setPrivateKey( - state.n, - state.e, - d, - state.p, - state.q, - d.mod(state.p1), - d.mod(state.q1), - state.q.modInverse(state.p) - ), - publicKey: pki2.rsa.setPublicKey(state.n, state.e) - }; - } - t2 = +/* @__PURE__ */ new Date(); - total += t2 - t1; - t1 = t2; - } - return state.keys !== null; - }; - pki2.rsa.generateKeyPair = function(bits, e, options, callback) { - if (arguments.length === 1) { - if (typeof bits === "object") { - options = bits; - bits = void 0; - } else if (typeof bits === "function") { - callback = bits; - bits = void 0; - } - } else if (arguments.length === 2) { - if (typeof bits === "number") { - if (typeof e === "function") { - callback = e; - e = void 0; - } else if (typeof e !== "number") { - options = e; - e = void 0; - } - } else { - options = bits; - callback = e; - bits = void 0; - e = void 0; - } - } else if (arguments.length === 3) { - if (typeof e === "number") { - if (typeof options === "function") { - callback = options; - options = void 0; - } - } else { - callback = options; - options = e; - e = void 0; - } - } - options = options || {}; - if (bits === void 0) { - bits = options.bits || 2048; - } - if (e === void 0) { - e = options.e || 65537; - } - if (!forge.options.usePureJavaScript && !options.prng && bits >= 256 && bits <= 16384 && (e === 65537 || e === 3)) { - if (callback) { - if (_detectNodeCrypto("generateKeyPair")) { - return _crypto.generateKeyPair("rsa", { - modulusLength: bits, - publicExponent: e, - publicKeyEncoding: { - type: "spki", - format: "pem" - }, - privateKeyEncoding: { - type: "pkcs8", - format: "pem" - } - }, function(err, pub, priv) { - if (err) { - return callback(err); - } - callback(null, { - privateKey: pki2.privateKeyFromPem(priv), - publicKey: pki2.publicKeyFromPem(pub) - }); - }); - } - if (_detectSubtleCrypto("generateKey") && _detectSubtleCrypto("exportKey")) { - return util.globalScope.crypto.subtle.generateKey({ - name: "RSASSA-PKCS1-v1_5", - modulusLength: bits, - publicExponent: _intToUint8Array(e), - hash: { name: "SHA-256" } - }, true, ["sign", "verify"]).then(function(pair) { - return util.globalScope.crypto.subtle.exportKey( - "pkcs8", - pair.privateKey - ); - }).then(void 0, function(err) { - callback(err); - }).then(function(pkcs8) { - if (pkcs8) { - var privateKey = pki2.privateKeyFromAsn1( - asn1.fromDer(forge.util.createBuffer(pkcs8)) - ); - callback(null, { - privateKey, - publicKey: pki2.setRsaPublicKey(privateKey.n, privateKey.e) - }); - } - }); - } - if (_detectSubtleMsCrypto("generateKey") && _detectSubtleMsCrypto("exportKey")) { - var genOp = util.globalScope.msCrypto.subtle.generateKey({ - name: "RSASSA-PKCS1-v1_5", - modulusLength: bits, - publicExponent: _intToUint8Array(e), - hash: { name: "SHA-256" } - }, true, ["sign", "verify"]); - genOp.oncomplete = function(e2) { - var pair = e2.target.result; - var exportOp = util.globalScope.msCrypto.subtle.exportKey( - "pkcs8", - pair.privateKey - ); - exportOp.oncomplete = function(e3) { - var pkcs8 = e3.target.result; - var privateKey = pki2.privateKeyFromAsn1( - asn1.fromDer(forge.util.createBuffer(pkcs8)) - ); - callback(null, { - privateKey, - publicKey: pki2.setRsaPublicKey(privateKey.n, privateKey.e) - }); - }; - exportOp.onerror = function(err) { - callback(err); - }; - }; - genOp.onerror = function(err) { - callback(err); - }; - return; - } - } else { - if (_detectNodeCrypto("generateKeyPairSync")) { - var keypair = _crypto.generateKeyPairSync("rsa", { - modulusLength: bits, - publicExponent: e, - publicKeyEncoding: { - type: "spki", - format: "pem" - }, - privateKeyEncoding: { - type: "pkcs8", - format: "pem" - } - }); - return { - privateKey: pki2.privateKeyFromPem(keypair.privateKey), - publicKey: pki2.publicKeyFromPem(keypair.publicKey) - }; - } - } - } - var state = pki2.rsa.createKeyPairGenerationState(bits, e, options); - if (!callback) { - pki2.rsa.stepKeyPairGenerationState(state, 0); - return state.keys; - } - _generateKeyPair(state, options, callback); - }; - pki2.setRsaPublicKey = pki2.rsa.setPublicKey = function(n, e) { - var key = { - n, - e - }; - key.encrypt = function(data, scheme, schemeOptions) { - if (typeof scheme === "string") { - scheme = scheme.toUpperCase(); - } else if (scheme === void 0) { - scheme = "RSAES-PKCS1-V1_5"; - } - if (scheme === "RSAES-PKCS1-V1_5") { - scheme = { - encode: function(m, key2, pub) { - return _encodePkcs1_v1_5(m, key2, 2).getBytes(); - } - }; - } else if (scheme === "RSA-OAEP" || scheme === "RSAES-OAEP") { - scheme = { - encode: function(m, key2) { - return forge.pkcs1.encode_rsa_oaep(key2, m, schemeOptions); - } - }; - } else if (["RAW", "NONE", "NULL", null].indexOf(scheme) !== -1) { - scheme = { encode: function(e3) { - return e3; - } }; - } else if (typeof scheme === "string") { - throw new Error('Unsupported encryption scheme: "' + scheme + '".'); - } - var e2 = scheme.encode(data, key, true); - return pki2.rsa.encrypt(e2, key, true); - }; - key.verify = function(digest, signature, scheme, options) { - if (typeof scheme === "string") { - scheme = scheme.toUpperCase(); - } else if (scheme === void 0) { - scheme = "RSASSA-PKCS1-V1_5"; - } - if (options === void 0) { - options = { - _parseAllDigestBytes: true, - _skipPaddingChecks: false - }; - } - if (!("_parseAllDigestBytes" in options)) { - options._parseAllDigestBytes = true; - } - if (!("_skipPaddingChecks" in options)) { - options._skipPaddingChecks = false; - } - if (scheme === "RSASSA-PKCS1-V1_5") { - scheme = { - verify: function(digest2, d2) { - d2 = _decodePkcs1_v1_5(d2, key, true, void 0, options); - var obj = asn1.fromDer(d2, { - parseAllBytes: options._parseAllDigestBytes - }); - var capture = {}; - var errors = []; - if (!asn1.validate(obj, digestInfoValidator, capture, errors) || obj.value.length !== 2) { - var error3 = new Error( - "ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value." - ); - error3.errors = errors; - throw error3; - } - var oid = asn1.derToOid(capture.algorithmIdentifier); - if (!(oid === forge.oids.md2 || oid === forge.oids.md5 || oid === forge.oids.sha1 || oid === forge.oids.sha224 || oid === forge.oids.sha256 || oid === forge.oids.sha384 || oid === forge.oids.sha512 || oid === forge.oids["sha512-224"] || oid === forge.oids["sha512-256"])) { - var error3 = new Error( - "Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier." - ); - error3.oid = oid; - throw error3; - } - if (oid === forge.oids.md2 || oid === forge.oids.md5) { - if (!("parameters" in capture)) { - throw new Error( - "ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifier NULL parameters." - ); - } - } - return digest2 === capture.digest; - } - }; - } else if (scheme === "NONE" || scheme === "NULL" || scheme === null) { - scheme = { - verify: function(digest2, d2) { - d2 = _decodePkcs1_v1_5(d2, key, true, void 0, options); - return digest2 === d2; - } - }; - } - var d = pki2.rsa.decrypt(signature, key, true, false); - return scheme.verify(digest, d, key.n.bitLength()); - }; - return key; - }; - pki2.setRsaPrivateKey = pki2.rsa.setPrivateKey = function(n, e, d, p, q, dP, dQ, qInv) { - var key = { - n, - e, - d, - p, - q, - dP, - dQ, - qInv - }; - key.decrypt = function(data, scheme, schemeOptions) { - if (typeof scheme === "string") { - scheme = scheme.toUpperCase(); - } else if (scheme === void 0) { - scheme = "RSAES-PKCS1-V1_5"; - } - var d2 = pki2.rsa.decrypt(data, key, false, false); - if (scheme === "RSAES-PKCS1-V1_5") { - scheme = { decode: _decodePkcs1_v1_5 }; - } else if (scheme === "RSA-OAEP" || scheme === "RSAES-OAEP") { - scheme = { - decode: function(d3, key2) { - return forge.pkcs1.decode_rsa_oaep(key2, d3, schemeOptions); - } - }; - } else if (["RAW", "NONE", "NULL", null].indexOf(scheme) !== -1) { - scheme = { decode: function(d3) { - return d3; - } }; - } else { - throw new Error('Unsupported encryption scheme: "' + scheme + '".'); - } - return scheme.decode(d2, key, false); - }; - key.sign = function(md2, scheme) { - var bt = false; - if (typeof scheme === "string") { - scheme = scheme.toUpperCase(); - } - if (scheme === void 0 || scheme === "RSASSA-PKCS1-V1_5") { - scheme = { encode: emsaPkcs1v15encode }; - bt = 1; - } else if (scheme === "NONE" || scheme === "NULL" || scheme === null) { - scheme = { encode: function() { - return md2; - } }; - bt = 1; - } - var d2 = scheme.encode(md2, key.n.bitLength()); - return pki2.rsa.encrypt(d2, key, bt); - }; - return key; - }; - pki2.wrapRsaPrivateKey = function(rsaKey) { - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // version (0) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(0).getBytes() - ), - // privateKeyAlgorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki2.oids.rsaEncryption).getBytes() - ), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]), - // PrivateKey - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - asn1.toDer(rsaKey).getBytes() - ) - ]); - }; - pki2.privateKeyFromAsn1 = function(obj) { - var capture = {}; - var errors = []; - if (asn1.validate(obj, privateKeyValidator, capture, errors)) { - obj = asn1.fromDer(forge.util.createBuffer(capture.privateKey)); - } - capture = {}; - errors = []; - if (!asn1.validate(obj, rsaPrivateKeyValidator, capture, errors)) { - var error3 = new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey."); - error3.errors = errors; - throw error3; - } - var n, e, d, p, q, dP, dQ, qInv; - n = forge.util.createBuffer(capture.privateKeyModulus).toHex(); - e = forge.util.createBuffer(capture.privateKeyPublicExponent).toHex(); - d = forge.util.createBuffer(capture.privateKeyPrivateExponent).toHex(); - p = forge.util.createBuffer(capture.privateKeyPrime1).toHex(); - q = forge.util.createBuffer(capture.privateKeyPrime2).toHex(); - dP = forge.util.createBuffer(capture.privateKeyExponent1).toHex(); - dQ = forge.util.createBuffer(capture.privateKeyExponent2).toHex(); - qInv = forge.util.createBuffer(capture.privateKeyCoefficient).toHex(); - return pki2.setRsaPrivateKey( - new BigInteger(n, 16), - new BigInteger(e, 16), - new BigInteger(d, 16), - new BigInteger(p, 16), - new BigInteger(q, 16), - new BigInteger(dP, 16), - new BigInteger(dQ, 16), - new BigInteger(qInv, 16) - ); - }; - pki2.privateKeyToAsn1 = pki2.privateKeyToRSAPrivateKey = function(key) { - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // version (0 = only 2 primes, 1 multiple primes) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(0).getBytes() - ), - // modulus (n) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.n) - ), - // publicExponent (e) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.e) - ), - // privateExponent (d) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.d) - ), - // privateKeyPrime1 (p) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.p) - ), - // privateKeyPrime2 (q) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.q) - ), - // privateKeyExponent1 (dP) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.dP) - ), - // privateKeyExponent2 (dQ) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.dQ) - ), - // coefficient (qInv) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.qInv) - ) - ]); - }; - pki2.publicKeyFromAsn1 = function(obj) { - var capture = {}; - var errors = []; - if (asn1.validate(obj, publicKeyValidator, capture, errors)) { - var oid = asn1.derToOid(capture.publicKeyOid); - if (oid !== pki2.oids.rsaEncryption) { - var error3 = new Error("Cannot read public key. Unknown OID."); - error3.oid = oid; - throw error3; - } - obj = capture.rsaPublicKey; - } - errors = []; - if (!asn1.validate(obj, rsaPublicKeyValidator, capture, errors)) { - var error3 = new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey."); - error3.errors = errors; - throw error3; - } - var n = forge.util.createBuffer(capture.publicKeyModulus).toHex(); - var e = forge.util.createBuffer(capture.publicKeyExponent).toHex(); - return pki2.setRsaPublicKey( - new BigInteger(n, 16), - new BigInteger(e, 16) - ); - }; - pki2.publicKeyToAsn1 = pki2.publicKeyToSubjectPublicKeyInfo = function(key) { - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // AlgorithmIdentifier - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki2.oids.rsaEncryption).getBytes() - ), - // parameters (null) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]), - // subjectPublicKey - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, [ - pki2.publicKeyToRSAPublicKey(key) - ]) - ]); - }; - pki2.publicKeyToRSAPublicKey = function(key) { - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // modulus (n) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.n) - ), - // publicExponent (e) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.e) - ) - ]); - }; - function _encodePkcs1_v1_5(m, key, bt) { - var eb = forge.util.createBuffer(); - var k = Math.ceil(key.n.bitLength() / 8); - if (m.length > k - 11) { - var error3 = new Error("Message is too long for PKCS#1 v1.5 padding."); - error3.length = m.length; - error3.max = k - 11; - throw error3; - } - eb.putByte(0); - eb.putByte(bt); - var padNum = k - 3 - m.length; - var padByte; - if (bt === 0 || bt === 1) { - padByte = bt === 0 ? 0 : 255; - for (var i = 0; i < padNum; ++i) { - eb.putByte(padByte); - } - } else { - while (padNum > 0) { - var numZeros = 0; - var padBytes = forge.random.getBytes(padNum); - for (var i = 0; i < padNum; ++i) { - padByte = padBytes.charCodeAt(i); - if (padByte === 0) { - ++numZeros; - } else { - eb.putByte(padByte); - } - } - padNum = numZeros; - } - } - eb.putByte(0); - eb.putBytes(m); - return eb; - } - function _decodePkcs1_v1_5(em, key, pub, ml, options) { - var k = Math.ceil(key.n.bitLength() / 8); - var eb = forge.util.createBuffer(em); - var first = eb.getByte(); - var bt = eb.getByte(); - if (first !== 0 || pub && bt !== 0 && bt !== 1 || !pub && bt !== 2 || pub && bt === 0 && typeof ml === "undefined") { - throw new Error("Encryption block is invalid."); - } - var padNum = 0; - if (bt === 0) { - padNum = k - 3 - ml; - for (var i = 0; i < padNum; ++i) { - if (eb.getByte() !== 0) { - throw new Error("Encryption block is invalid."); - } - } - } else if (bt === 1) { - padNum = 0; - while (eb.length() > 1) { - if (eb.getByte() !== 255) { - --eb.read; - break; - } - ++padNum; - } - if (padNum < 8 && !(options ? options._skipPaddingChecks : false)) { - throw new Error("Encryption block is invalid."); - } - } else if (bt === 2) { - padNum = 0; - while (eb.length() > 1) { - if (eb.getByte() === 0) { - --eb.read; - break; - } - ++padNum; - } - if (padNum < 8 && !(options ? options._skipPaddingChecks : false)) { - throw new Error("Encryption block is invalid."); - } - } - var zero = eb.getByte(); - if (zero !== 0 || padNum !== k - 3 - eb.length()) { - throw new Error("Encryption block is invalid."); - } - return eb.getBytes(); - } - function _generateKeyPair(state, options, callback) { - if (typeof options === "function") { - callback = options; - options = {}; - } - options = options || {}; - var opts = { - algorithm: { - name: options.algorithm || "PRIMEINC", - options: { - workers: options.workers || 2, - workLoad: options.workLoad || 100, - workerScript: options.workerScript - } - } - }; - if ("prng" in options) { - opts.prng = options.prng; - } - generate(); - function generate() { - getPrime(state.pBits, function(err, num) { - if (err) { - return callback(err); - } - state.p = num; - if (state.q !== null) { - return finish(err, state.q); - } - getPrime(state.qBits, finish); - }); - } - function getPrime(bits, callback2) { - forge.prime.generateProbablePrime(bits, opts, callback2); - } - function finish(err, num) { - if (err) { - return callback(err); - } - state.q = num; - if (state.p.compareTo(state.q) < 0) { - var tmp = state.p; - state.p = state.q; - state.q = tmp; - } - if (state.p.subtract(BigInteger.ONE).gcd(state.e).compareTo(BigInteger.ONE) !== 0) { - state.p = null; - generate(); - return; - } - if (state.q.subtract(BigInteger.ONE).gcd(state.e).compareTo(BigInteger.ONE) !== 0) { - state.q = null; - getPrime(state.qBits, finish); - return; - } - state.p1 = state.p.subtract(BigInteger.ONE); - state.q1 = state.q.subtract(BigInteger.ONE); - state.phi = state.p1.multiply(state.q1); - if (state.phi.gcd(state.e).compareTo(BigInteger.ONE) !== 0) { - state.p = state.q = null; - generate(); - return; - } - state.n = state.p.multiply(state.q); - if (state.n.bitLength() !== state.bits) { - state.q = null; - getPrime(state.qBits, finish); - return; - } - var d = state.e.modInverse(state.phi); - state.keys = { - privateKey: pki2.rsa.setPrivateKey( - state.n, - state.e, - d, - state.p, - state.q, - d.mod(state.p1), - d.mod(state.q1), - state.q.modInverse(state.p) - ), - publicKey: pki2.rsa.setPublicKey(state.n, state.e) - }; - callback(null, state.keys); - } - } - function _bnToBytes(b) { - var hex = b.toString(16); - if (hex[0] >= "8") { - hex = "00" + hex; - } - var bytes = forge.util.hexToBytes(hex); - if (bytes.length > 1 && // leading 0x00 for positive integer - (bytes.charCodeAt(0) === 0 && (bytes.charCodeAt(1) & 128) === 0 || // leading 0xFF for negative integer - bytes.charCodeAt(0) === 255 && (bytes.charCodeAt(1) & 128) === 128)) { - return bytes.substr(1); - } - return bytes; - } - function _getMillerRabinTests(bits) { - if (bits <= 100) return 27; - if (bits <= 150) return 18; - if (bits <= 200) return 15; - if (bits <= 250) return 12; - if (bits <= 300) return 9; - if (bits <= 350) return 8; - if (bits <= 400) return 7; - if (bits <= 500) return 6; - if (bits <= 600) return 5; - if (bits <= 800) return 4; - if (bits <= 1250) return 3; - return 2; - } - function _detectNodeCrypto(fn) { - return forge.util.isNodejs && typeof _crypto[fn] === "function"; - } - function _detectSubtleCrypto(fn) { - return typeof util.globalScope !== "undefined" && typeof util.globalScope.crypto === "object" && typeof util.globalScope.crypto.subtle === "object" && typeof util.globalScope.crypto.subtle[fn] === "function"; - } - function _detectSubtleMsCrypto(fn) { - return typeof util.globalScope !== "undefined" && typeof util.globalScope.msCrypto === "object" && typeof util.globalScope.msCrypto.subtle === "object" && typeof util.globalScope.msCrypto.subtle[fn] === "function"; - } - function _intToUint8Array(x) { - var bytes = forge.util.hexToBytes(x.toString(16)); - var buffer = new Uint8Array(bytes.length); - for (var i = 0; i < bytes.length; ++i) { - buffer[i] = bytes.charCodeAt(i); - } - return buffer; - } - } -}); - -// node_modules/node-forge/lib/pbe.js -var require_pbe = __commonJS({ - "node_modules/node-forge/lib/pbe.js"(exports2, module2) { - var forge = require_forge(); - require_aes(); - require_asn1(); - require_des(); - require_md(); - require_oids(); - require_pbkdf2(); - require_pem(); - require_random(); - require_rc2(); - require_rsa(); - require_util13(); - if (typeof BigInteger === "undefined") { - BigInteger = forge.jsbn.BigInteger; - } - var BigInteger; - var asn1 = forge.asn1; - var pki2 = forge.pki = forge.pki || {}; - module2.exports = pki2.pbe = forge.pbe = forge.pbe || {}; - var oids = pki2.oids; - var encryptedPrivateKeyValidator = { - name: "EncryptedPrivateKeyInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "EncryptedPrivateKeyInfo.encryptionAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "AlgorithmIdentifier.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "encryptionOid" - }, { - name: "AlgorithmIdentifier.parameters", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "encryptionParams" - }] - }, { - // encryptedData - name: "EncryptedPrivateKeyInfo.encryptedData", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "encryptedData" - }] - }; - var PBES2AlgorithmsValidator = { - name: "PBES2Algorithms", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "PBES2Algorithms.keyDerivationFunc", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "PBES2Algorithms.keyDerivationFunc.oid", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "kdfOid" - }, { - name: "PBES2Algorithms.params", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "PBES2Algorithms.params.salt", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "kdfSalt" - }, { - name: "PBES2Algorithms.params.iterationCount", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "kdfIterationCount" - }, { - name: "PBES2Algorithms.params.keyLength", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - optional: true, - capture: "keyLength" - }, { - // prf - name: "PBES2Algorithms.params.prf", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - optional: true, - value: [{ - name: "PBES2Algorithms.params.prf.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "prfOid" - }] - }] - }] - }, { - name: "PBES2Algorithms.encryptionScheme", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "PBES2Algorithms.encryptionScheme.oid", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "encOid" - }, { - name: "PBES2Algorithms.encryptionScheme.iv", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "encIv" - }] - }] - }; - var pkcs12PbeParamsValidator = { - name: "pkcs-12PbeParams", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "pkcs-12PbeParams.salt", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "salt" - }, { - name: "pkcs-12PbeParams.iterations", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "iterations" - }] - }; - pki2.encryptPrivateKeyInfo = function(obj, password, options) { - options = options || {}; - options.saltSize = options.saltSize || 8; - options.count = options.count || 2048; - options.algorithm = options.algorithm || "aes128"; - options.prfAlgorithm = options.prfAlgorithm || "sha1"; - var salt = forge.random.getBytesSync(options.saltSize); - var count = options.count; - var countBytes = asn1.integerToDer(count); - var dkLen; - var encryptionAlgorithm; - var encryptedData; - if (options.algorithm.indexOf("aes") === 0 || options.algorithm === "des") { - var ivLen, encOid, cipherFn; - switch (options.algorithm) { - case "aes128": - dkLen = 16; - ivLen = 16; - encOid = oids["aes128-CBC"]; - cipherFn = forge.aes.createEncryptionCipher; - break; - case "aes192": - dkLen = 24; - ivLen = 16; - encOid = oids["aes192-CBC"]; - cipherFn = forge.aes.createEncryptionCipher; - break; - case "aes256": - dkLen = 32; - ivLen = 16; - encOid = oids["aes256-CBC"]; - cipherFn = forge.aes.createEncryptionCipher; - break; - case "des": - dkLen = 8; - ivLen = 8; - encOid = oids["desCBC"]; - cipherFn = forge.des.createEncryptionCipher; - break; - default: - var error3 = new Error("Cannot encrypt private key. Unknown encryption algorithm."); - error3.algorithm = options.algorithm; - throw error3; - } - var prfAlgorithm = "hmacWith" + options.prfAlgorithm.toUpperCase(); - var md2 = prfAlgorithmToMessageDigest(prfAlgorithm); - var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md2); - var iv = forge.random.getBytesSync(ivLen); - var cipher = cipherFn(dk); - cipher.start(iv); - cipher.update(asn1.toDer(obj)); - cipher.finish(); - encryptedData = cipher.output.getBytes(); - var params = createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm); - encryptionAlgorithm = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(oids["pkcs5PBES2"]).getBytes() - ), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // keyDerivationFunc - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(oids["pkcs5PBKDF2"]).getBytes() - ), - // PBKDF2-params - params - ]), - // encryptionScheme - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(encOid).getBytes() - ), - // iv - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - iv - ) - ]) - ]) - ] - ); - } else if (options.algorithm === "3des") { - dkLen = 24; - var saltBytes = new forge.util.ByteBuffer(salt); - var dk = pki2.pbe.generatePkcs12Key(password, saltBytes, 1, count, dkLen); - var iv = pki2.pbe.generatePkcs12Key(password, saltBytes, 2, count, dkLen); - var cipher = forge.des.createEncryptionCipher(dk); - cipher.start(iv); - cipher.update(asn1.toDer(obj)); - cipher.finish(); - encryptedData = cipher.output.getBytes(); - encryptionAlgorithm = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes() - ), - // pkcs-12PbeParams - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // salt - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt), - // iteration count - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - countBytes.getBytes() - ) - ]) - ] - ); - } else { - var error3 = new Error("Cannot encrypt private key. Unknown encryption algorithm."); - error3.algorithm = options.algorithm; - throw error3; - } - var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // encryptionAlgorithm - encryptionAlgorithm, - // encryptedData - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - encryptedData - ) - ]); - return rval; - }; - pki2.decryptPrivateKeyInfo = function(obj, password) { - var rval = null; - var capture = {}; - var errors = []; - if (!asn1.validate(obj, encryptedPrivateKeyValidator, capture, errors)) { - var error3 = new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo."); - error3.errors = errors; - throw error3; - } - var oid = asn1.derToOid(capture.encryptionOid); - var cipher = pki2.pbe.getCipher(oid, capture.encryptionParams, password); - var encrypted = forge.util.createBuffer(capture.encryptedData); - cipher.update(encrypted); - if (cipher.finish()) { - rval = asn1.fromDer(cipher.output); - } - return rval; - }; - pki2.encryptedPrivateKeyToPem = function(epki, maxline) { - var msg = { - type: "ENCRYPTED PRIVATE KEY", - body: asn1.toDer(epki).getBytes() - }; - return forge.pem.encode(msg, { maxline }); - }; - pki2.encryptedPrivateKeyFromPem = function(pem) { - var msg = forge.pem.decode(pem)[0]; - if (msg.type !== "ENCRYPTED PRIVATE KEY") { - var error3 = new Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".'); - error3.headerType = msg.type; - throw error3; - } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error("Could not convert encrypted private key from PEM; PEM is encrypted."); - } - return asn1.fromDer(msg.body); - }; - pki2.encryptRsaPrivateKey = function(rsaKey, password, options) { - options = options || {}; - if (!options.legacy) { - var rval = pki2.wrapRsaPrivateKey(pki2.privateKeyToAsn1(rsaKey)); - rval = pki2.encryptPrivateKeyInfo(rval, password, options); - return pki2.encryptedPrivateKeyToPem(rval); - } - var algorithm; - var iv; - var dkLen; - var cipherFn; - switch (options.algorithm) { - case "aes128": - algorithm = "AES-128-CBC"; - dkLen = 16; - iv = forge.random.getBytesSync(16); - cipherFn = forge.aes.createEncryptionCipher; - break; - case "aes192": - algorithm = "AES-192-CBC"; - dkLen = 24; - iv = forge.random.getBytesSync(16); - cipherFn = forge.aes.createEncryptionCipher; - break; - case "aes256": - algorithm = "AES-256-CBC"; - dkLen = 32; - iv = forge.random.getBytesSync(16); - cipherFn = forge.aes.createEncryptionCipher; - break; - case "3des": - algorithm = "DES-EDE3-CBC"; - dkLen = 24; - iv = forge.random.getBytesSync(8); - cipherFn = forge.des.createEncryptionCipher; - break; - case "des": - algorithm = "DES-CBC"; - dkLen = 8; - iv = forge.random.getBytesSync(8); - cipherFn = forge.des.createEncryptionCipher; - break; - default: - var error3 = new Error('Could not encrypt RSA private key; unsupported encryption algorithm "' + options.algorithm + '".'); - error3.algorithm = options.algorithm; - throw error3; - } - var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen); - var cipher = cipherFn(dk); - cipher.start(iv); - cipher.update(asn1.toDer(pki2.privateKeyToAsn1(rsaKey))); - cipher.finish(); - var msg = { - type: "RSA PRIVATE KEY", - procType: { - version: "4", - type: "ENCRYPTED" - }, - dekInfo: { - algorithm, - parameters: forge.util.bytesToHex(iv).toUpperCase() - }, - body: cipher.output.getBytes() - }; - return forge.pem.encode(msg); - }; - pki2.decryptRsaPrivateKey = function(pem, password) { - var rval = null; - var msg = forge.pem.decode(pem)[0]; - if (msg.type !== "ENCRYPTED PRIVATE KEY" && msg.type !== "PRIVATE KEY" && msg.type !== "RSA PRIVATE KEY") { - var error3 = new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".'); - error3.headerType = error3; - throw error3; - } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - var dkLen; - var cipherFn; - switch (msg.dekInfo.algorithm) { - case "DES-CBC": - dkLen = 8; - cipherFn = forge.des.createDecryptionCipher; - break; - case "DES-EDE3-CBC": - dkLen = 24; - cipherFn = forge.des.createDecryptionCipher; - break; - case "AES-128-CBC": - dkLen = 16; - cipherFn = forge.aes.createDecryptionCipher; - break; - case "AES-192-CBC": - dkLen = 24; - cipherFn = forge.aes.createDecryptionCipher; - break; - case "AES-256-CBC": - dkLen = 32; - cipherFn = forge.aes.createDecryptionCipher; - break; - case "RC2-40-CBC": - dkLen = 5; - cipherFn = function(key) { - return forge.rc2.createDecryptionCipher(key, 40); - }; - break; - case "RC2-64-CBC": - dkLen = 8; - cipherFn = function(key) { - return forge.rc2.createDecryptionCipher(key, 64); - }; - break; - case "RC2-128-CBC": - dkLen = 16; - cipherFn = function(key) { - return forge.rc2.createDecryptionCipher(key, 128); - }; - break; - default: - var error3 = new Error('Could not decrypt private key; unsupported encryption algorithm "' + msg.dekInfo.algorithm + '".'); - error3.algorithm = msg.dekInfo.algorithm; - throw error3; - } - var iv = forge.util.hexToBytes(msg.dekInfo.parameters); - var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen); - var cipher = cipherFn(dk); - cipher.start(iv); - cipher.update(forge.util.createBuffer(msg.body)); - if (cipher.finish()) { - rval = cipher.output.getBytes(); - } else { - return rval; - } - } else { - rval = msg.body; - } - if (msg.type === "ENCRYPTED PRIVATE KEY") { - rval = pki2.decryptPrivateKeyInfo(asn1.fromDer(rval), password); - } else { - rval = asn1.fromDer(rval); - } - if (rval !== null) { - rval = pki2.privateKeyFromAsn1(rval); - } - return rval; - }; - pki2.pbe.generatePkcs12Key = function(password, salt, id, iter, n, md2) { - var j, l; - if (typeof md2 === "undefined" || md2 === null) { - if (!("sha1" in forge.md)) { - throw new Error('"sha1" hash algorithm unavailable.'); - } - md2 = forge.md.sha1.create(); - } - var u = md2.digestLength; - var v = md2.blockLength; - var result = new forge.util.ByteBuffer(); - var passBuf = new forge.util.ByteBuffer(); - if (password !== null && password !== void 0) { - for (l = 0; l < password.length; l++) { - passBuf.putInt16(password.charCodeAt(l)); - } - passBuf.putInt16(0); - } - var p = passBuf.length(); - var s = salt.length(); - var D = new forge.util.ByteBuffer(); - D.fillWithByte(id, v); - var Slen = v * Math.ceil(s / v); - var S = new forge.util.ByteBuffer(); - for (l = 0; l < Slen; l++) { - S.putByte(salt.at(l % s)); - } - var Plen = v * Math.ceil(p / v); - var P = new forge.util.ByteBuffer(); - for (l = 0; l < Plen; l++) { - P.putByte(passBuf.at(l % p)); - } - var I = S; - I.putBuffer(P); - var c = Math.ceil(n / u); - for (var i = 1; i <= c; i++) { - var buf = new forge.util.ByteBuffer(); - buf.putBytes(D.bytes()); - buf.putBytes(I.bytes()); - for (var round = 0; round < iter; round++) { - md2.start(); - md2.update(buf.getBytes()); - buf = md2.digest(); - } - var B = new forge.util.ByteBuffer(); - for (l = 0; l < v; l++) { - B.putByte(buf.at(l % u)); - } - var k = Math.ceil(s / v) + Math.ceil(p / v); - var Inew = new forge.util.ByteBuffer(); - for (j = 0; j < k; j++) { - var chunk = new forge.util.ByteBuffer(I.getBytes(v)); - var x = 511; - for (l = B.length() - 1; l >= 0; l--) { - x = x >> 8; - x += B.at(l) + chunk.at(l); - chunk.setAt(l, x & 255); - } - Inew.putBuffer(chunk); - } - I = Inew; - result.putBuffer(buf); - } - result.truncate(result.length() - n); - return result; - }; - pki2.pbe.getCipher = function(oid, params, password) { - switch (oid) { - case pki2.oids["pkcs5PBES2"]: - return pki2.pbe.getCipherForPBES2(oid, params, password); - case pki2.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]: - case pki2.oids["pbewithSHAAnd40BitRC2-CBC"]: - return pki2.pbe.getCipherForPKCS12PBE(oid, params, password); - default: - var error3 = new Error("Cannot read encrypted PBE data block. Unsupported OID."); - error3.oid = oid; - error3.supportedOids = [ - "pkcs5PBES2", - "pbeWithSHAAnd3-KeyTripleDES-CBC", - "pbewithSHAAnd40BitRC2-CBC" - ]; - throw error3; - } - }; - pki2.pbe.getCipherForPBES2 = function(oid, params, password) { - var capture = {}; - var errors = []; - if (!asn1.validate(params, PBES2AlgorithmsValidator, capture, errors)) { - var error3 = new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo."); - error3.errors = errors; - throw error3; - } - oid = asn1.derToOid(capture.kdfOid); - if (oid !== pki2.oids["pkcs5PBKDF2"]) { - var error3 = new Error("Cannot read encrypted private key. Unsupported key derivation function OID."); - error3.oid = oid; - error3.supportedOids = ["pkcs5PBKDF2"]; - throw error3; - } - oid = asn1.derToOid(capture.encOid); - if (oid !== pki2.oids["aes128-CBC"] && oid !== pki2.oids["aes192-CBC"] && oid !== pki2.oids["aes256-CBC"] && oid !== pki2.oids["des-EDE3-CBC"] && oid !== pki2.oids["desCBC"]) { - var error3 = new Error("Cannot read encrypted private key. Unsupported encryption scheme OID."); - error3.oid = oid; - error3.supportedOids = [ - "aes128-CBC", - "aes192-CBC", - "aes256-CBC", - "des-EDE3-CBC", - "desCBC" - ]; - throw error3; - } - var salt = capture.kdfSalt; - var count = forge.util.createBuffer(capture.kdfIterationCount); - count = count.getInt(count.length() << 3); - var dkLen; - var cipherFn; - switch (pki2.oids[oid]) { - case "aes128-CBC": - dkLen = 16; - cipherFn = forge.aes.createDecryptionCipher; - break; - case "aes192-CBC": - dkLen = 24; - cipherFn = forge.aes.createDecryptionCipher; - break; - case "aes256-CBC": - dkLen = 32; - cipherFn = forge.aes.createDecryptionCipher; - break; - case "des-EDE3-CBC": - dkLen = 24; - cipherFn = forge.des.createDecryptionCipher; - break; - case "desCBC": - dkLen = 8; - cipherFn = forge.des.createDecryptionCipher; - break; - } - var md2 = prfOidToMessageDigest(capture.prfOid); - var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md2); - var iv = capture.encIv; - var cipher = cipherFn(dk); - cipher.start(iv); - return cipher; - }; - pki2.pbe.getCipherForPKCS12PBE = function(oid, params, password) { - var capture = {}; - var errors = []; - if (!asn1.validate(params, pkcs12PbeParamsValidator, capture, errors)) { - var error3 = new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo."); - error3.errors = errors; - throw error3; - } - var salt = forge.util.createBuffer(capture.salt); - var count = forge.util.createBuffer(capture.iterations); - count = count.getInt(count.length() << 3); - var dkLen, dIvLen, cipherFn; - switch (oid) { - case pki2.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]: - dkLen = 24; - dIvLen = 8; - cipherFn = forge.des.startDecrypting; - break; - case pki2.oids["pbewithSHAAnd40BitRC2-CBC"]: - dkLen = 5; - dIvLen = 8; - cipherFn = function(key2, iv2) { - var cipher = forge.rc2.createDecryptionCipher(key2, 40); - cipher.start(iv2, null); - return cipher; - }; - break; - default: - var error3 = new Error("Cannot read PKCS #12 PBE data block. Unsupported OID."); - error3.oid = oid; - throw error3; - } - var md2 = prfOidToMessageDigest(capture.prfOid); - var key = pki2.pbe.generatePkcs12Key(password, salt, 1, count, dkLen, md2); - md2.start(); - var iv = pki2.pbe.generatePkcs12Key(password, salt, 2, count, dIvLen, md2); - return cipherFn(key, iv); - }; - pki2.pbe.opensslDeriveBytes = function(password, salt, dkLen, md2) { - if (typeof md2 === "undefined" || md2 === null) { - if (!("md5" in forge.md)) { - throw new Error('"md5" hash algorithm unavailable.'); - } - md2 = forge.md.md5.create(); - } - if (salt === null) { - salt = ""; - } - var digests = [hash(md2, password + salt)]; - for (var length = 16, i = 1; length < dkLen; ++i, length += 16) { - digests.push(hash(md2, digests[i - 1] + password + salt)); - } - return digests.join("").substr(0, dkLen); - }; - function hash(md2, bytes) { - return md2.start().update(bytes).digest().getBytes(); - } - function prfOidToMessageDigest(prfOid) { - var prfAlgorithm; - if (!prfOid) { - prfAlgorithm = "hmacWithSHA1"; - } else { - prfAlgorithm = pki2.oids[asn1.derToOid(prfOid)]; - if (!prfAlgorithm) { - var error3 = new Error("Unsupported PRF OID."); - error3.oid = prfOid; - error3.supported = [ - "hmacWithSHA1", - "hmacWithSHA224", - "hmacWithSHA256", - "hmacWithSHA384", - "hmacWithSHA512" - ]; - throw error3; - } - } - return prfAlgorithmToMessageDigest(prfAlgorithm); - } - function prfAlgorithmToMessageDigest(prfAlgorithm) { - var factory = forge.md; - switch (prfAlgorithm) { - case "hmacWithSHA224": - factory = forge.md.sha512; - case "hmacWithSHA1": - case "hmacWithSHA256": - case "hmacWithSHA384": - case "hmacWithSHA512": - prfAlgorithm = prfAlgorithm.substr(8).toLowerCase(); - break; - default: - var error3 = new Error("Unsupported PRF algorithm."); - error3.algorithm = prfAlgorithm; - error3.supported = [ - "hmacWithSHA1", - "hmacWithSHA224", - "hmacWithSHA256", - "hmacWithSHA384", - "hmacWithSHA512" - ]; - throw error3; - } - if (!factory || !(prfAlgorithm in factory)) { - throw new Error("Unknown hash algorithm: " + prfAlgorithm); - } - return factory[prfAlgorithm].create(); - } - function createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm) { - var params = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // salt - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - salt - ), - // iteration count - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - countBytes.getBytes() - ) - ]); - if (prfAlgorithm !== "hmacWithSHA1") { - params.value.push( - // key length - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - forge.util.hexToBytes(dkLen.toString(16)) - ), - // AlgorithmIdentifier - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki2.oids[prfAlgorithm]).getBytes() - ), - // parameters (null) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]) - ); - } - return params; - } - } -}); - -// node_modules/node-forge/lib/pkcs7asn1.js -var require_pkcs7asn1 = __commonJS({ - "node_modules/node-forge/lib/pkcs7asn1.js"(exports2, module2) { - var forge = require_forge(); - require_asn1(); - require_util13(); - var asn1 = forge.asn1; - var p7v = module2.exports = forge.pkcs7asn1 = forge.pkcs7asn1 || {}; - forge.pkcs7 = forge.pkcs7 || {}; - forge.pkcs7.asn1 = p7v; - var contentInfoValidator = { - name: "ContentInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "ContentInfo.ContentType", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "contentType" - }, { - name: "ContentInfo.content", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - constructed: true, - optional: true, - captureAsn1: "content" - }] - }; - p7v.contentInfoValidator = contentInfoValidator; - var encryptedContentInfoValidator = { - name: "EncryptedContentInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "EncryptedContentInfo.contentType", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "contentType" - }, { - name: "EncryptedContentInfo.contentEncryptionAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "EncryptedContentInfo.contentEncryptionAlgorithm.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "encAlgorithm" - }, { - name: "EncryptedContentInfo.contentEncryptionAlgorithm.parameter", - tagClass: asn1.Class.UNIVERSAL, - captureAsn1: "encParameter" - }] - }, { - name: "EncryptedContentInfo.encryptedContent", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - /* The PKCS#7 structure output by OpenSSL somewhat differs from what - * other implementations do generate. - * - * OpenSSL generates a structure like this: - * SEQUENCE { - * ... - * [0] - * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38 - * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45 - * ... - * } - * - * Whereas other implementations (and this PKCS#7 module) generate: - * SEQUENCE { - * ... - * [0] { - * OCTET STRING - * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38 - * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45 - * ... - * } - * } - * - * In order to support both, we just capture the context specific - * field here. The OCTET STRING bit is removed below. - */ - capture: "encryptedContent", - captureAsn1: "encryptedContentAsn1" - }] - }; - p7v.envelopedDataValidator = { - name: "EnvelopedData", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "EnvelopedData.Version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "version" - }, { - name: "EnvelopedData.RecipientInfos", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SET, - constructed: true, - captureAsn1: "recipientInfos" - }].concat(encryptedContentInfoValidator) - }; - p7v.encryptedDataValidator = { - name: "EncryptedData", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "EncryptedData.Version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "version" - }].concat(encryptedContentInfoValidator) - }; - var signerValidator = { - name: "SignerInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "SignerInfo.version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false - }, { - name: "SignerInfo.issuerAndSerialNumber", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "SignerInfo.issuerAndSerialNumber.issuer", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "issuer" - }, { - name: "SignerInfo.issuerAndSerialNumber.serialNumber", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "serial" - }] - }, { - name: "SignerInfo.digestAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "SignerInfo.digestAlgorithm.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "digestAlgorithm" - }, { - name: "SignerInfo.digestAlgorithm.parameter", - tagClass: asn1.Class.UNIVERSAL, - constructed: false, - captureAsn1: "digestParameter", - optional: true - }] - }, { - name: "SignerInfo.authenticatedAttributes", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - constructed: true, - optional: true, - capture: "authenticatedAttributes" - }, { - name: "SignerInfo.digestEncryptionAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - capture: "signatureAlgorithm" - }, { - name: "SignerInfo.encryptedDigest", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "signature" - }, { - name: "SignerInfo.unauthenticatedAttributes", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 1, - constructed: true, - optional: true, - capture: "unauthenticatedAttributes" - }] - }; - p7v.signedDataValidator = { - name: "SignedData", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [ - { - name: "SignedData.Version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "version" - }, - { - name: "SignedData.DigestAlgorithms", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SET, - constructed: true, - captureAsn1: "digestAlgorithms" - }, - contentInfoValidator, - { - name: "SignedData.Certificates", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - optional: true, - captureAsn1: "certificates" - }, - { - name: "SignedData.CertificateRevocationLists", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 1, - optional: true, - captureAsn1: "crls" - }, - { - name: "SignedData.SignerInfos", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SET, - capture: "signerInfos", - optional: true, - value: [signerValidator] - } - ] - }; - p7v.recipientInfoValidator = { - name: "RecipientInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "RecipientInfo.version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "version" - }, { - name: "RecipientInfo.issuerAndSerial", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "RecipientInfo.issuerAndSerial.issuer", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "issuer" - }, { - name: "RecipientInfo.issuerAndSerial.serialNumber", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "serial" - }] - }, { - name: "RecipientInfo.keyEncryptionAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "RecipientInfo.keyEncryptionAlgorithm.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "encAlgorithm" - }, { - name: "RecipientInfo.keyEncryptionAlgorithm.parameter", - tagClass: asn1.Class.UNIVERSAL, - constructed: false, - captureAsn1: "encParameter", - optional: true - }] - }, { - name: "RecipientInfo.encryptedKey", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "encKey" - }] - }; - } -}); - -// node_modules/node-forge/lib/mgf1.js -var require_mgf1 = __commonJS({ - "node_modules/node-forge/lib/mgf1.js"(exports2, module2) { - var forge = require_forge(); - require_util13(); - forge.mgf = forge.mgf || {}; - var mgf1 = module2.exports = forge.mgf.mgf1 = forge.mgf1 = forge.mgf1 || {}; - mgf1.create = function(md2) { - var mgf = { - /** - * Generate mask of specified length. - * - * @param {String} seed The seed for mask generation. - * @param maskLen Number of bytes to generate. - * @return {String} The generated mask. - */ - generate: function(seed, maskLen) { - var t = new forge.util.ByteBuffer(); - var len = Math.ceil(maskLen / md2.digestLength); - for (var i = 0; i < len; i++) { - var c = new forge.util.ByteBuffer(); - c.putInt32(i); - md2.start(); - md2.update(seed + c.getBytes()); - t.putBuffer(md2.digest()); - } - t.truncate(t.length() - maskLen); - return t.getBytes(); - } - }; - return mgf; - }; - } -}); - -// node_modules/node-forge/lib/mgf.js -var require_mgf = __commonJS({ - "node_modules/node-forge/lib/mgf.js"(exports2, module2) { - var forge = require_forge(); - require_mgf1(); - module2.exports = forge.mgf = forge.mgf || {}; - forge.mgf.mgf1 = forge.mgf1; - } -}); - -// node_modules/node-forge/lib/pss.js -var require_pss = __commonJS({ - "node_modules/node-forge/lib/pss.js"(exports2, module2) { - var forge = require_forge(); - require_random(); - require_util13(); - var pss = module2.exports = forge.pss = forge.pss || {}; - pss.create = function(options) { - if (arguments.length === 3) { - options = { - md: arguments[0], - mgf: arguments[1], - saltLength: arguments[2] - }; - } - var hash = options.md; - var mgf = options.mgf; - var hLen = hash.digestLength; - var salt_ = options.salt || null; - if (typeof salt_ === "string") { - salt_ = forge.util.createBuffer(salt_); - } - var sLen; - if ("saltLength" in options) { - sLen = options.saltLength; - } else if (salt_ !== null) { - sLen = salt_.length(); - } else { - throw new Error("Salt length not specified or specific salt not given."); - } - if (salt_ !== null && salt_.length() !== sLen) { - throw new Error("Given salt length does not match length of given salt."); - } - var prng = options.prng || forge.random; - var pssobj = {}; - pssobj.encode = function(md2, modBits) { - var i; - var emBits = modBits - 1; - var emLen = Math.ceil(emBits / 8); - var mHash = md2.digest().getBytes(); - if (emLen < hLen + sLen + 2) { - throw new Error("Message is too long to encrypt."); - } - var salt; - if (salt_ === null) { - salt = prng.getBytesSync(sLen); - } else { - salt = salt_.bytes(); - } - var m_ = new forge.util.ByteBuffer(); - m_.fillWithByte(0, 8); - m_.putBytes(mHash); - m_.putBytes(salt); - hash.start(); - hash.update(m_.getBytes()); - var h = hash.digest().getBytes(); - var ps = new forge.util.ByteBuffer(); - ps.fillWithByte(0, emLen - sLen - hLen - 2); - ps.putByte(1); - ps.putBytes(salt); - var db = ps.getBytes(); - var maskLen = emLen - hLen - 1; - var dbMask = mgf.generate(h, maskLen); - var maskedDB = ""; - for (i = 0; i < maskLen; i++) { - maskedDB += String.fromCharCode(db.charCodeAt(i) ^ dbMask.charCodeAt(i)); - } - var mask = 65280 >> 8 * emLen - emBits & 255; - maskedDB = String.fromCharCode(maskedDB.charCodeAt(0) & ~mask) + maskedDB.substr(1); - return maskedDB + h + String.fromCharCode(188); - }; - pssobj.verify = function(mHash, em, modBits) { - var i; - var emBits = modBits - 1; - var emLen = Math.ceil(emBits / 8); - em = em.substr(-emLen); - if (emLen < hLen + sLen + 2) { - throw new Error("Inconsistent parameters to PSS signature verification."); - } - if (em.charCodeAt(emLen - 1) !== 188) { - throw new Error("Encoded message does not end in 0xBC."); - } - var maskLen = emLen - hLen - 1; - var maskedDB = em.substr(0, maskLen); - var h = em.substr(maskLen, hLen); - var mask = 65280 >> 8 * emLen - emBits & 255; - if ((maskedDB.charCodeAt(0) & mask) !== 0) { - throw new Error("Bits beyond keysize not zero as expected."); - } - var dbMask = mgf.generate(h, maskLen); - var db = ""; - for (i = 0; i < maskLen; i++) { - db += String.fromCharCode(maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i)); - } - db = String.fromCharCode(db.charCodeAt(0) & ~mask) + db.substr(1); - var checkLen = emLen - hLen - sLen - 2; - for (i = 0; i < checkLen; i++) { - if (db.charCodeAt(i) !== 0) { - throw new Error("Leftmost octets not zero as expected"); - } - } - if (db.charCodeAt(checkLen) !== 1) { - throw new Error("Inconsistent PSS signature, 0x01 marker not found"); - } - var salt = db.substr(-sLen); - var m_ = new forge.util.ByteBuffer(); - m_.fillWithByte(0, 8); - m_.putBytes(mHash); - m_.putBytes(salt); - hash.start(); - hash.update(m_.getBytes()); - var h_ = hash.digest().getBytes(); - return h === h_; - }; - return pssobj; - }; - } -}); - -// node_modules/node-forge/lib/x509.js -var require_x509 = __commonJS({ - "node_modules/node-forge/lib/x509.js"(exports2, module2) { - var forge = require_forge(); - require_aes(); - require_asn1(); - require_des(); - require_md(); - require_mgf(); - require_oids(); - require_pem(); - require_pss(); - require_rsa(); - require_util13(); - var asn1 = forge.asn1; - var pki2 = module2.exports = forge.pki = forge.pki || {}; - var oids = pki2.oids; - var _shortNames = {}; - _shortNames["CN"] = oids["commonName"]; - _shortNames["commonName"] = "CN"; - _shortNames["C"] = oids["countryName"]; - _shortNames["countryName"] = "C"; - _shortNames["L"] = oids["localityName"]; - _shortNames["localityName"] = "L"; - _shortNames["ST"] = oids["stateOrProvinceName"]; - _shortNames["stateOrProvinceName"] = "ST"; - _shortNames["O"] = oids["organizationName"]; - _shortNames["organizationName"] = "O"; - _shortNames["OU"] = oids["organizationalUnitName"]; - _shortNames["organizationalUnitName"] = "OU"; - _shortNames["E"] = oids["emailAddress"]; - _shortNames["emailAddress"] = "E"; - var publicKeyValidator = forge.pki.rsa.publicKeyValidator; - var x509CertificateValidator = { - name: "Certificate", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "Certificate.TBSCertificate", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "tbsCertificate", - value: [ - { - name: "Certificate.TBSCertificate.version", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - constructed: true, - optional: true, - value: [{ - name: "Certificate.TBSCertificate.version.integer", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "certVersion" - }] - }, - { - name: "Certificate.TBSCertificate.serialNumber", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "certSerialNumber" - }, - { - name: "Certificate.TBSCertificate.signature", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "Certificate.TBSCertificate.signature.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "certinfoSignatureOid" - }, { - name: "Certificate.TBSCertificate.signature.parameters", - tagClass: asn1.Class.UNIVERSAL, - optional: true, - captureAsn1: "certinfoSignatureParams" - }] - }, - { - name: "Certificate.TBSCertificate.issuer", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "certIssuer" - }, - { - name: "Certificate.TBSCertificate.validity", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - // Note: UTC and generalized times may both appear so the capture - // names are based on their detected order, the names used below - // are only for the common case, which validity time really means - // "notBefore" and which means "notAfter" will be determined by order - value: [{ - // notBefore (Time) (UTC time case) - name: "Certificate.TBSCertificate.validity.notBefore (utc)", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.UTCTIME, - constructed: false, - optional: true, - capture: "certValidity1UTCTime" - }, { - // notBefore (Time) (generalized time case) - name: "Certificate.TBSCertificate.validity.notBefore (generalized)", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.GENERALIZEDTIME, - constructed: false, - optional: true, - capture: "certValidity2GeneralizedTime" - }, { - // notAfter (Time) (only UTC time is supported) - name: "Certificate.TBSCertificate.validity.notAfter (utc)", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.UTCTIME, - constructed: false, - optional: true, - capture: "certValidity3UTCTime" - }, { - // notAfter (Time) (only UTC time is supported) - name: "Certificate.TBSCertificate.validity.notAfter (generalized)", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.GENERALIZEDTIME, - constructed: false, - optional: true, - capture: "certValidity4GeneralizedTime" - }] - }, - { - // Name (subject) (RDNSequence) - name: "Certificate.TBSCertificate.subject", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "certSubject" - }, - // SubjectPublicKeyInfo - publicKeyValidator, - { - // issuerUniqueID (optional) - name: "Certificate.TBSCertificate.issuerUniqueID", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 1, - constructed: true, - optional: true, - value: [{ - name: "Certificate.TBSCertificate.issuerUniqueID.id", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - // TODO: support arbitrary bit length ids - captureBitStringValue: "certIssuerUniqueId" - }] - }, - { - // subjectUniqueID (optional) - name: "Certificate.TBSCertificate.subjectUniqueID", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 2, - constructed: true, - optional: true, - value: [{ - name: "Certificate.TBSCertificate.subjectUniqueID.id", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - // TODO: support arbitrary bit length ids - captureBitStringValue: "certSubjectUniqueId" - }] - }, - { - // Extensions (optional) - name: "Certificate.TBSCertificate.extensions", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 3, - constructed: true, - captureAsn1: "certExtensions", - optional: true - } - ] - }, { - // AlgorithmIdentifier (signature algorithm) - name: "Certificate.signatureAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - // algorithm - name: "Certificate.signatureAlgorithm.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "certSignatureOid" - }, { - name: "Certificate.TBSCertificate.signature.parameters", - tagClass: asn1.Class.UNIVERSAL, - optional: true, - captureAsn1: "certSignatureParams" - }] - }, { - // SignatureValue - name: "Certificate.signatureValue", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - captureBitStringValue: "certSignature" - }] - }; - var rsassaPssParameterValidator = { - name: "rsapss", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "rsapss.hashAlgorithm", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - constructed: true, - value: [{ - name: "rsapss.hashAlgorithm.AlgorithmIdentifier", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Class.SEQUENCE, - constructed: true, - optional: true, - value: [{ - name: "rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "hashOid" - /* parameter block omitted, for SHA1 NULL anyhow. */ - }] - }] - }, { - name: "rsapss.maskGenAlgorithm", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 1, - constructed: true, - value: [{ - name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Class.SEQUENCE, - constructed: true, - optional: true, - value: [{ - name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "maskGenOid" - }, { - name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier.params", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "maskGenHashOid" - /* parameter block omitted, for SHA1 NULL anyhow. */ - }] - }] - }] - }, { - name: "rsapss.saltLength", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 2, - optional: true, - value: [{ - name: "rsapss.saltLength.saltLength", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Class.INTEGER, - constructed: false, - capture: "saltLength" - }] - }, { - name: "rsapss.trailerField", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 3, - optional: true, - value: [{ - name: "rsapss.trailer.trailer", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Class.INTEGER, - constructed: false, - capture: "trailer" - }] - }] - }; - var certificationRequestInfoValidator = { - name: "CertificationRequestInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "certificationRequestInfo", - value: [ - { - name: "CertificationRequestInfo.integer", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "certificationRequestInfoVersion" - }, - { - // Name (subject) (RDNSequence) - name: "CertificationRequestInfo.subject", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "certificationRequestInfoSubject" - }, - // SubjectPublicKeyInfo - publicKeyValidator, - { - name: "CertificationRequestInfo.attributes", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - constructed: true, - optional: true, - capture: "certificationRequestInfoAttributes", - value: [{ - name: "CertificationRequestInfo.attributes", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "CertificationRequestInfo.attributes.type", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false - }, { - name: "CertificationRequestInfo.attributes.value", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SET, - constructed: true - }] - }] - } - ] - }; - var certificationRequestValidator = { - name: "CertificationRequest", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "csr", - value: [ - certificationRequestInfoValidator, - { - // AlgorithmIdentifier (signature algorithm) - name: "CertificationRequest.signatureAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - // algorithm - name: "CertificationRequest.signatureAlgorithm.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "csrSignatureOid" - }, { - name: "CertificationRequest.signatureAlgorithm.parameters", - tagClass: asn1.Class.UNIVERSAL, - optional: true, - captureAsn1: "csrSignatureParams" - }] - }, - { - // signature - name: "CertificationRequest.signature", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - captureBitStringValue: "csrSignature" - } - ] - }; - pki2.RDNAttributesAsArray = function(rdn, md2) { - var rval = []; - var set, attr, obj; - for (var si = 0; si < rdn.value.length; ++si) { - set = rdn.value[si]; - for (var i = 0; i < set.value.length; ++i) { - obj = {}; - attr = set.value[i]; - obj.type = asn1.derToOid(attr.value[0].value); - obj.value = attr.value[1].value; - obj.valueTagClass = attr.value[1].type; - if (obj.type in oids) { - obj.name = oids[obj.type]; - if (obj.name in _shortNames) { - obj.shortName = _shortNames[obj.name]; - } - } - if (md2) { - md2.update(obj.type); - md2.update(obj.value); - } - rval.push(obj); - } - } - return rval; - }; - pki2.CRIAttributesAsArray = function(attributes) { - var rval = []; - for (var si = 0; si < attributes.length; ++si) { - var seq = attributes[si]; - var type = asn1.derToOid(seq.value[0].value); - var values = seq.value[1].value; - for (var vi = 0; vi < values.length; ++vi) { - var obj = {}; - obj.type = type; - obj.value = values[vi].value; - obj.valueTagClass = values[vi].type; - if (obj.type in oids) { - obj.name = oids[obj.type]; - if (obj.name in _shortNames) { - obj.shortName = _shortNames[obj.name]; - } - } - if (obj.type === oids.extensionRequest) { - obj.extensions = []; - for (var ei = 0; ei < obj.value.length; ++ei) { - obj.extensions.push(pki2.certificateExtensionFromAsn1(obj.value[ei])); - } - } - rval.push(obj); - } - } - return rval; - }; - function _getAttribute(obj, options) { - if (typeof options === "string") { - options = { shortName: options }; - } - var rval = null; - var attr; - for (var i = 0; rval === null && i < obj.attributes.length; ++i) { - attr = obj.attributes[i]; - if (options.type && options.type === attr.type) { - rval = attr; - } else if (options.name && options.name === attr.name) { - rval = attr; - } else if (options.shortName && options.shortName === attr.shortName) { - rval = attr; - } - } - return rval; - } - var _readSignatureParameters = function(oid, obj, fillDefaults) { - var params = {}; - if (oid !== oids["RSASSA-PSS"]) { - return params; - } - if (fillDefaults) { - params = { - hash: { - algorithmOid: oids["sha1"] - }, - mgf: { - algorithmOid: oids["mgf1"], - hash: { - algorithmOid: oids["sha1"] - } - }, - saltLength: 20 - }; - } - var capture = {}; - var errors = []; - if (!asn1.validate(obj, rsassaPssParameterValidator, capture, errors)) { - var error3 = new Error("Cannot read RSASSA-PSS parameter block."); - error3.errors = errors; - throw error3; - } - if (capture.hashOid !== void 0) { - params.hash = params.hash || {}; - params.hash.algorithmOid = asn1.derToOid(capture.hashOid); - } - if (capture.maskGenOid !== void 0) { - params.mgf = params.mgf || {}; - params.mgf.algorithmOid = asn1.derToOid(capture.maskGenOid); - params.mgf.hash = params.mgf.hash || {}; - params.mgf.hash.algorithmOid = asn1.derToOid(capture.maskGenHashOid); - } - if (capture.saltLength !== void 0) { - params.saltLength = capture.saltLength.charCodeAt(0); - } - return params; - }; - var _createSignatureDigest = function(options) { - switch (oids[options.signatureOid]) { - case "sha1WithRSAEncryption": - // deprecated alias - case "sha1WithRSASignature": - return forge.md.sha1.create(); - case "md5WithRSAEncryption": - return forge.md.md5.create(); - case "sha256WithRSAEncryption": - return forge.md.sha256.create(); - case "sha384WithRSAEncryption": - return forge.md.sha384.create(); - case "sha512WithRSAEncryption": - return forge.md.sha512.create(); - case "RSASSA-PSS": - return forge.md.sha256.create(); - default: - var error3 = new Error( - "Could not compute " + options.type + " digest. Unknown signature OID." - ); - error3.signatureOid = options.signatureOid; - throw error3; - } - }; - var _verifySignature = function(options) { - var cert = options.certificate; - var scheme; - switch (cert.signatureOid) { - case oids.sha1WithRSAEncryption: - // deprecated alias - case oids.sha1WithRSASignature: - break; - case oids["RSASSA-PSS"]: - var hash, mgf; - hash = oids[cert.signatureParameters.mgf.hash.algorithmOid]; - if (hash === void 0 || forge.md[hash] === void 0) { - var error3 = new Error("Unsupported MGF hash function."); - error3.oid = cert.signatureParameters.mgf.hash.algorithmOid; - error3.name = hash; - throw error3; - } - mgf = oids[cert.signatureParameters.mgf.algorithmOid]; - if (mgf === void 0 || forge.mgf[mgf] === void 0) { - var error3 = new Error("Unsupported MGF function."); - error3.oid = cert.signatureParameters.mgf.algorithmOid; - error3.name = mgf; - throw error3; - } - mgf = forge.mgf[mgf].create(forge.md[hash].create()); - hash = oids[cert.signatureParameters.hash.algorithmOid]; - if (hash === void 0 || forge.md[hash] === void 0) { - var error3 = new Error("Unsupported RSASSA-PSS hash function."); - error3.oid = cert.signatureParameters.hash.algorithmOid; - error3.name = hash; - throw error3; - } - scheme = forge.pss.create( - forge.md[hash].create(), - mgf, - cert.signatureParameters.saltLength - ); - break; - } - return cert.publicKey.verify( - options.md.digest().getBytes(), - options.signature, - scheme - ); - }; - pki2.certificateFromPem = function(pem, computeHash, strict) { - var msg = forge.pem.decode(pem)[0]; - if (msg.type !== "CERTIFICATE" && msg.type !== "X509 CERTIFICATE" && msg.type !== "TRUSTED CERTIFICATE") { - var error3 = new Error( - 'Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".' - ); - error3.headerType = msg.type; - throw error3; - } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error( - "Could not convert certificate from PEM; PEM is encrypted." - ); - } - var obj = asn1.fromDer(msg.body, strict); - return pki2.certificateFromAsn1(obj, computeHash); - }; - pki2.certificateToPem = function(cert, maxline) { - var msg = { - type: "CERTIFICATE", - body: asn1.toDer(pki2.certificateToAsn1(cert)).getBytes() - }; - return forge.pem.encode(msg, { maxline }); - }; - pki2.publicKeyFromPem = function(pem) { - var msg = forge.pem.decode(pem)[0]; - if (msg.type !== "PUBLIC KEY" && msg.type !== "RSA PUBLIC KEY") { - var error3 = new Error('Could not convert public key from PEM; PEM header type is not "PUBLIC KEY" or "RSA PUBLIC KEY".'); - error3.headerType = msg.type; - throw error3; - } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error("Could not convert public key from PEM; PEM is encrypted."); - } - var obj = asn1.fromDer(msg.body); - return pki2.publicKeyFromAsn1(obj); - }; - pki2.publicKeyToPem = function(key, maxline) { - var msg = { - type: "PUBLIC KEY", - body: asn1.toDer(pki2.publicKeyToAsn1(key)).getBytes() - }; - return forge.pem.encode(msg, { maxline }); - }; - pki2.publicKeyToRSAPublicKeyPem = function(key, maxline) { - var msg = { - type: "RSA PUBLIC KEY", - body: asn1.toDer(pki2.publicKeyToRSAPublicKey(key)).getBytes() - }; - return forge.pem.encode(msg, { maxline }); - }; - pki2.getPublicKeyFingerprint = function(key, options) { - options = options || {}; - var md2 = options.md || forge.md.sha1.create(); - var type = options.type || "RSAPublicKey"; - var bytes; - switch (type) { - case "RSAPublicKey": - bytes = asn1.toDer(pki2.publicKeyToRSAPublicKey(key)).getBytes(); - break; - case "SubjectPublicKeyInfo": - bytes = asn1.toDer(pki2.publicKeyToAsn1(key)).getBytes(); - break; - default: - throw new Error('Unknown fingerprint type "' + options.type + '".'); - } - md2.start(); - md2.update(bytes); - var digest = md2.digest(); - if (options.encoding === "hex") { - var hex = digest.toHex(); - if (options.delimiter) { - return hex.match(/.{2}/g).join(options.delimiter); - } - return hex; - } else if (options.encoding === "binary") { - return digest.getBytes(); - } else if (options.encoding) { - throw new Error('Unknown encoding "' + options.encoding + '".'); - } - return digest; - }; - pki2.certificationRequestFromPem = function(pem, computeHash, strict) { - var msg = forge.pem.decode(pem)[0]; - if (msg.type !== "CERTIFICATE REQUEST") { - var error3 = new Error('Could not convert certification request from PEM; PEM header type is not "CERTIFICATE REQUEST".'); - error3.headerType = msg.type; - throw error3; - } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error("Could not convert certification request from PEM; PEM is encrypted."); - } - var obj = asn1.fromDer(msg.body, strict); - return pki2.certificationRequestFromAsn1(obj, computeHash); - }; - pki2.certificationRequestToPem = function(csr, maxline) { - var msg = { - type: "CERTIFICATE REQUEST", - body: asn1.toDer(pki2.certificationRequestToAsn1(csr)).getBytes() - }; - return forge.pem.encode(msg, { maxline }); - }; - pki2.createCertificate = function() { - var cert = {}; - cert.version = 2; - cert.serialNumber = "00"; - cert.signatureOid = null; - cert.signature = null; - cert.siginfo = {}; - cert.siginfo.algorithmOid = null; - cert.validity = {}; - cert.validity.notBefore = /* @__PURE__ */ new Date(); - cert.validity.notAfter = /* @__PURE__ */ new Date(); - cert.issuer = {}; - cert.issuer.getField = function(sn) { - return _getAttribute(cert.issuer, sn); - }; - cert.issuer.addField = function(attr) { - _fillMissingFields([attr]); - cert.issuer.attributes.push(attr); - }; - cert.issuer.attributes = []; - cert.issuer.hash = null; - cert.subject = {}; - cert.subject.getField = function(sn) { - return _getAttribute(cert.subject, sn); - }; - cert.subject.addField = function(attr) { - _fillMissingFields([attr]); - cert.subject.attributes.push(attr); - }; - cert.subject.attributes = []; - cert.subject.hash = null; - cert.extensions = []; - cert.publicKey = null; - cert.md = null; - cert.setSubject = function(attrs, uniqueId) { - _fillMissingFields(attrs); - cert.subject.attributes = attrs; - delete cert.subject.uniqueId; - if (uniqueId) { - cert.subject.uniqueId = uniqueId; - } - cert.subject.hash = null; - }; - cert.setIssuer = function(attrs, uniqueId) { - _fillMissingFields(attrs); - cert.issuer.attributes = attrs; - delete cert.issuer.uniqueId; - if (uniqueId) { - cert.issuer.uniqueId = uniqueId; - } - cert.issuer.hash = null; - }; - cert.setExtensions = function(exts) { - for (var i = 0; i < exts.length; ++i) { - _fillMissingExtensionFields(exts[i], { cert }); - } - cert.extensions = exts; - }; - cert.getExtension = function(options) { - if (typeof options === "string") { - options = { name: options }; - } - var rval = null; - var ext; - for (var i = 0; rval === null && i < cert.extensions.length; ++i) { - ext = cert.extensions[i]; - if (options.id && ext.id === options.id) { - rval = ext; - } else if (options.name && ext.name === options.name) { - rval = ext; - } - } - return rval; - }; - cert.sign = function(key, md2) { - cert.md = md2 || forge.md.sha1.create(); - var algorithmOid = oids[cert.md.algorithm + "WithRSAEncryption"]; - if (!algorithmOid) { - var error3 = new Error("Could not compute certificate digest. Unknown message digest algorithm OID."); - error3.algorithm = cert.md.algorithm; - throw error3; - } - cert.signatureOid = cert.siginfo.algorithmOid = algorithmOid; - cert.tbsCertificate = pki2.getTBSCertificate(cert); - var bytes = asn1.toDer(cert.tbsCertificate); - cert.md.update(bytes.getBytes()); - cert.signature = key.sign(cert.md); - }; - cert.verify = function(child) { - var rval = false; - if (!cert.issued(child)) { - var issuer = child.issuer; - var subject = cert.subject; - var error3 = new Error( - "The parent certificate did not issue the given child certificate; the child certificate's issuer does not match the parent's subject." - ); - error3.expectedIssuer = subject.attributes; - error3.actualIssuer = issuer.attributes; - throw error3; - } - var md2 = child.md; - if (md2 === null) { - md2 = _createSignatureDigest({ - signatureOid: child.signatureOid, - type: "certificate" - }); - var tbsCertificate = child.tbsCertificate || pki2.getTBSCertificate(child); - var bytes = asn1.toDer(tbsCertificate); - md2.update(bytes.getBytes()); - } - if (md2 !== null) { - rval = _verifySignature({ - certificate: cert, - md: md2, - signature: child.signature - }); - } - return rval; - }; - cert.isIssuer = function(parent) { - var rval = false; - var i = cert.issuer; - var s = parent.subject; - if (i.hash && s.hash) { - rval = i.hash === s.hash; - } else if (i.attributes.length === s.attributes.length) { - rval = true; - var iattr, sattr; - for (var n = 0; rval && n < i.attributes.length; ++n) { - iattr = i.attributes[n]; - sattr = s.attributes[n]; - if (iattr.type !== sattr.type || iattr.value !== sattr.value) { - rval = false; - } - } - } - return rval; - }; - cert.issued = function(child) { - return child.isIssuer(cert); - }; - cert.generateSubjectKeyIdentifier = function() { - return pki2.getPublicKeyFingerprint(cert.publicKey, { type: "RSAPublicKey" }); - }; - cert.verifySubjectKeyIdentifier = function() { - var oid = oids["subjectKeyIdentifier"]; - for (var i = 0; i < cert.extensions.length; ++i) { - var ext = cert.extensions[i]; - if (ext.id === oid) { - var ski = cert.generateSubjectKeyIdentifier().getBytes(); - return forge.util.hexToBytes(ext.subjectKeyIdentifier) === ski; - } - } - return false; - }; - return cert; - }; - pki2.certificateFromAsn1 = function(obj, computeHash) { - var capture = {}; - var errors = []; - if (!asn1.validate(obj, x509CertificateValidator, capture, errors)) { - var error3 = new Error("Cannot read X.509 certificate. ASN.1 object is not an X509v3 Certificate."); - error3.errors = errors; - throw error3; - } - var oid = asn1.derToOid(capture.publicKeyOid); - if (oid !== pki2.oids.rsaEncryption) { - throw new Error("Cannot read public key. OID is not RSA."); - } - var cert = pki2.createCertificate(); - cert.version = capture.certVersion ? capture.certVersion.charCodeAt(0) : 0; - var serial = forge.util.createBuffer(capture.certSerialNumber); - cert.serialNumber = serial.toHex(); - cert.signatureOid = forge.asn1.derToOid(capture.certSignatureOid); - cert.signatureParameters = _readSignatureParameters( - cert.signatureOid, - capture.certSignatureParams, - true - ); - cert.siginfo.algorithmOid = forge.asn1.derToOid(capture.certinfoSignatureOid); - cert.siginfo.parameters = _readSignatureParameters( - cert.siginfo.algorithmOid, - capture.certinfoSignatureParams, - false - ); - cert.signature = capture.certSignature; - var validity = []; - if (capture.certValidity1UTCTime !== void 0) { - validity.push(asn1.utcTimeToDate(capture.certValidity1UTCTime)); - } - if (capture.certValidity2GeneralizedTime !== void 0) { - validity.push(asn1.generalizedTimeToDate( - capture.certValidity2GeneralizedTime - )); - } - if (capture.certValidity3UTCTime !== void 0) { - validity.push(asn1.utcTimeToDate(capture.certValidity3UTCTime)); - } - if (capture.certValidity4GeneralizedTime !== void 0) { - validity.push(asn1.generalizedTimeToDate( - capture.certValidity4GeneralizedTime - )); - } - if (validity.length > 2) { - throw new Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate."); - } - if (validity.length < 2) { - throw new Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime."); - } - cert.validity.notBefore = validity[0]; - cert.validity.notAfter = validity[1]; - cert.tbsCertificate = capture.tbsCertificate; - if (computeHash) { - cert.md = _createSignatureDigest({ - signatureOid: cert.signatureOid, - type: "certificate" - }); - var bytes = asn1.toDer(cert.tbsCertificate); - cert.md.update(bytes.getBytes()); - } - var imd = forge.md.sha1.create(); - var ibytes = asn1.toDer(capture.certIssuer); - imd.update(ibytes.getBytes()); - cert.issuer.getField = function(sn) { - return _getAttribute(cert.issuer, sn); - }; - cert.issuer.addField = function(attr) { - _fillMissingFields([attr]); - cert.issuer.attributes.push(attr); - }; - cert.issuer.attributes = pki2.RDNAttributesAsArray(capture.certIssuer); - if (capture.certIssuerUniqueId) { - cert.issuer.uniqueId = capture.certIssuerUniqueId; - } - cert.issuer.hash = imd.digest().toHex(); - var smd = forge.md.sha1.create(); - var sbytes = asn1.toDer(capture.certSubject); - smd.update(sbytes.getBytes()); - cert.subject.getField = function(sn) { - return _getAttribute(cert.subject, sn); - }; - cert.subject.addField = function(attr) { - _fillMissingFields([attr]); - cert.subject.attributes.push(attr); - }; - cert.subject.attributes = pki2.RDNAttributesAsArray(capture.certSubject); - if (capture.certSubjectUniqueId) { - cert.subject.uniqueId = capture.certSubjectUniqueId; - } - cert.subject.hash = smd.digest().toHex(); - if (capture.certExtensions) { - cert.extensions = pki2.certificateExtensionsFromAsn1(capture.certExtensions); - } else { - cert.extensions = []; - } - cert.publicKey = pki2.publicKeyFromAsn1(capture.subjectPublicKeyInfo); - return cert; - }; - pki2.certificateExtensionsFromAsn1 = function(exts) { - var rval = []; - for (var i = 0; i < exts.value.length; ++i) { - var extseq = exts.value[i]; - for (var ei = 0; ei < extseq.value.length; ++ei) { - rval.push(pki2.certificateExtensionFromAsn1(extseq.value[ei])); - } - } - return rval; - }; - pki2.certificateExtensionFromAsn1 = function(ext) { - var e = {}; - e.id = asn1.derToOid(ext.value[0].value); - e.critical = false; - if (ext.value[1].type === asn1.Type.BOOLEAN) { - e.critical = ext.value[1].value.charCodeAt(0) !== 0; - e.value = ext.value[2].value; - } else { - e.value = ext.value[1].value; - } - if (e.id in oids) { - e.name = oids[e.id]; - if (e.name === "keyUsage") { - var ev = asn1.fromDer(e.value); - var b2 = 0; - var b3 = 0; - if (ev.value.length > 1) { - b2 = ev.value.charCodeAt(1); - b3 = ev.value.length > 2 ? ev.value.charCodeAt(2) : 0; - } - e.digitalSignature = (b2 & 128) === 128; - e.nonRepudiation = (b2 & 64) === 64; - e.keyEncipherment = (b2 & 32) === 32; - e.dataEncipherment = (b2 & 16) === 16; - e.keyAgreement = (b2 & 8) === 8; - e.keyCertSign = (b2 & 4) === 4; - e.cRLSign = (b2 & 2) === 2; - e.encipherOnly = (b2 & 1) === 1; - e.decipherOnly = (b3 & 128) === 128; - } else if (e.name === "basicConstraints") { - var ev = asn1.fromDer(e.value); - if (ev.value.length > 0 && ev.value[0].type === asn1.Type.BOOLEAN) { - e.cA = ev.value[0].value.charCodeAt(0) !== 0; - } else { - e.cA = false; - } - var value = null; - if (ev.value.length > 0 && ev.value[0].type === asn1.Type.INTEGER) { - value = ev.value[0].value; - } else if (ev.value.length > 1) { - value = ev.value[1].value; - } - if (value !== null) { - e.pathLenConstraint = asn1.derToInteger(value); - } - } else if (e.name === "extKeyUsage") { - var ev = asn1.fromDer(e.value); - for (var vi = 0; vi < ev.value.length; ++vi) { - var oid = asn1.derToOid(ev.value[vi].value); - if (oid in oids) { - e[oids[oid]] = true; - } else { - e[oid] = true; - } - } - } else if (e.name === "nsCertType") { - var ev = asn1.fromDer(e.value); - var b2 = 0; - if (ev.value.length > 1) { - b2 = ev.value.charCodeAt(1); - } - e.client = (b2 & 128) === 128; - e.server = (b2 & 64) === 64; - e.email = (b2 & 32) === 32; - e.objsign = (b2 & 16) === 16; - e.reserved = (b2 & 8) === 8; - e.sslCA = (b2 & 4) === 4; - e.emailCA = (b2 & 2) === 2; - e.objCA = (b2 & 1) === 1; - } else if (e.name === "subjectAltName" || e.name === "issuerAltName") { - e.altNames = []; - var gn; - var ev = asn1.fromDer(e.value); - for (var n = 0; n < ev.value.length; ++n) { - gn = ev.value[n]; - var altName = { - type: gn.type, - value: gn.value - }; - e.altNames.push(altName); - switch (gn.type) { - // rfc822Name - case 1: - // dNSName - case 2: - // uniformResourceIdentifier (URI) - case 6: - break; - // IPAddress - case 7: - altName.ip = forge.util.bytesToIP(gn.value); - break; - // registeredID - case 8: - altName.oid = asn1.derToOid(gn.value); - break; - default: - } - } - } else if (e.name === "subjectKeyIdentifier") { - var ev = asn1.fromDer(e.value); - e.subjectKeyIdentifier = forge.util.bytesToHex(ev.value); - } - } - return e; - }; - pki2.certificationRequestFromAsn1 = function(obj, computeHash) { - var capture = {}; - var errors = []; - if (!asn1.validate(obj, certificationRequestValidator, capture, errors)) { - var error3 = new Error("Cannot read PKCS#10 certificate request. ASN.1 object is not a PKCS#10 CertificationRequest."); - error3.errors = errors; - throw error3; - } - var oid = asn1.derToOid(capture.publicKeyOid); - if (oid !== pki2.oids.rsaEncryption) { - throw new Error("Cannot read public key. OID is not RSA."); - } - var csr = pki2.createCertificationRequest(); - csr.version = capture.csrVersion ? capture.csrVersion.charCodeAt(0) : 0; - csr.signatureOid = forge.asn1.derToOid(capture.csrSignatureOid); - csr.signatureParameters = _readSignatureParameters( - csr.signatureOid, - capture.csrSignatureParams, - true - ); - csr.siginfo.algorithmOid = forge.asn1.derToOid(capture.csrSignatureOid); - csr.siginfo.parameters = _readSignatureParameters( - csr.siginfo.algorithmOid, - capture.csrSignatureParams, - false - ); - csr.signature = capture.csrSignature; - csr.certificationRequestInfo = capture.certificationRequestInfo; - if (computeHash) { - csr.md = _createSignatureDigest({ - signatureOid: csr.signatureOid, - type: "certification request" - }); - var bytes = asn1.toDer(csr.certificationRequestInfo); - csr.md.update(bytes.getBytes()); - } - var smd = forge.md.sha1.create(); - csr.subject.getField = function(sn) { - return _getAttribute(csr.subject, sn); - }; - csr.subject.addField = function(attr) { - _fillMissingFields([attr]); - csr.subject.attributes.push(attr); - }; - csr.subject.attributes = pki2.RDNAttributesAsArray( - capture.certificationRequestInfoSubject, - smd - ); - csr.subject.hash = smd.digest().toHex(); - csr.publicKey = pki2.publicKeyFromAsn1(capture.subjectPublicKeyInfo); - csr.getAttribute = function(sn) { - return _getAttribute(csr, sn); - }; - csr.addAttribute = function(attr) { - _fillMissingFields([attr]); - csr.attributes.push(attr); - }; - csr.attributes = pki2.CRIAttributesAsArray( - capture.certificationRequestInfoAttributes || [] - ); - return csr; - }; - pki2.createCertificationRequest = function() { - var csr = {}; - csr.version = 0; - csr.signatureOid = null; - csr.signature = null; - csr.siginfo = {}; - csr.siginfo.algorithmOid = null; - csr.subject = {}; - csr.subject.getField = function(sn) { - return _getAttribute(csr.subject, sn); - }; - csr.subject.addField = function(attr) { - _fillMissingFields([attr]); - csr.subject.attributes.push(attr); - }; - csr.subject.attributes = []; - csr.subject.hash = null; - csr.publicKey = null; - csr.attributes = []; - csr.getAttribute = function(sn) { - return _getAttribute(csr, sn); - }; - csr.addAttribute = function(attr) { - _fillMissingFields([attr]); - csr.attributes.push(attr); - }; - csr.md = null; - csr.setSubject = function(attrs) { - _fillMissingFields(attrs); - csr.subject.attributes = attrs; - csr.subject.hash = null; - }; - csr.setAttributes = function(attrs) { - _fillMissingFields(attrs); - csr.attributes = attrs; - }; - csr.sign = function(key, md2) { - csr.md = md2 || forge.md.sha1.create(); - var algorithmOid = oids[csr.md.algorithm + "WithRSAEncryption"]; - if (!algorithmOid) { - var error3 = new Error("Could not compute certification request digest. Unknown message digest algorithm OID."); - error3.algorithm = csr.md.algorithm; - throw error3; - } - csr.signatureOid = csr.siginfo.algorithmOid = algorithmOid; - csr.certificationRequestInfo = pki2.getCertificationRequestInfo(csr); - var bytes = asn1.toDer(csr.certificationRequestInfo); - csr.md.update(bytes.getBytes()); - csr.signature = key.sign(csr.md); - }; - csr.verify = function() { - var rval = false; - var md2 = csr.md; - if (md2 === null) { - md2 = _createSignatureDigest({ - signatureOid: csr.signatureOid, - type: "certification request" - }); - var cri = csr.certificationRequestInfo || pki2.getCertificationRequestInfo(csr); - var bytes = asn1.toDer(cri); - md2.update(bytes.getBytes()); - } - if (md2 !== null) { - rval = _verifySignature({ - certificate: csr, - md: md2, - signature: csr.signature - }); - } - return rval; - }; - return csr; - }; - function _dnToAsn1(obj) { - var rval = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [] - ); - var attr, set; - var attrs = obj.attributes; - for (var i = 0; i < attrs.length; ++i) { - attr = attrs[i]; - var value = attr.value; - var valueTagClass = asn1.Type.PRINTABLESTRING; - if ("valueTagClass" in attr) { - valueTagClass = attr.valueTagClass; - if (valueTagClass === asn1.Type.UTF8) { - value = forge.util.encodeUtf8(value); - } - } - set = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // AttributeType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(attr.type).getBytes() - ), - // AttributeValue - asn1.create(asn1.Class.UNIVERSAL, valueTagClass, false, value) - ]) - ]); - rval.value.push(set); - } - return rval; - } - function _fillMissingFields(attrs) { - var attr; - for (var i = 0; i < attrs.length; ++i) { - attr = attrs[i]; - if (typeof attr.name === "undefined") { - if (attr.type && attr.type in pki2.oids) { - attr.name = pki2.oids[attr.type]; - } else if (attr.shortName && attr.shortName in _shortNames) { - attr.name = pki2.oids[_shortNames[attr.shortName]]; - } - } - if (typeof attr.type === "undefined") { - if (attr.name && attr.name in pki2.oids) { - attr.type = pki2.oids[attr.name]; - } else { - var error3 = new Error("Attribute type not specified."); - error3.attribute = attr; - throw error3; - } - } - if (typeof attr.shortName === "undefined") { - if (attr.name && attr.name in _shortNames) { - attr.shortName = _shortNames[attr.name]; - } - } - if (attr.type === oids.extensionRequest) { - attr.valueConstructed = true; - attr.valueTagClass = asn1.Type.SEQUENCE; - if (!attr.value && attr.extensions) { - attr.value = []; - for (var ei = 0; ei < attr.extensions.length; ++ei) { - attr.value.push(pki2.certificateExtensionToAsn1( - _fillMissingExtensionFields(attr.extensions[ei]) - )); - } - } - } - if (typeof attr.value === "undefined") { - var error3 = new Error("Attribute value not specified."); - error3.attribute = attr; - throw error3; - } - } - } - function _fillMissingExtensionFields(e, options) { - options = options || {}; - if (typeof e.name === "undefined") { - if (e.id && e.id in pki2.oids) { - e.name = pki2.oids[e.id]; - } - } - if (typeof e.id === "undefined") { - if (e.name && e.name in pki2.oids) { - e.id = pki2.oids[e.name]; - } else { - var error3 = new Error("Extension ID not specified."); - error3.extension = e; - throw error3; - } - } - if (typeof e.value !== "undefined") { - return e; - } - if (e.name === "keyUsage") { - var unused = 0; - var b2 = 0; - var b3 = 0; - if (e.digitalSignature) { - b2 |= 128; - unused = 7; - } - if (e.nonRepudiation) { - b2 |= 64; - unused = 6; - } - if (e.keyEncipherment) { - b2 |= 32; - unused = 5; - } - if (e.dataEncipherment) { - b2 |= 16; - unused = 4; - } - if (e.keyAgreement) { - b2 |= 8; - unused = 3; - } - if (e.keyCertSign) { - b2 |= 4; - unused = 2; - } - if (e.cRLSign) { - b2 |= 2; - unused = 1; - } - if (e.encipherOnly) { - b2 |= 1; - unused = 0; - } - if (e.decipherOnly) { - b3 |= 128; - unused = 7; - } - var value = String.fromCharCode(unused); - if (b3 !== 0) { - value += String.fromCharCode(b2) + String.fromCharCode(b3); - } else if (b2 !== 0) { - value += String.fromCharCode(b2); - } - e.value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BITSTRING, - false, - value - ); - } else if (e.name === "basicConstraints") { - e.value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [] - ); - if (e.cA) { - e.value.value.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BOOLEAN, - false, - String.fromCharCode(255) - )); - } - if ("pathLenConstraint" in e) { - e.value.value.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(e.pathLenConstraint).getBytes() - )); - } - } else if (e.name === "extKeyUsage") { - e.value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [] - ); - var seq = e.value.value; - for (var key in e) { - if (e[key] !== true) { - continue; - } - if (key in oids) { - seq.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(oids[key]).getBytes() - )); - } else if (key.indexOf(".") !== -1) { - seq.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(key).getBytes() - )); - } - } - } else if (e.name === "nsCertType") { - var unused = 0; - var b2 = 0; - if (e.client) { - b2 |= 128; - unused = 7; - } - if (e.server) { - b2 |= 64; - unused = 6; - } - if (e.email) { - b2 |= 32; - unused = 5; - } - if (e.objsign) { - b2 |= 16; - unused = 4; - } - if (e.reserved) { - b2 |= 8; - unused = 3; - } - if (e.sslCA) { - b2 |= 4; - unused = 2; - } - if (e.emailCA) { - b2 |= 2; - unused = 1; - } - if (e.objCA) { - b2 |= 1; - unused = 0; - } - var value = String.fromCharCode(unused); - if (b2 !== 0) { - value += String.fromCharCode(b2); - } - e.value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BITSTRING, - false, - value - ); - } else if (e.name === "subjectAltName" || e.name === "issuerAltName") { - e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - var altName; - for (var n = 0; n < e.altNames.length; ++n) { - altName = e.altNames[n]; - var value = altName.value; - if (altName.type === 7 && altName.ip) { - value = forge.util.bytesFromIP(altName.ip); - if (value === null) { - var error3 = new Error( - 'Extension "ip" value is not a valid IPv4 or IPv6 address.' - ); - error3.extension = e; - throw error3; - } - } else if (altName.type === 8) { - if (altName.oid) { - value = asn1.oidToDer(asn1.oidToDer(altName.oid)); - } else { - value = asn1.oidToDer(value); - } - } - e.value.value.push(asn1.create( - asn1.Class.CONTEXT_SPECIFIC, - altName.type, - false, - value - )); - } - } else if (e.name === "nsComment" && options.cert) { - if (!/^[\x00-\x7F]*$/.test(e.comment) || e.comment.length < 1 || e.comment.length > 128) { - throw new Error('Invalid "nsComment" content.'); - } - e.value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.IA5STRING, - false, - e.comment - ); - } else if (e.name === "subjectKeyIdentifier" && options.cert) { - var ski = options.cert.generateSubjectKeyIdentifier(); - e.subjectKeyIdentifier = ski.toHex(); - e.value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - ski.getBytes() - ); - } else if (e.name === "authorityKeyIdentifier" && options.cert) { - e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - var seq = e.value.value; - if (e.keyIdentifier) { - var keyIdentifier = e.keyIdentifier === true ? options.cert.generateSubjectKeyIdentifier().getBytes() : e.keyIdentifier; - seq.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, false, keyIdentifier) - ); - } - if (e.authorityCertIssuer) { - var authorityCertIssuer = [ - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 4, true, [ - _dnToAsn1(e.authorityCertIssuer === true ? options.cert.issuer : e.authorityCertIssuer) - ]) - ]; - seq.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, authorityCertIssuer) - ); - } - if (e.serialNumber) { - var serialNumber = forge.util.hexToBytes(e.serialNumber === true ? options.cert.serialNumber : e.serialNumber); - seq.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, false, serialNumber) - ); - } - } else if (e.name === "cRLDistributionPoints") { - e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - var seq = e.value.value; - var subSeq = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [] - ); - var fullNameGeneralNames = asn1.create( - asn1.Class.CONTEXT_SPECIFIC, - 0, - true, - [] - ); - var altName; - for (var n = 0; n < e.altNames.length; ++n) { - altName = e.altNames[n]; - var value = altName.value; - if (altName.type === 7 && altName.ip) { - value = forge.util.bytesFromIP(altName.ip); - if (value === null) { - var error3 = new Error( - 'Extension "ip" value is not a valid IPv4 or IPv6 address.' - ); - error3.extension = e; - throw error3; - } - } else if (altName.type === 8) { - if (altName.oid) { - value = asn1.oidToDer(asn1.oidToDer(altName.oid)); - } else { - value = asn1.oidToDer(value); - } - } - fullNameGeneralNames.value.push(asn1.create( - asn1.Class.CONTEXT_SPECIFIC, - altName.type, - false, - value - )); - } - subSeq.value.push(asn1.create( - asn1.Class.CONTEXT_SPECIFIC, - 0, - true, - [fullNameGeneralNames] - )); - seq.push(subSeq); - } - if (typeof e.value === "undefined") { - var error3 = new Error("Extension value not specified."); - error3.extension = e; - throw error3; - } - return e; - } - function _signatureParametersToAsn1(oid, params) { - switch (oid) { - case oids["RSASSA-PSS"]: - var parts = []; - if (params.hash.algorithmOid !== void 0) { - parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(params.hash.algorithmOid).getBytes() - ), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]) - ])); - } - if (params.mgf.algorithmOid !== void 0) { - parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(params.mgf.algorithmOid).getBytes() - ), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(params.mgf.hash.algorithmOid).getBytes() - ), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]) - ]) - ])); - } - if (params.saltLength !== void 0) { - parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(params.saltLength).getBytes() - ) - ])); - } - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, parts); - default: - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, ""); - } - } - function _CRIAttributesToAsn1(csr) { - var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []); - if (csr.attributes.length === 0) { - return rval; - } - var attrs = csr.attributes; - for (var i = 0; i < attrs.length; ++i) { - var attr = attrs[i]; - var value = attr.value; - var valueTagClass = asn1.Type.UTF8; - if ("valueTagClass" in attr) { - valueTagClass = attr.valueTagClass; - } - if (valueTagClass === asn1.Type.UTF8) { - value = forge.util.encodeUtf8(value); - } - var valueConstructed = false; - if ("valueConstructed" in attr) { - valueConstructed = attr.valueConstructed; - } - var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // AttributeType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(attr.type).getBytes() - ), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ - // AttributeValue - asn1.create( - asn1.Class.UNIVERSAL, - valueTagClass, - valueConstructed, - value - ) - ]) - ]); - rval.value.push(seq); - } - return rval; - } - var jan_1_1950 = /* @__PURE__ */ new Date("1950-01-01T00:00:00Z"); - var jan_1_2050 = /* @__PURE__ */ new Date("2050-01-01T00:00:00Z"); - function _dateToAsn1(date) { - if (date >= jan_1_1950 && date < jan_1_2050) { - return asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.UTCTIME, - false, - asn1.dateToUtcTime(date) - ); - } else { - return asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.GENERALIZEDTIME, - false, - asn1.dateToGeneralizedTime(date) - ); - } - } - pki2.getTBSCertificate = function(cert) { - var notBefore = _dateToAsn1(cert.validity.notBefore); - var notAfter = _dateToAsn1(cert.validity.notAfter); - var tbs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // version - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - // integer - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(cert.version).getBytes() - ) - ]), - // serialNumber - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - forge.util.hexToBytes(cert.serialNumber) - ), - // signature - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(cert.siginfo.algorithmOid).getBytes() - ), - // parameters - _signatureParametersToAsn1( - cert.siginfo.algorithmOid, - cert.siginfo.parameters - ) - ]), - // issuer - _dnToAsn1(cert.issuer), - // validity - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - notBefore, - notAfter - ]), - // subject - _dnToAsn1(cert.subject), - // SubjectPublicKeyInfo - pki2.publicKeyToAsn1(cert.publicKey) - ]); - if (cert.issuer.uniqueId) { - tbs.value.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BITSTRING, - false, - // TODO: support arbitrary bit length ids - String.fromCharCode(0) + cert.issuer.uniqueId - ) - ]) - ); - } - if (cert.subject.uniqueId) { - tbs.value.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BITSTRING, - false, - // TODO: support arbitrary bit length ids - String.fromCharCode(0) + cert.subject.uniqueId - ) - ]) - ); - } - if (cert.extensions.length > 0) { - tbs.value.push(pki2.certificateExtensionsToAsn1(cert.extensions)); - } - return tbs; - }; - pki2.getCertificationRequestInfo = function(csr) { - var cri = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // version - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(csr.version).getBytes() - ), - // subject - _dnToAsn1(csr.subject), - // SubjectPublicKeyInfo - pki2.publicKeyToAsn1(csr.publicKey), - // attributes - _CRIAttributesToAsn1(csr) - ]); - return cri; - }; - pki2.distinguishedNameToAsn1 = function(dn) { - return _dnToAsn1(dn); - }; - pki2.certificateToAsn1 = function(cert) { - var tbsCertificate = cert.tbsCertificate || pki2.getTBSCertificate(cert); - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // TBSCertificate - tbsCertificate, - // AlgorithmIdentifier (signature algorithm) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(cert.signatureOid).getBytes() - ), - // parameters - _signatureParametersToAsn1(cert.signatureOid, cert.signatureParameters) - ]), - // SignatureValue - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BITSTRING, - false, - String.fromCharCode(0) + cert.signature - ) - ]); - }; - pki2.certificateExtensionsToAsn1 = function(exts) { - var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 3, true, []); - var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - rval.value.push(seq); - for (var i = 0; i < exts.length; ++i) { - seq.value.push(pki2.certificateExtensionToAsn1(exts[i])); - } - return rval; - }; - pki2.certificateExtensionToAsn1 = function(ext) { - var extseq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - extseq.value.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(ext.id).getBytes() - )); - if (ext.critical) { - extseq.value.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BOOLEAN, - false, - String.fromCharCode(255) - )); - } - var value = ext.value; - if (typeof ext.value !== "string") { - value = asn1.toDer(value).getBytes(); - } - extseq.value.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - value - )); - return extseq; - }; - pki2.certificationRequestToAsn1 = function(csr) { - var cri = csr.certificationRequestInfo || pki2.getCertificationRequestInfo(csr); - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // CertificationRequestInfo - cri, - // AlgorithmIdentifier (signature algorithm) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(csr.signatureOid).getBytes() - ), - // parameters - _signatureParametersToAsn1(csr.signatureOid, csr.signatureParameters) - ]), - // signature - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BITSTRING, - false, - String.fromCharCode(0) + csr.signature - ) - ]); - }; - pki2.createCaStore = function(certs) { - var caStore = { - // stored certificates - certs: {} - }; - caStore.getIssuer = function(cert2) { - var rval = getBySubject(cert2.issuer); - return rval; - }; - caStore.addCertificate = function(cert2) { - if (typeof cert2 === "string") { - cert2 = forge.pki.certificateFromPem(cert2); - } - ensureSubjectHasHash(cert2.subject); - if (!caStore.hasCertificate(cert2)) { - if (cert2.subject.hash in caStore.certs) { - var tmp = caStore.certs[cert2.subject.hash]; - if (!forge.util.isArray(tmp)) { - tmp = [tmp]; - } - tmp.push(cert2); - caStore.certs[cert2.subject.hash] = tmp; - } else { - caStore.certs[cert2.subject.hash] = cert2; - } - } - }; - caStore.hasCertificate = function(cert2) { - if (typeof cert2 === "string") { - cert2 = forge.pki.certificateFromPem(cert2); - } - var match = getBySubject(cert2.subject); - if (!match) { - return false; - } - if (!forge.util.isArray(match)) { - match = [match]; - } - var der1 = asn1.toDer(pki2.certificateToAsn1(cert2)).getBytes(); - for (var i2 = 0; i2 < match.length; ++i2) { - var der2 = asn1.toDer(pki2.certificateToAsn1(match[i2])).getBytes(); - if (der1 === der2) { - return true; - } - } - return false; - }; - caStore.listAllCertificates = function() { - var certList = []; - for (var hash in caStore.certs) { - if (caStore.certs.hasOwnProperty(hash)) { - var value = caStore.certs[hash]; - if (!forge.util.isArray(value)) { - certList.push(value); - } else { - for (var i2 = 0; i2 < value.length; ++i2) { - certList.push(value[i2]); - } - } - } - } - return certList; - }; - caStore.removeCertificate = function(cert2) { - var result; - if (typeof cert2 === "string") { - cert2 = forge.pki.certificateFromPem(cert2); - } - ensureSubjectHasHash(cert2.subject); - if (!caStore.hasCertificate(cert2)) { - return null; - } - var match = getBySubject(cert2.subject); - if (!forge.util.isArray(match)) { - result = caStore.certs[cert2.subject.hash]; - delete caStore.certs[cert2.subject.hash]; - return result; - } - var der1 = asn1.toDer(pki2.certificateToAsn1(cert2)).getBytes(); - for (var i2 = 0; i2 < match.length; ++i2) { - var der2 = asn1.toDer(pki2.certificateToAsn1(match[i2])).getBytes(); - if (der1 === der2) { - result = match[i2]; - match.splice(i2, 1); - } - } - if (match.length === 0) { - delete caStore.certs[cert2.subject.hash]; - } - return result; - }; - function getBySubject(subject) { - ensureSubjectHasHash(subject); - return caStore.certs[subject.hash] || null; - } - function ensureSubjectHasHash(subject) { - if (!subject.hash) { - var md2 = forge.md.sha1.create(); - subject.attributes = pki2.RDNAttributesAsArray(_dnToAsn1(subject), md2); - subject.hash = md2.digest().toHex(); - } - } - if (certs) { - for (var i = 0; i < certs.length; ++i) { - var cert = certs[i]; - caStore.addCertificate(cert); - } - } - return caStore; - }; - pki2.certificateError = { - bad_certificate: "forge.pki.BadCertificate", - unsupported_certificate: "forge.pki.UnsupportedCertificate", - certificate_revoked: "forge.pki.CertificateRevoked", - certificate_expired: "forge.pki.CertificateExpired", - certificate_unknown: "forge.pki.CertificateUnknown", - unknown_ca: "forge.pki.UnknownCertificateAuthority" - }; - pki2.verifyCertificateChain = function(caStore, chain, options) { - if (typeof options === "function") { - options = { verify: options }; - } - options = options || {}; - chain = chain.slice(0); - var certs = chain.slice(0); - var validityCheckDate = options.validityCheckDate; - if (typeof validityCheckDate === "undefined") { - validityCheckDate = /* @__PURE__ */ new Date(); - } - var first = true; - var error3 = null; - var depth = 0; - do { - var cert = chain.shift(); - var parent = null; - var selfSigned = false; - if (validityCheckDate) { - if (validityCheckDate < cert.validity.notBefore || validityCheckDate > cert.validity.notAfter) { - error3 = { - message: "Certificate is not valid yet or has expired.", - error: pki2.certificateError.certificate_expired, - notBefore: cert.validity.notBefore, - notAfter: cert.validity.notAfter, - // TODO: we might want to reconsider renaming 'now' to - // 'validityCheckDate' should this API be changed in the future. - now: validityCheckDate - }; - } - } - if (error3 === null) { - parent = chain[0] || caStore.getIssuer(cert); - if (parent === null) { - if (cert.isIssuer(cert)) { - selfSigned = true; - parent = cert; - } - } - if (parent) { - var parents = parent; - if (!forge.util.isArray(parents)) { - parents = [parents]; - } - var verified = false; - while (!verified && parents.length > 0) { - parent = parents.shift(); - try { - verified = parent.verify(cert); - } catch (ex) { - } - } - if (!verified) { - error3 = { - message: "Certificate signature is invalid.", - error: pki2.certificateError.bad_certificate - }; - } - } - if (error3 === null && (!parent || selfSigned) && !caStore.hasCertificate(cert)) { - error3 = { - message: "Certificate is not trusted.", - error: pki2.certificateError.unknown_ca - }; - } - } - if (error3 === null && parent && !cert.isIssuer(parent)) { - error3 = { - message: "Certificate issuer is invalid.", - error: pki2.certificateError.bad_certificate - }; - } - if (error3 === null) { - var se = { - keyUsage: true, - basicConstraints: true - }; - for (var i = 0; error3 === null && i < cert.extensions.length; ++i) { - var ext = cert.extensions[i]; - if (ext.critical && !(ext.name in se)) { - error3 = { - message: "Certificate has an unsupported critical extension.", - error: pki2.certificateError.unsupported_certificate - }; - } - } - } - if (error3 === null && (!first || chain.length === 0 && (!parent || selfSigned))) { - var bcExt = cert.getExtension("basicConstraints"); - var keyUsageExt = cert.getExtension("keyUsage"); - if (keyUsageExt !== null) { - if (!keyUsageExt.keyCertSign || bcExt === null) { - error3 = { - message: "Certificate keyUsage or basicConstraints conflict or indicate that the certificate is not a CA. If the certificate is the only one in the chain or isn't the first then the certificate must be a valid CA.", - error: pki2.certificateError.bad_certificate - }; - } - } - if (error3 === null && bcExt === null) { - error3 = { - message: "Certificate is missing basicConstraints extension and cannot be used as a CA.", - error: pki2.certificateError.bad_certificate - }; - } - if (error3 === null && bcExt !== null && !bcExt.cA) { - error3 = { - message: "Certificate basicConstraints indicates the certificate is not a CA.", - error: pki2.certificateError.bad_certificate - }; - } - if (error3 === null && keyUsageExt !== null && "pathLenConstraint" in bcExt) { - var pathLen = depth - 1; - if (pathLen > bcExt.pathLenConstraint) { - error3 = { - message: "Certificate basicConstraints pathLenConstraint violated.", - error: pki2.certificateError.bad_certificate - }; - } - } - } - var vfd = error3 === null ? true : error3.error; - var ret = options.verify ? options.verify(vfd, depth, certs) : vfd; - if (ret === true) { - error3 = null; - } else { - if (vfd === true) { - error3 = { - message: "The application rejected the certificate.", - error: pki2.certificateError.bad_certificate - }; - } - if (ret || ret === 0) { - if (typeof ret === "object" && !forge.util.isArray(ret)) { - if (ret.message) { - error3.message = ret.message; - } - if (ret.error) { - error3.error = ret.error; - } - } else if (typeof ret === "string") { - error3.error = ret; - } - } - throw error3; - } - first = false; - ++depth; - } while (chain.length > 0); - return true; - }; - } -}); - -// node_modules/node-forge/lib/pkcs12.js -var require_pkcs12 = __commonJS({ - "node_modules/node-forge/lib/pkcs12.js"(exports2, module2) { - var forge = require_forge(); - require_asn1(); - require_hmac(); - require_oids(); - require_pkcs7asn1(); - require_pbe(); - require_random(); - require_rsa(); - require_sha1(); - require_util13(); - require_x509(); - var asn1 = forge.asn1; - var pki2 = forge.pki; - var p12 = module2.exports = forge.pkcs12 = forge.pkcs12 || {}; - var contentInfoValidator = { - name: "ContentInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - // a ContentInfo - constructed: true, - value: [{ - name: "ContentInfo.contentType", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "contentType" - }, { - name: "ContentInfo.content", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - constructed: true, - captureAsn1: "content" - }] - }; - var pfxValidator = { - name: "PFX", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [ - { - name: "PFX.version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "version" - }, - contentInfoValidator, - { - name: "PFX.macData", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - optional: true, - captureAsn1: "mac", - value: [{ - name: "PFX.macData.mac", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - // DigestInfo - constructed: true, - value: [{ - name: "PFX.macData.mac.digestAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - // DigestAlgorithmIdentifier - constructed: true, - value: [{ - name: "PFX.macData.mac.digestAlgorithm.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "macAlgorithm" - }, { - name: "PFX.macData.mac.digestAlgorithm.parameters", - optional: true, - tagClass: asn1.Class.UNIVERSAL, - captureAsn1: "macAlgorithmParameters" - }] - }, { - name: "PFX.macData.mac.digest", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "macDigest" - }] - }, { - name: "PFX.macData.macSalt", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "macSalt" - }, { - name: "PFX.macData.iterations", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - optional: true, - capture: "macIterations" - }] - } - ] - }; - var safeBagValidator = { - name: "SafeBag", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "SafeBag.bagId", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "bagId" - }, { - name: "SafeBag.bagValue", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - constructed: true, - captureAsn1: "bagValue" - }, { - name: "SafeBag.bagAttributes", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SET, - constructed: true, - optional: true, - capture: "bagAttributes" - }] - }; - var attributeValidator = { - name: "Attribute", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "Attribute.attrId", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "oid" - }, { - name: "Attribute.attrValues", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SET, - constructed: true, - capture: "values" - }] - }; - var certBagValidator = { - name: "CertBag", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "CertBag.certId", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "certId" - }, { - name: "CertBag.certValue", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - constructed: true, - /* So far we only support X.509 certificates (which are wrapped in - an OCTET STRING, hence hard code that here). */ - value: [{ - name: "CertBag.certValue[0]", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Class.OCTETSTRING, - constructed: false, - capture: "cert" - }] - }] - }; - function _getBagsByAttribute(safeContents, attrName, attrValue, bagType) { - var result = []; - for (var i = 0; i < safeContents.length; i++) { - for (var j = 0; j < safeContents[i].safeBags.length; j++) { - var bag = safeContents[i].safeBags[j]; - if (bagType !== void 0 && bag.type !== bagType) { - continue; - } - if (attrName === null) { - result.push(bag); - continue; - } - if (bag.attributes[attrName] !== void 0 && bag.attributes[attrName].indexOf(attrValue) >= 0) { - result.push(bag); - } - } - } - return result; - } - p12.pkcs12FromAsn1 = function(obj, strict, password) { - if (typeof strict === "string") { - password = strict; - strict = true; - } else if (strict === void 0) { - strict = true; - } - var capture = {}; - var errors = []; - if (!asn1.validate(obj, pfxValidator, capture, errors)) { - var error3 = new Error("Cannot read PKCS#12 PFX. ASN.1 object is not an PKCS#12 PFX."); - error3.errors = error3; - throw error3; - } - var pfx = { - version: capture.version.charCodeAt(0), - safeContents: [], - /** - * Gets bags with matching attributes. - * - * @param filter the attributes to filter by: - * [localKeyId] the localKeyId to search for. - * [localKeyIdHex] the localKeyId in hex to search for. - * [friendlyName] the friendly name to search for. - * [bagType] bag type to narrow each attribute search by. - * - * @return a map of attribute type to an array of matching bags or, if no - * attribute was given but a bag type, the map key will be the - * bag type. - */ - getBags: function(filter) { - var rval = {}; - var localKeyId; - if ("localKeyId" in filter) { - localKeyId = filter.localKeyId; - } else if ("localKeyIdHex" in filter) { - localKeyId = forge.util.hexToBytes(filter.localKeyIdHex); - } - if (localKeyId === void 0 && !("friendlyName" in filter) && "bagType" in filter) { - rval[filter.bagType] = _getBagsByAttribute( - pfx.safeContents, - null, - null, - filter.bagType - ); - } - if (localKeyId !== void 0) { - rval.localKeyId = _getBagsByAttribute( - pfx.safeContents, - "localKeyId", - localKeyId, - filter.bagType - ); - } - if ("friendlyName" in filter) { - rval.friendlyName = _getBagsByAttribute( - pfx.safeContents, - "friendlyName", - filter.friendlyName, - filter.bagType - ); - } - return rval; - }, - /** - * DEPRECATED: use getBags() instead. - * - * Get bags with matching friendlyName attribute. - * - * @param friendlyName the friendly name to search for. - * @param [bagType] bag type to narrow search by. - * - * @return an array of bags with matching friendlyName attribute. - */ - getBagsByFriendlyName: function(friendlyName, bagType) { - return _getBagsByAttribute( - pfx.safeContents, - "friendlyName", - friendlyName, - bagType - ); - }, - /** - * DEPRECATED: use getBags() instead. - * - * Get bags with matching localKeyId attribute. - * - * @param localKeyId the localKeyId to search for. - * @param [bagType] bag type to narrow search by. - * - * @return an array of bags with matching localKeyId attribute. - */ - getBagsByLocalKeyId: function(localKeyId, bagType) { - return _getBagsByAttribute( - pfx.safeContents, - "localKeyId", - localKeyId, - bagType - ); - } - }; - if (capture.version.charCodeAt(0) !== 3) { - var error3 = new Error("PKCS#12 PFX of version other than 3 not supported."); - error3.version = capture.version.charCodeAt(0); - throw error3; - } - if (asn1.derToOid(capture.contentType) !== pki2.oids.data) { - var error3 = new Error("Only PKCS#12 PFX in password integrity mode supported."); - error3.oid = asn1.derToOid(capture.contentType); - throw error3; - } - var data = capture.content.value[0]; - if (data.tagClass !== asn1.Class.UNIVERSAL || data.type !== asn1.Type.OCTETSTRING) { - throw new Error("PKCS#12 authSafe content data is not an OCTET STRING."); - } - data = _decodePkcs7Data(data); - if (capture.mac) { - var md2 = null; - var macKeyBytes = 0; - var macAlgorithm = asn1.derToOid(capture.macAlgorithm); - switch (macAlgorithm) { - case pki2.oids.sha1: - md2 = forge.md.sha1.create(); - macKeyBytes = 20; - break; - case pki2.oids.sha256: - md2 = forge.md.sha256.create(); - macKeyBytes = 32; - break; - case pki2.oids.sha384: - md2 = forge.md.sha384.create(); - macKeyBytes = 48; - break; - case pki2.oids.sha512: - md2 = forge.md.sha512.create(); - macKeyBytes = 64; - break; - case pki2.oids.md5: - md2 = forge.md.md5.create(); - macKeyBytes = 16; - break; - } - if (md2 === null) { - throw new Error("PKCS#12 uses unsupported MAC algorithm: " + macAlgorithm); - } - var macSalt = new forge.util.ByteBuffer(capture.macSalt); - var macIterations = "macIterations" in capture ? parseInt(forge.util.bytesToHex(capture.macIterations), 16) : 1; - var macKey = p12.generateKey( - password, - macSalt, - 3, - macIterations, - macKeyBytes, - md2 - ); - var mac = forge.hmac.create(); - mac.start(md2, macKey); - mac.update(data.value); - var macValue = mac.getMac(); - if (macValue.getBytes() !== capture.macDigest) { - throw new Error("PKCS#12 MAC could not be verified. Invalid password?"); - } - } else if (Array.isArray(obj.value) && obj.value.length > 2) { - throw new Error("Invalid PKCS#12. macData field present but MAC was not validated."); - } - _decodeAuthenticatedSafe(pfx, data.value, strict, password); - return pfx; - }; - function _decodePkcs7Data(data) { - if (data.composed || data.constructed) { - var value = forge.util.createBuffer(); - for (var i = 0; i < data.value.length; ++i) { - value.putBytes(data.value[i].value); - } - data.composed = data.constructed = false; - data.value = value.getBytes(); - } - return data; - } - function _decodeAuthenticatedSafe(pfx, authSafe, strict, password) { - authSafe = asn1.fromDer(authSafe, strict); - if (authSafe.tagClass !== asn1.Class.UNIVERSAL || authSafe.type !== asn1.Type.SEQUENCE || authSafe.constructed !== true) { - throw new Error("PKCS#12 AuthenticatedSafe expected to be a SEQUENCE OF ContentInfo"); - } - for (var i = 0; i < authSafe.value.length; i++) { - var contentInfo = authSafe.value[i]; - var capture = {}; - var errors = []; - if (!asn1.validate(contentInfo, contentInfoValidator, capture, errors)) { - var error3 = new Error("Cannot read ContentInfo."); - error3.errors = errors; - throw error3; - } - var obj = { - encrypted: false - }; - var safeContents = null; - var data = capture.content.value[0]; - switch (asn1.derToOid(capture.contentType)) { - case pki2.oids.data: - if (data.tagClass !== asn1.Class.UNIVERSAL || data.type !== asn1.Type.OCTETSTRING) { - throw new Error("PKCS#12 SafeContents Data is not an OCTET STRING."); - } - safeContents = _decodePkcs7Data(data).value; - break; - case pki2.oids.encryptedData: - safeContents = _decryptSafeContents(data, password); - obj.encrypted = true; - break; - default: - var error3 = new Error("Unsupported PKCS#12 contentType."); - error3.contentType = asn1.derToOid(capture.contentType); - throw error3; - } - obj.safeBags = _decodeSafeContents(safeContents, strict, password); - pfx.safeContents.push(obj); - } - } - function _decryptSafeContents(data, password) { - var capture = {}; - var errors = []; - if (!asn1.validate( - data, - forge.pkcs7.asn1.encryptedDataValidator, - capture, - errors - )) { - var error3 = new Error("Cannot read EncryptedContentInfo."); - error3.errors = errors; - throw error3; - } - var oid = asn1.derToOid(capture.contentType); - if (oid !== pki2.oids.data) { - var error3 = new Error( - "PKCS#12 EncryptedContentInfo ContentType is not Data." - ); - error3.oid = oid; - throw error3; - } - oid = asn1.derToOid(capture.encAlgorithm); - var cipher = pki2.pbe.getCipher(oid, capture.encParameter, password); - var encryptedContentAsn1 = _decodePkcs7Data(capture.encryptedContentAsn1); - var encrypted = forge.util.createBuffer(encryptedContentAsn1.value); - cipher.update(encrypted); - if (!cipher.finish()) { - throw new Error("Failed to decrypt PKCS#12 SafeContents."); - } - return cipher.output.getBytes(); - } - function _decodeSafeContents(safeContents, strict, password) { - if (!strict && safeContents.length === 0) { - return []; - } - safeContents = asn1.fromDer(safeContents, strict); - if (safeContents.tagClass !== asn1.Class.UNIVERSAL || safeContents.type !== asn1.Type.SEQUENCE || safeContents.constructed !== true) { - throw new Error( - "PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag." - ); - } - var res = []; - for (var i = 0; i < safeContents.value.length; i++) { - var safeBag = safeContents.value[i]; - var capture = {}; - var errors = []; - if (!asn1.validate(safeBag, safeBagValidator, capture, errors)) { - var error3 = new Error("Cannot read SafeBag."); - error3.errors = errors; - throw error3; - } - var bag = { - type: asn1.derToOid(capture.bagId), - attributes: _decodeBagAttributes(capture.bagAttributes) - }; - res.push(bag); - var validator, decoder; - var bagAsn1 = capture.bagValue.value[0]; - switch (bag.type) { - case pki2.oids.pkcs8ShroudedKeyBag: - bagAsn1 = pki2.decryptPrivateKeyInfo(bagAsn1, password); - if (bagAsn1 === null) { - throw new Error( - "Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?" - ); - } - /* fall through */ - case pki2.oids.keyBag: - try { - bag.key = pki2.privateKeyFromAsn1(bagAsn1); - } catch (e) { - bag.key = null; - bag.asn1 = bagAsn1; - } - continue; - /* Nothing more to do. */ - case pki2.oids.certBag: - validator = certBagValidator; - decoder = function() { - if (asn1.derToOid(capture.certId) !== pki2.oids.x509Certificate) { - var error4 = new Error( - "Unsupported certificate type, only X.509 supported." - ); - error4.oid = asn1.derToOid(capture.certId); - throw error4; - } - var certAsn1 = asn1.fromDer(capture.cert, strict); - try { - bag.cert = pki2.certificateFromAsn1(certAsn1, true); - } catch (e) { - bag.cert = null; - bag.asn1 = certAsn1; - } - }; - break; - default: - var error3 = new Error("Unsupported PKCS#12 SafeBag type."); - error3.oid = bag.type; - throw error3; - } - if (validator !== void 0 && !asn1.validate(bagAsn1, validator, capture, errors)) { - var error3 = new Error("Cannot read PKCS#12 " + validator.name); - error3.errors = errors; - throw error3; - } - decoder(); - } - return res; - } - function _decodeBagAttributes(attributes) { - var decodedAttrs = {}; - if (attributes !== void 0) { - for (var i = 0; i < attributes.length; ++i) { - var capture = {}; - var errors = []; - if (!asn1.validate(attributes[i], attributeValidator, capture, errors)) { - var error3 = new Error("Cannot read PKCS#12 BagAttribute."); - error3.errors = errors; - throw error3; - } - var oid = asn1.derToOid(capture.oid); - if (pki2.oids[oid] === void 0) { - continue; - } - decodedAttrs[pki2.oids[oid]] = []; - for (var j = 0; j < capture.values.length; ++j) { - decodedAttrs[pki2.oids[oid]].push(capture.values[j].value); - } - } - } - return decodedAttrs; - } - p12.toPkcs12Asn1 = function(key, cert, password, options) { - options = options || {}; - options.saltSize = options.saltSize || 8; - options.count = options.count || 2048; - options.algorithm = options.algorithm || options.encAlgorithm || "aes128"; - if (!("useMac" in options)) { - options.useMac = true; - } - if (!("localKeyId" in options)) { - options.localKeyId = null; - } - if (!("generateLocalKeyId" in options)) { - options.generateLocalKeyId = true; - } - var localKeyId = options.localKeyId; - var bagAttrs; - if (localKeyId !== null) { - localKeyId = forge.util.hexToBytes(localKeyId); - } else if (options.generateLocalKeyId) { - if (cert) { - var pairedCert = forge.util.isArray(cert) ? cert[0] : cert; - if (typeof pairedCert === "string") { - pairedCert = pki2.certificateFromPem(pairedCert); - } - var sha1 = forge.md.sha1.create(); - sha1.update(asn1.toDer(pki2.certificateToAsn1(pairedCert)).getBytes()); - localKeyId = sha1.digest().getBytes(); - } else { - localKeyId = forge.random.getBytes(20); - } - } - var attrs = []; - if (localKeyId !== null) { - attrs.push( - // localKeyID - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // attrId - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki2.oids.localKeyId).getBytes() - ), - // attrValues - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - localKeyId - ) - ]) - ]) - ); - } - if ("friendlyName" in options) { - attrs.push( - // friendlyName - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // attrId - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki2.oids.friendlyName).getBytes() - ), - // attrValues - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BMPSTRING, - false, - options.friendlyName - ) - ]) - ]) - ); - } - if (attrs.length > 0) { - bagAttrs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, attrs); - } - var contents = []; - var chain = []; - if (cert !== null) { - if (forge.util.isArray(cert)) { - chain = cert; - } else { - chain = [cert]; - } - } - var certSafeBags = []; - for (var i = 0; i < chain.length; ++i) { - cert = chain[i]; - if (typeof cert === "string") { - cert = pki2.certificateFromPem(cert); - } - var certBagAttrs = i === 0 ? bagAttrs : void 0; - var certAsn1 = pki2.certificateToAsn1(cert); - var certSafeBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // bagId - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki2.oids.certBag).getBytes() - ), - // bagValue - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - // CertBag - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // certId - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki2.oids.x509Certificate).getBytes() - ), - // certValue (x509Certificate) - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - asn1.toDer(certAsn1).getBytes() - ) - ]) - ]) - ]), - // bagAttributes (OPTIONAL) - certBagAttrs - ]); - certSafeBags.push(certSafeBag); - } - if (certSafeBags.length > 0) { - var certSafeContents = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - certSafeBags - ); - var certCI = ( - // PKCS#7 ContentInfo - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // contentType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - // OID for the content type is 'data' - asn1.oidToDer(pki2.oids.data).getBytes() - ), - // content - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - asn1.toDer(certSafeContents).getBytes() - ) - ]) - ]) - ); - contents.push(certCI); - } - var keyBag = null; - if (key !== null) { - var pkAsn1 = pki2.wrapRsaPrivateKey(pki2.privateKeyToAsn1(key)); - if (password === null) { - keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // bagId - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki2.oids.keyBag).getBytes() - ), - // bagValue - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - // PrivateKeyInfo - pkAsn1 - ]), - // bagAttributes (OPTIONAL) - bagAttrs - ]); - } else { - keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // bagId - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki2.oids.pkcs8ShroudedKeyBag).getBytes() - ), - // bagValue - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - // EncryptedPrivateKeyInfo - pki2.encryptPrivateKeyInfo(pkAsn1, password, options) - ]), - // bagAttributes (OPTIONAL) - bagAttrs - ]); - } - var keySafeContents = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [keyBag]); - var keyCI = ( - // PKCS#7 ContentInfo - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // contentType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - // OID for the content type is 'data' - asn1.oidToDer(pki2.oids.data).getBytes() - ), - // content - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - asn1.toDer(keySafeContents).getBytes() - ) - ]) - ]) - ); - contents.push(keyCI); - } - var safe = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - contents - ); - var macData; - if (options.useMac) { - var sha1 = forge.md.sha1.create(); - var macSalt = new forge.util.ByteBuffer( - forge.random.getBytes(options.saltSize) - ); - var count = options.count; - var key = p12.generateKey(password, macSalt, 3, count, 20); - var mac = forge.hmac.create(); - mac.start(sha1, key); - mac.update(asn1.toDer(safe).getBytes()); - var macValue = mac.getMac(); - macData = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // mac DigestInfo - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // digestAlgorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm = SHA-1 - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki2.oids.sha1).getBytes() - ), - // parameters = Null - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]), - // digest - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - macValue.getBytes() - ) - ]), - // macSalt OCTET STRING - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - macSalt.getBytes() - ), - // iterations INTEGER (XXX: Only support count < 65536) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(count).getBytes() - ) - ]); - } - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // version (3) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(3).getBytes() - ), - // PKCS#7 ContentInfo - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // contentType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - // OID for the content type is 'data' - asn1.oidToDer(pki2.oids.data).getBytes() - ), - // content - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - asn1.toDer(safe).getBytes() - ) - ]) - ]), - macData - ]); - }; - p12.generateKey = forge.pbe.generatePkcs12Key; - } -}); - -// node_modules/node-forge/lib/pki.js -var require_pki = __commonJS({ - "node_modules/node-forge/lib/pki.js"(exports2, module2) { - var forge = require_forge(); - require_asn1(); - require_oids(); - require_pbe(); - require_pem(); - require_pbkdf2(); - require_pkcs12(); - require_pss(); - require_rsa(); - require_util13(); - require_x509(); - var asn1 = forge.asn1; - var pki2 = module2.exports = forge.pki = forge.pki || {}; - pki2.pemToDer = function(pem) { - var msg = forge.pem.decode(pem)[0]; - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error("Could not convert PEM to DER; PEM is encrypted."); - } - return forge.util.createBuffer(msg.body); - }; - pki2.privateKeyFromPem = function(pem) { - var msg = forge.pem.decode(pem)[0]; - if (msg.type !== "PRIVATE KEY" && msg.type !== "RSA PRIVATE KEY") { - var error3 = new Error('Could not convert private key from PEM; PEM header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".'); - error3.headerType = msg.type; - throw error3; - } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error("Could not convert private key from PEM; PEM is encrypted."); - } - var obj = asn1.fromDer(msg.body); - return pki2.privateKeyFromAsn1(obj); - }; - pki2.privateKeyToPem = function(key, maxline) { - var msg = { - type: "RSA PRIVATE KEY", - body: asn1.toDer(pki2.privateKeyToAsn1(key)).getBytes() - }; - return forge.pem.encode(msg, { maxline }); - }; - pki2.privateKeyInfoToPem = function(pki3, maxline) { - var msg = { - type: "PRIVATE KEY", - body: asn1.toDer(pki3).getBytes() - }; - return forge.pem.encode(msg, { maxline }); - }; - } -}); - -// node_modules/node-forge/lib/tls.js -var require_tls = __commonJS({ - "node_modules/node-forge/lib/tls.js"(exports2, module2) { - var forge = require_forge(); - require_asn1(); - require_hmac(); - require_md5(); - require_pem(); - require_pki(); - require_random(); - require_sha1(); - require_util13(); - var prf_TLS1 = function(secret, label, seed, length) { - var rval = forge.util.createBuffer(); - var idx = secret.length >> 1; - var slen = idx + (secret.length & 1); - var s1 = secret.substr(0, slen); - var s2 = secret.substr(idx, slen); - var ai = forge.util.createBuffer(); - var hmac = forge.hmac.create(); - seed = label + seed; - var md5itr = Math.ceil(length / 16); - var sha1itr = Math.ceil(length / 20); - hmac.start("MD5", s1); - var md5bytes = forge.util.createBuffer(); - ai.putBytes(seed); - for (var i = 0; i < md5itr; ++i) { - hmac.start(null, null); - hmac.update(ai.getBytes()); - ai.putBuffer(hmac.digest()); - hmac.start(null, null); - hmac.update(ai.bytes() + seed); - md5bytes.putBuffer(hmac.digest()); - } - hmac.start("SHA1", s2); - var sha1bytes = forge.util.createBuffer(); - ai.clear(); - ai.putBytes(seed); - for (var i = 0; i < sha1itr; ++i) { - hmac.start(null, null); - hmac.update(ai.getBytes()); - ai.putBuffer(hmac.digest()); - hmac.start(null, null); - hmac.update(ai.bytes() + seed); - sha1bytes.putBuffer(hmac.digest()); - } - rval.putBytes(forge.util.xorBytes( - md5bytes.getBytes(), - sha1bytes.getBytes(), - length - )); - return rval; - }; - var hmac_sha1 = function(key2, seqNum, record) { - var hmac = forge.hmac.create(); - hmac.start("SHA1", key2); - var b = forge.util.createBuffer(); - b.putInt32(seqNum[0]); - b.putInt32(seqNum[1]); - b.putByte(record.type); - b.putByte(record.version.major); - b.putByte(record.version.minor); - b.putInt16(record.length); - b.putBytes(record.fragment.bytes()); - hmac.update(b.getBytes()); - return hmac.digest().getBytes(); - }; - var deflate = function(c, record, s) { - var rval = false; - try { - var bytes = c.deflate(record.fragment.getBytes()); - record.fragment = forge.util.createBuffer(bytes); - record.length = bytes.length; - rval = true; - } catch (ex) { - } - return rval; - }; - var inflate = function(c, record, s) { - var rval = false; - try { - var bytes = c.inflate(record.fragment.getBytes()); - record.fragment = forge.util.createBuffer(bytes); - record.length = bytes.length; - rval = true; - } catch (ex) { - } - return rval; - }; - var readVector = function(b, lenBytes) { - var len = 0; - switch (lenBytes) { - case 1: - len = b.getByte(); - break; - case 2: - len = b.getInt16(); - break; - case 3: - len = b.getInt24(); - break; - case 4: - len = b.getInt32(); - break; - } - return forge.util.createBuffer(b.getBytes(len)); - }; - var writeVector = function(b, lenBytes, v) { - b.putInt(v.length(), lenBytes << 3); - b.putBuffer(v); - }; - var tls = {}; - tls.Versions = { - TLS_1_0: { major: 3, minor: 1 }, - TLS_1_1: { major: 3, minor: 2 }, - TLS_1_2: { major: 3, minor: 3 } - }; - tls.SupportedVersions = [ - tls.Versions.TLS_1_1, - tls.Versions.TLS_1_0 - ]; - tls.Version = tls.SupportedVersions[0]; - tls.MaxFragment = 16384 - 1024; - tls.ConnectionEnd = { - server: 0, - client: 1 - }; - tls.PRFAlgorithm = { - tls_prf_sha256: 0 - }; - tls.BulkCipherAlgorithm = { - none: null, - rc4: 0, - des3: 1, - aes: 2 - }; - tls.CipherType = { - stream: 0, - block: 1, - aead: 2 - }; - tls.MACAlgorithm = { - none: null, - hmac_md5: 0, - hmac_sha1: 1, - hmac_sha256: 2, - hmac_sha384: 3, - hmac_sha512: 4 - }; - tls.CompressionMethod = { - none: 0, - deflate: 1 - }; - tls.ContentType = { - change_cipher_spec: 20, - alert: 21, - handshake: 22, - application_data: 23, - heartbeat: 24 - }; - tls.HandshakeType = { - hello_request: 0, - client_hello: 1, - server_hello: 2, - certificate: 11, - server_key_exchange: 12, - certificate_request: 13, - server_hello_done: 14, - certificate_verify: 15, - client_key_exchange: 16, - finished: 20 - }; - tls.Alert = {}; - tls.Alert.Level = { - warning: 1, - fatal: 2 - }; - tls.Alert.Description = { - close_notify: 0, - unexpected_message: 10, - bad_record_mac: 20, - decryption_failed: 21, - record_overflow: 22, - decompression_failure: 30, - handshake_failure: 40, - bad_certificate: 42, - unsupported_certificate: 43, - certificate_revoked: 44, - certificate_expired: 45, - certificate_unknown: 46, - illegal_parameter: 47, - unknown_ca: 48, - access_denied: 49, - decode_error: 50, - decrypt_error: 51, - export_restriction: 60, - protocol_version: 70, - insufficient_security: 71, - internal_error: 80, - user_canceled: 90, - no_renegotiation: 100 - }; - tls.HeartbeatMessageType = { - heartbeat_request: 1, - heartbeat_response: 2 - }; - tls.CipherSuites = {}; - tls.getCipherSuite = function(twoBytes) { - var rval = null; - for (var key2 in tls.CipherSuites) { - var cs = tls.CipherSuites[key2]; - if (cs.id[0] === twoBytes.charCodeAt(0) && cs.id[1] === twoBytes.charCodeAt(1)) { - rval = cs; - break; - } - } - return rval; - }; - tls.handleUnexpected = function(c, record) { - var ignore = !c.open && c.entity === tls.ConnectionEnd.client; - if (!ignore) { - c.error(c, { - message: "Unexpected message. Received TLS record out of order.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.unexpected_message - } - }); - } - }; - tls.handleHelloRequest = function(c, record, length) { - if (!c.handshaking && c.handshakes > 0) { - tls.queue(c, tls.createAlert(c, { - level: tls.Alert.Level.warning, - description: tls.Alert.Description.no_renegotiation - })); - tls.flush(c); - } - c.process(); - }; - tls.parseHelloMessage = function(c, record, length) { - var msg = null; - var client = c.entity === tls.ConnectionEnd.client; - if (length < 38) { - c.error(c, { - message: client ? "Invalid ServerHello message. Message too short." : "Invalid ClientHello message. Message too short.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.illegal_parameter - } - }); - } else { - var b = record.fragment; - var remaining = b.length(); - msg = { - version: { - major: b.getByte(), - minor: b.getByte() - }, - random: forge.util.createBuffer(b.getBytes(32)), - session_id: readVector(b, 1), - extensions: [] - }; - if (client) { - msg.cipher_suite = b.getBytes(2); - msg.compression_method = b.getByte(); - } else { - msg.cipher_suites = readVector(b, 2); - msg.compression_methods = readVector(b, 1); - } - remaining = length - (remaining - b.length()); - if (remaining > 0) { - var exts = readVector(b, 2); - while (exts.length() > 0) { - msg.extensions.push({ - type: [exts.getByte(), exts.getByte()], - data: readVector(exts, 2) - }); - } - if (!client) { - for (var i = 0; i < msg.extensions.length; ++i) { - var ext = msg.extensions[i]; - if (ext.type[0] === 0 && ext.type[1] === 0) { - var snl = readVector(ext.data, 2); - while (snl.length() > 0) { - var snType = snl.getByte(); - if (snType !== 0) { - break; - } - c.session.extensions.server_name.serverNameList.push( - readVector(snl, 2).getBytes() - ); - } - } - } - } - } - if (c.session.version) { - if (msg.version.major !== c.session.version.major || msg.version.minor !== c.session.version.minor) { - return c.error(c, { - message: "TLS version change is disallowed during renegotiation.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.protocol_version - } - }); - } - } - if (client) { - c.session.cipherSuite = tls.getCipherSuite(msg.cipher_suite); - } else { - var tmp = forge.util.createBuffer(msg.cipher_suites.bytes()); - while (tmp.length() > 0) { - c.session.cipherSuite = tls.getCipherSuite(tmp.getBytes(2)); - if (c.session.cipherSuite !== null) { - break; - } - } - } - if (c.session.cipherSuite === null) { - return c.error(c, { - message: "No cipher suites in common.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.handshake_failure - }, - cipherSuite: forge.util.bytesToHex(msg.cipher_suite) - }); - } - if (client) { - c.session.compressionMethod = msg.compression_method; - } else { - c.session.compressionMethod = tls.CompressionMethod.none; - } - } - return msg; - }; - tls.createSecurityParameters = function(c, msg) { - var client = c.entity === tls.ConnectionEnd.client; - var msgRandom = msg.random.bytes(); - var cRandom = client ? c.session.sp.client_random : msgRandom; - var sRandom = client ? msgRandom : tls.createRandom().getBytes(); - c.session.sp = { - entity: c.entity, - prf_algorithm: tls.PRFAlgorithm.tls_prf_sha256, - bulk_cipher_algorithm: null, - cipher_type: null, - enc_key_length: null, - block_length: null, - fixed_iv_length: null, - record_iv_length: null, - mac_algorithm: null, - mac_length: null, - mac_key_length: null, - compression_algorithm: c.session.compressionMethod, - pre_master_secret: null, - master_secret: null, - client_random: cRandom, - server_random: sRandom - }; - }; - tls.handleServerHello = function(c, record, length) { - var msg = tls.parseHelloMessage(c, record, length); - if (c.fail) { - return; - } - if (msg.version.minor <= c.version.minor) { - c.version.minor = msg.version.minor; - } else { - return c.error(c, { - message: "Incompatible TLS version.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.protocol_version - } - }); - } - c.session.version = c.version; - var sessionId = msg.session_id.bytes(); - if (sessionId.length > 0 && sessionId === c.session.id) { - c.expect = SCC; - c.session.resuming = true; - c.session.sp.server_random = msg.random.bytes(); - } else { - c.expect = SCE; - c.session.resuming = false; - tls.createSecurityParameters(c, msg); - } - c.session.id = sessionId; - c.process(); - }; - tls.handleClientHello = function(c, record, length) { - var msg = tls.parseHelloMessage(c, record, length); - if (c.fail) { - return; - } - var sessionId = msg.session_id.bytes(); - var session = null; - if (c.sessionCache) { - session = c.sessionCache.getSession(sessionId); - if (session === null) { - sessionId = ""; - } else if (session.version.major !== msg.version.major || session.version.minor > msg.version.minor) { - session = null; - sessionId = ""; - } - } - if (sessionId.length === 0) { - sessionId = forge.random.getBytes(32); - } - c.session.id = sessionId; - c.session.clientHelloVersion = msg.version; - c.session.sp = {}; - if (session) { - c.version = c.session.version = session.version; - c.session.sp = session.sp; - } else { - var version; - for (var i = 1; i < tls.SupportedVersions.length; ++i) { - version = tls.SupportedVersions[i]; - if (version.minor <= msg.version.minor) { - break; - } - } - c.version = { major: version.major, minor: version.minor }; - c.session.version = c.version; - } - if (session !== null) { - c.expect = CCC; - c.session.resuming = true; - c.session.sp.client_random = msg.random.bytes(); - } else { - c.expect = c.verifyClient !== false ? CCE : CKE; - c.session.resuming = false; - tls.createSecurityParameters(c, msg); - } - c.open = true; - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createServerHello(c) - })); - if (c.session.resuming) { - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.change_cipher_spec, - data: tls.createChangeCipherSpec() - })); - c.state.pending = tls.createConnectionState(c); - c.state.current.write = c.state.pending.write; - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createFinished(c) - })); - } else { - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createCertificate(c) - })); - if (!c.fail) { - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createServerKeyExchange(c) - })); - if (c.verifyClient !== false) { - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createCertificateRequest(c) - })); - } - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createServerHelloDone(c) - })); - } - } - tls.flush(c); - c.process(); - }; - tls.handleCertificate = function(c, record, length) { - if (length < 3) { - return c.error(c, { - message: "Invalid Certificate message. Message too short.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.illegal_parameter - } - }); - } - var b = record.fragment; - var msg = { - certificate_list: readVector(b, 3) - }; - var cert, asn1; - var certs = []; - try { - while (msg.certificate_list.length() > 0) { - cert = readVector(msg.certificate_list, 3); - asn1 = forge.asn1.fromDer(cert); - cert = forge.pki.certificateFromAsn1(asn1, true); - certs.push(cert); - } - } catch (ex) { - return c.error(c, { - message: "Could not parse certificate list.", - cause: ex, - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.bad_certificate - } - }); - } - var client = c.entity === tls.ConnectionEnd.client; - if ((client || c.verifyClient === true) && certs.length === 0) { - c.error(c, { - message: client ? "No server certificate provided." : "No client certificate provided.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.illegal_parameter - } - }); - } else if (certs.length === 0) { - c.expect = client ? SKE : CKE; - } else { - if (client) { - c.session.serverCertificate = certs[0]; - } else { - c.session.clientCertificate = certs[0]; - } - if (tls.verifyCertificateChain(c, certs)) { - c.expect = client ? SKE : CKE; - } - } - c.process(); - }; - tls.handleServerKeyExchange = function(c, record, length) { - if (length > 0) { - return c.error(c, { - message: "Invalid key parameters. Only RSA is supported.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.unsupported_certificate - } - }); - } - c.expect = SCR; - c.process(); - }; - tls.handleClientKeyExchange = function(c, record, length) { - if (length < 48) { - return c.error(c, { - message: "Invalid key parameters. Only RSA is supported.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.unsupported_certificate - } - }); - } - var b = record.fragment; - var msg = { - enc_pre_master_secret: readVector(b, 2).getBytes() - }; - var privateKey = null; - if (c.getPrivateKey) { - try { - privateKey = c.getPrivateKey(c, c.session.serverCertificate); - privateKey = forge.pki.privateKeyFromPem(privateKey); - } catch (ex) { - c.error(c, { - message: "Could not get private key.", - cause: ex, - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.internal_error - } - }); - } - } - if (privateKey === null) { - return c.error(c, { - message: "No private key set.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.internal_error - } - }); - } - try { - var sp = c.session.sp; - sp.pre_master_secret = privateKey.decrypt(msg.enc_pre_master_secret); - var version = c.session.clientHelloVersion; - if (version.major !== sp.pre_master_secret.charCodeAt(0) || version.minor !== sp.pre_master_secret.charCodeAt(1)) { - throw new Error("TLS version rollback attack detected."); - } - } catch (ex) { - sp.pre_master_secret = forge.random.getBytes(48); - } - c.expect = CCC; - if (c.session.clientCertificate !== null) { - c.expect = CCV; - } - c.process(); - }; - tls.handleCertificateRequest = function(c, record, length) { - if (length < 3) { - return c.error(c, { - message: "Invalid CertificateRequest. Message too short.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.illegal_parameter - } - }); - } - var b = record.fragment; - var msg = { - certificate_types: readVector(b, 1), - certificate_authorities: readVector(b, 2) - }; - c.session.certificateRequest = msg; - c.expect = SHD; - c.process(); - }; - tls.handleCertificateVerify = function(c, record, length) { - if (length < 2) { - return c.error(c, { - message: "Invalid CertificateVerify. Message too short.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.illegal_parameter - } - }); - } - var b = record.fragment; - b.read -= 4; - var msgBytes = b.bytes(); - b.read += 4; - var msg = { - signature: readVector(b, 2).getBytes() - }; - var verify = forge.util.createBuffer(); - verify.putBuffer(c.session.md5.digest()); - verify.putBuffer(c.session.sha1.digest()); - verify = verify.getBytes(); - try { - var cert = c.session.clientCertificate; - if (!cert.publicKey.verify(verify, msg.signature, "NONE")) { - throw new Error("CertificateVerify signature does not match."); - } - c.session.md5.update(msgBytes); - c.session.sha1.update(msgBytes); - } catch (ex) { - return c.error(c, { - message: "Bad signature in CertificateVerify.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.handshake_failure - } - }); - } - c.expect = CCC; - c.process(); - }; - tls.handleServerHelloDone = function(c, record, length) { - if (length > 0) { - return c.error(c, { - message: "Invalid ServerHelloDone message. Invalid length.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.record_overflow - } - }); - } - if (c.serverCertificate === null) { - var error3 = { - message: "No server certificate provided. Not enough security.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.insufficient_security - } - }; - var depth = 0; - var ret = c.verify(c, error3.alert.description, depth, []); - if (ret !== true) { - if (ret || ret === 0) { - if (typeof ret === "object" && !forge.util.isArray(ret)) { - if (ret.message) { - error3.message = ret.message; - } - if (ret.alert) { - error3.alert.description = ret.alert; - } - } else if (typeof ret === "number") { - error3.alert.description = ret; - } - } - return c.error(c, error3); - } - } - if (c.session.certificateRequest !== null) { - record = tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createCertificate(c) - }); - tls.queue(c, record); - } - record = tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createClientKeyExchange(c) - }); - tls.queue(c, record); - c.expect = SER; - var callback = function(c2, signature) { - if (c2.session.certificateRequest !== null && c2.session.clientCertificate !== null) { - tls.queue(c2, tls.createRecord(c2, { - type: tls.ContentType.handshake, - data: tls.createCertificateVerify(c2, signature) - })); - } - tls.queue(c2, tls.createRecord(c2, { - type: tls.ContentType.change_cipher_spec, - data: tls.createChangeCipherSpec() - })); - c2.state.pending = tls.createConnectionState(c2); - c2.state.current.write = c2.state.pending.write; - tls.queue(c2, tls.createRecord(c2, { - type: tls.ContentType.handshake, - data: tls.createFinished(c2) - })); - c2.expect = SCC; - tls.flush(c2); - c2.process(); - }; - if (c.session.certificateRequest === null || c.session.clientCertificate === null) { - return callback(c, null); - } - tls.getClientSignature(c, callback); - }; - tls.handleChangeCipherSpec = function(c, record) { - if (record.fragment.getByte() !== 1) { - return c.error(c, { - message: "Invalid ChangeCipherSpec message received.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.illegal_parameter - } - }); - } - var client = c.entity === tls.ConnectionEnd.client; - if (c.session.resuming && client || !c.session.resuming && !client) { - c.state.pending = tls.createConnectionState(c); - } - c.state.current.read = c.state.pending.read; - if (!c.session.resuming && client || c.session.resuming && !client) { - c.state.pending = null; - } - c.expect = client ? SFI : CFI; - c.process(); - }; - tls.handleFinished = function(c, record, length) { - var b = record.fragment; - b.read -= 4; - var msgBytes = b.bytes(); - b.read += 4; - var vd = record.fragment.getBytes(); - b = forge.util.createBuffer(); - b.putBuffer(c.session.md5.digest()); - b.putBuffer(c.session.sha1.digest()); - var client = c.entity === tls.ConnectionEnd.client; - var label = client ? "server finished" : "client finished"; - var sp = c.session.sp; - var vdl = 12; - var prf = prf_TLS1; - b = prf(sp.master_secret, label, b.getBytes(), vdl); - if (b.getBytes() !== vd) { - return c.error(c, { - message: "Invalid verify_data in Finished message.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.decrypt_error - } - }); - } - c.session.md5.update(msgBytes); - c.session.sha1.update(msgBytes); - if (c.session.resuming && client || !c.session.resuming && !client) { - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.change_cipher_spec, - data: tls.createChangeCipherSpec() - })); - c.state.current.write = c.state.pending.write; - c.state.pending = null; - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createFinished(c) - })); - } - c.expect = client ? SAD : CAD; - c.handshaking = false; - ++c.handshakes; - c.peerCertificate = client ? c.session.serverCertificate : c.session.clientCertificate; - tls.flush(c); - c.isConnected = true; - c.connected(c); - c.process(); - }; - tls.handleAlert = function(c, record) { - var b = record.fragment; - var alert = { - level: b.getByte(), - description: b.getByte() - }; - var msg; - switch (alert.description) { - case tls.Alert.Description.close_notify: - msg = "Connection closed."; - break; - case tls.Alert.Description.unexpected_message: - msg = "Unexpected message."; - break; - case tls.Alert.Description.bad_record_mac: - msg = "Bad record MAC."; - break; - case tls.Alert.Description.decryption_failed: - msg = "Decryption failed."; - break; - case tls.Alert.Description.record_overflow: - msg = "Record overflow."; - break; - case tls.Alert.Description.decompression_failure: - msg = "Decompression failed."; - break; - case tls.Alert.Description.handshake_failure: - msg = "Handshake failure."; - break; - case tls.Alert.Description.bad_certificate: - msg = "Bad certificate."; - break; - case tls.Alert.Description.unsupported_certificate: - msg = "Unsupported certificate."; - break; - case tls.Alert.Description.certificate_revoked: - msg = "Certificate revoked."; - break; - case tls.Alert.Description.certificate_expired: - msg = "Certificate expired."; - break; - case tls.Alert.Description.certificate_unknown: - msg = "Certificate unknown."; - break; - case tls.Alert.Description.illegal_parameter: - msg = "Illegal parameter."; - break; - case tls.Alert.Description.unknown_ca: - msg = "Unknown certificate authority."; - break; - case tls.Alert.Description.access_denied: - msg = "Access denied."; - break; - case tls.Alert.Description.decode_error: - msg = "Decode error."; - break; - case tls.Alert.Description.decrypt_error: - msg = "Decrypt error."; - break; - case tls.Alert.Description.export_restriction: - msg = "Export restriction."; - break; - case tls.Alert.Description.protocol_version: - msg = "Unsupported protocol version."; - break; - case tls.Alert.Description.insufficient_security: - msg = "Insufficient security."; - break; - case tls.Alert.Description.internal_error: - msg = "Internal error."; - break; - case tls.Alert.Description.user_canceled: - msg = "User canceled."; - break; - case tls.Alert.Description.no_renegotiation: - msg = "Renegotiation not supported."; - break; - default: - msg = "Unknown error."; - break; - } - if (alert.description === tls.Alert.Description.close_notify) { - return c.close(); - } - c.error(c, { - message: msg, - send: false, - // origin is the opposite end - origin: c.entity === tls.ConnectionEnd.client ? "server" : "client", - alert - }); - c.process(); - }; - tls.handleHandshake = function(c, record) { - var b = record.fragment; - var type = b.getByte(); - var length = b.getInt24(); - if (length > b.length()) { - c.fragmented = record; - record.fragment = forge.util.createBuffer(); - b.read -= 4; - return c.process(); - } - c.fragmented = null; - b.read -= 4; - var bytes = b.bytes(length + 4); - b.read += 4; - if (type in hsTable[c.entity][c.expect]) { - if (c.entity === tls.ConnectionEnd.server && !c.open && !c.fail) { - c.handshaking = true; - c.session = { - version: null, - extensions: { - server_name: { - serverNameList: [] - } - }, - cipherSuite: null, - compressionMethod: null, - serverCertificate: null, - clientCertificate: null, - md5: forge.md.md5.create(), - sha1: forge.md.sha1.create() - }; - } - if (type !== tls.HandshakeType.hello_request && type !== tls.HandshakeType.certificate_verify && type !== tls.HandshakeType.finished) { - c.session.md5.update(bytes); - c.session.sha1.update(bytes); - } - hsTable[c.entity][c.expect][type](c, record, length); - } else { - tls.handleUnexpected(c, record); - } - }; - tls.handleApplicationData = function(c, record) { - c.data.putBuffer(record.fragment); - c.dataReady(c); - c.process(); - }; - tls.handleHeartbeat = function(c, record) { - var b = record.fragment; - var type = b.getByte(); - var length = b.getInt16(); - var payload = b.getBytes(length); - if (type === tls.HeartbeatMessageType.heartbeat_request) { - if (c.handshaking || length > payload.length) { - return c.process(); - } - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.heartbeat, - data: tls.createHeartbeat( - tls.HeartbeatMessageType.heartbeat_response, - payload - ) - })); - tls.flush(c); - } else if (type === tls.HeartbeatMessageType.heartbeat_response) { - if (payload !== c.expectedHeartbeatPayload) { - return c.process(); - } - if (c.heartbeatReceived) { - c.heartbeatReceived(c, forge.util.createBuffer(payload)); - } - } - c.process(); - }; - var SHE = 0; - var SCE = 1; - var SKE = 2; - var SCR = 3; - var SHD = 4; - var SCC = 5; - var SFI = 6; - var SAD = 7; - var SER = 8; - var CHE = 0; - var CCE = 1; - var CKE = 2; - var CCV = 3; - var CCC = 4; - var CFI = 5; - var CAD = 6; - var __ = tls.handleUnexpected; - var R0 = tls.handleChangeCipherSpec; - var R1 = tls.handleAlert; - var R2 = tls.handleHandshake; - var R3 = tls.handleApplicationData; - var R4 = tls.handleHeartbeat; - var ctTable = []; - ctTable[tls.ConnectionEnd.client] = [ - // CC,AL,HS,AD,HB - /*SHE*/ - [__, R1, R2, __, R4], - /*SCE*/ - [__, R1, R2, __, R4], - /*SKE*/ - [__, R1, R2, __, R4], - /*SCR*/ - [__, R1, R2, __, R4], - /*SHD*/ - [__, R1, R2, __, R4], - /*SCC*/ - [R0, R1, __, __, R4], - /*SFI*/ - [__, R1, R2, __, R4], - /*SAD*/ - [__, R1, R2, R3, R4], - /*SER*/ - [__, R1, R2, __, R4] - ]; - ctTable[tls.ConnectionEnd.server] = [ - // CC,AL,HS,AD - /*CHE*/ - [__, R1, R2, __, R4], - /*CCE*/ - [__, R1, R2, __, R4], - /*CKE*/ - [__, R1, R2, __, R4], - /*CCV*/ - [__, R1, R2, __, R4], - /*CCC*/ - [R0, R1, __, __, R4], - /*CFI*/ - [__, R1, R2, __, R4], - /*CAD*/ - [__, R1, R2, R3, R4], - /*CER*/ - [__, R1, R2, __, R4] - ]; - var H0 = tls.handleHelloRequest; - var H1 = tls.handleServerHello; - var H2 = tls.handleCertificate; - var H3 = tls.handleServerKeyExchange; - var H4 = tls.handleCertificateRequest; - var H5 = tls.handleServerHelloDone; - var H6 = tls.handleFinished; - var hsTable = []; - hsTable[tls.ConnectionEnd.client] = [ - // HR,01,SH,03,04,05,06,07,08,09,10,SC,SK,CR,HD,15,CK,17,18,19,FI - /*SHE*/ - [__, __, H1, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], - /*SCE*/ - [H0, __, __, __, __, __, __, __, __, __, __, H2, H3, H4, H5, __, __, __, __, __, __], - /*SKE*/ - [H0, __, __, __, __, __, __, __, __, __, __, __, H3, H4, H5, __, __, __, __, __, __], - /*SCR*/ - [H0, __, __, __, __, __, __, __, __, __, __, __, __, H4, H5, __, __, __, __, __, __], - /*SHD*/ - [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, H5, __, __, __, __, __, __], - /*SCC*/ - [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], - /*SFI*/ - [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H6], - /*SAD*/ - [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], - /*SER*/ - [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __] - ]; - var H7 = tls.handleClientHello; - var H8 = tls.handleClientKeyExchange; - var H9 = tls.handleCertificateVerify; - hsTable[tls.ConnectionEnd.server] = [ - // 01,CH,02,03,04,05,06,07,08,09,10,CC,12,13,14,CV,CK,17,18,19,FI - /*CHE*/ - [__, H7, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], - /*CCE*/ - [__, __, __, __, __, __, __, __, __, __, __, H2, __, __, __, __, __, __, __, __, __], - /*CKE*/ - [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H8, __, __, __, __], - /*CCV*/ - [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H9, __, __, __, __, __], - /*CCC*/ - [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], - /*CFI*/ - [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H6], - /*CAD*/ - [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], - /*CER*/ - [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __] - ]; - tls.generateKeys = function(c, sp) { - var prf = prf_TLS1; - var random = sp.client_random + sp.server_random; - if (!c.session.resuming) { - sp.master_secret = prf( - sp.pre_master_secret, - "master secret", - random, - 48 - ).bytes(); - sp.pre_master_secret = null; - } - random = sp.server_random + sp.client_random; - var length = 2 * sp.mac_key_length + 2 * sp.enc_key_length; - var tls10 = c.version.major === tls.Versions.TLS_1_0.major && c.version.minor === tls.Versions.TLS_1_0.minor; - if (tls10) { - length += 2 * sp.fixed_iv_length; - } - var km = prf(sp.master_secret, "key expansion", random, length); - var rval = { - client_write_MAC_key: km.getBytes(sp.mac_key_length), - server_write_MAC_key: km.getBytes(sp.mac_key_length), - client_write_key: km.getBytes(sp.enc_key_length), - server_write_key: km.getBytes(sp.enc_key_length) - }; - if (tls10) { - rval.client_write_IV = km.getBytes(sp.fixed_iv_length); - rval.server_write_IV = km.getBytes(sp.fixed_iv_length); - } - return rval; - }; - tls.createConnectionState = function(c) { - var client = c.entity === tls.ConnectionEnd.client; - var createMode = function() { - var mode = { - // two 32-bit numbers, first is most significant - sequenceNumber: [0, 0], - macKey: null, - macLength: 0, - macFunction: null, - cipherState: null, - cipherFunction: function(record) { - return true; - }, - compressionState: null, - compressFunction: function(record) { - return true; - }, - updateSequenceNumber: function() { - if (mode.sequenceNumber[1] === 4294967295) { - mode.sequenceNumber[1] = 0; - ++mode.sequenceNumber[0]; - } else { - ++mode.sequenceNumber[1]; - } - } - }; - return mode; - }; - var state = { - read: createMode(), - write: createMode() - }; - state.read.update = function(c2, record) { - if (!state.read.cipherFunction(record, state.read)) { - c2.error(c2, { - message: "Could not decrypt record or bad MAC.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - // doesn't matter if decryption failed or MAC was - // invalid, return the same error so as not to reveal - // which one occurred - description: tls.Alert.Description.bad_record_mac - } - }); - } else if (!state.read.compressFunction(c2, record, state.read)) { - c2.error(c2, { - message: "Could not decompress record.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.decompression_failure - } - }); - } - return !c2.fail; - }; - state.write.update = function(c2, record) { - if (!state.write.compressFunction(c2, record, state.write)) { - c2.error(c2, { - message: "Could not compress record.", - send: false, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.internal_error - } - }); - } else if (!state.write.cipherFunction(record, state.write)) { - c2.error(c2, { - message: "Could not encrypt record.", - send: false, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.internal_error - } - }); - } - return !c2.fail; - }; - if (c.session) { - var sp = c.session.sp; - c.session.cipherSuite.initSecurityParameters(sp); - sp.keys = tls.generateKeys(c, sp); - state.read.macKey = client ? sp.keys.server_write_MAC_key : sp.keys.client_write_MAC_key; - state.write.macKey = client ? sp.keys.client_write_MAC_key : sp.keys.server_write_MAC_key; - c.session.cipherSuite.initConnectionState(state, c, sp); - switch (sp.compression_algorithm) { - case tls.CompressionMethod.none: - break; - case tls.CompressionMethod.deflate: - state.read.compressFunction = inflate; - state.write.compressFunction = deflate; - break; - default: - throw new Error("Unsupported compression algorithm."); - } - } - return state; - }; - tls.createRandom = function() { - var d = /* @__PURE__ */ new Date(); - var utc = +d + d.getTimezoneOffset() * 6e4; - var rval = forge.util.createBuffer(); - rval.putInt32(utc); - rval.putBytes(forge.random.getBytes(28)); - return rval; - }; - tls.createRecord = function(c, options) { - if (!options.data) { - return null; - } - var record = { - type: options.type, - version: { - major: c.version.major, - minor: c.version.minor - }, - length: options.data.length(), - fragment: options.data - }; - return record; - }; - tls.createAlert = function(c, alert) { - var b = forge.util.createBuffer(); - b.putByte(alert.level); - b.putByte(alert.description); - return tls.createRecord(c, { - type: tls.ContentType.alert, - data: b - }); - }; - tls.createClientHello = function(c) { - c.session.clientHelloVersion = { - major: c.version.major, - minor: c.version.minor - }; - var cipherSuites = forge.util.createBuffer(); - for (var i = 0; i < c.cipherSuites.length; ++i) { - var cs = c.cipherSuites[i]; - cipherSuites.putByte(cs.id[0]); - cipherSuites.putByte(cs.id[1]); - } - var cSuites = cipherSuites.length(); - var compressionMethods = forge.util.createBuffer(); - compressionMethods.putByte(tls.CompressionMethod.none); - var cMethods = compressionMethods.length(); - var extensions = forge.util.createBuffer(); - if (c.virtualHost) { - var ext = forge.util.createBuffer(); - ext.putByte(0); - ext.putByte(0); - var serverName = forge.util.createBuffer(); - serverName.putByte(0); - writeVector(serverName, 2, forge.util.createBuffer(c.virtualHost)); - var snList = forge.util.createBuffer(); - writeVector(snList, 2, serverName); - writeVector(ext, 2, snList); - extensions.putBuffer(ext); - } - var extLength = extensions.length(); - if (extLength > 0) { - extLength += 2; - } - var sessionId = c.session.id; - var length = sessionId.length + 1 + // session ID vector - 2 + // version (major + minor) - 4 + 28 + // random time and random bytes - 2 + cSuites + // cipher suites vector - 1 + cMethods + // compression methods vector - extLength; - var rval = forge.util.createBuffer(); - rval.putByte(tls.HandshakeType.client_hello); - rval.putInt24(length); - rval.putByte(c.version.major); - rval.putByte(c.version.minor); - rval.putBytes(c.session.sp.client_random); - writeVector(rval, 1, forge.util.createBuffer(sessionId)); - writeVector(rval, 2, cipherSuites); - writeVector(rval, 1, compressionMethods); - if (extLength > 0) { - writeVector(rval, 2, extensions); - } - return rval; - }; - tls.createServerHello = function(c) { - var sessionId = c.session.id; - var length = sessionId.length + 1 + // session ID vector - 2 + // version (major + minor) - 4 + 28 + // random time and random bytes - 2 + // chosen cipher suite - 1; - var rval = forge.util.createBuffer(); - rval.putByte(tls.HandshakeType.server_hello); - rval.putInt24(length); - rval.putByte(c.version.major); - rval.putByte(c.version.minor); - rval.putBytes(c.session.sp.server_random); - writeVector(rval, 1, forge.util.createBuffer(sessionId)); - rval.putByte(c.session.cipherSuite.id[0]); - rval.putByte(c.session.cipherSuite.id[1]); - rval.putByte(c.session.compressionMethod); - return rval; - }; - tls.createCertificate = function(c) { - var client = c.entity === tls.ConnectionEnd.client; - var cert = null; - if (c.getCertificate) { - var hint; - if (client) { - hint = c.session.certificateRequest; - } else { - hint = c.session.extensions.server_name.serverNameList; - } - cert = c.getCertificate(c, hint); - } - var certList = forge.util.createBuffer(); - if (cert !== null) { - try { - if (!forge.util.isArray(cert)) { - cert = [cert]; - } - var asn1 = null; - for (var i = 0; i < cert.length; ++i) { - var msg = forge.pem.decode(cert[i])[0]; - if (msg.type !== "CERTIFICATE" && msg.type !== "X509 CERTIFICATE" && msg.type !== "TRUSTED CERTIFICATE") { - var error3 = new Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".'); - error3.headerType = msg.type; - throw error3; - } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error("Could not convert certificate from PEM; PEM is encrypted."); - } - var der = forge.util.createBuffer(msg.body); - if (asn1 === null) { - asn1 = forge.asn1.fromDer(der.bytes(), false); - } - var certBuffer = forge.util.createBuffer(); - writeVector(certBuffer, 3, der); - certList.putBuffer(certBuffer); - } - cert = forge.pki.certificateFromAsn1(asn1); - if (client) { - c.session.clientCertificate = cert; - } else { - c.session.serverCertificate = cert; - } - } catch (ex) { - return c.error(c, { - message: "Could not send certificate list.", - cause: ex, - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.bad_certificate - } - }); - } - } - var length = 3 + certList.length(); - var rval = forge.util.createBuffer(); - rval.putByte(tls.HandshakeType.certificate); - rval.putInt24(length); - writeVector(rval, 3, certList); - return rval; - }; - tls.createClientKeyExchange = function(c) { - var b = forge.util.createBuffer(); - b.putByte(c.session.clientHelloVersion.major); - b.putByte(c.session.clientHelloVersion.minor); - b.putBytes(forge.random.getBytes(46)); - var sp = c.session.sp; - sp.pre_master_secret = b.getBytes(); - var key2 = c.session.serverCertificate.publicKey; - b = key2.encrypt(sp.pre_master_secret); - var length = b.length + 2; - var rval = forge.util.createBuffer(); - rval.putByte(tls.HandshakeType.client_key_exchange); - rval.putInt24(length); - rval.putInt16(b.length); - rval.putBytes(b); - return rval; - }; - tls.createServerKeyExchange = function(c) { - var length = 0; - var rval = forge.util.createBuffer(); - if (length > 0) { - rval.putByte(tls.HandshakeType.server_key_exchange); - rval.putInt24(length); - } - return rval; - }; - tls.getClientSignature = function(c, callback) { - var b = forge.util.createBuffer(); - b.putBuffer(c.session.md5.digest()); - b.putBuffer(c.session.sha1.digest()); - b = b.getBytes(); - c.getSignature = c.getSignature || function(c2, b2, callback2) { - var privateKey = null; - if (c2.getPrivateKey) { - try { - privateKey = c2.getPrivateKey(c2, c2.session.clientCertificate); - privateKey = forge.pki.privateKeyFromPem(privateKey); - } catch (ex) { - c2.error(c2, { - message: "Could not get private key.", - cause: ex, - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.internal_error - } - }); - } - } - if (privateKey === null) { - c2.error(c2, { - message: "No private key set.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.internal_error - } - }); - } else { - b2 = privateKey.sign(b2, null); - } - callback2(c2, b2); - }; - c.getSignature(c, b, callback); - }; - tls.createCertificateVerify = function(c, signature) { - var length = signature.length + 2; - var rval = forge.util.createBuffer(); - rval.putByte(tls.HandshakeType.certificate_verify); - rval.putInt24(length); - rval.putInt16(signature.length); - rval.putBytes(signature); - return rval; - }; - tls.createCertificateRequest = function(c) { - var certTypes = forge.util.createBuffer(); - certTypes.putByte(1); - var cAs = forge.util.createBuffer(); - for (var key2 in c.caStore.certs) { - var cert = c.caStore.certs[key2]; - var dn = forge.pki.distinguishedNameToAsn1(cert.subject); - var byteBuffer = forge.asn1.toDer(dn); - cAs.putInt16(byteBuffer.length()); - cAs.putBuffer(byteBuffer); - } - var length = 1 + certTypes.length() + 2 + cAs.length(); - var rval = forge.util.createBuffer(); - rval.putByte(tls.HandshakeType.certificate_request); - rval.putInt24(length); - writeVector(rval, 1, certTypes); - writeVector(rval, 2, cAs); - return rval; - }; - tls.createServerHelloDone = function(c) { - var rval = forge.util.createBuffer(); - rval.putByte(tls.HandshakeType.server_hello_done); - rval.putInt24(0); - return rval; - }; - tls.createChangeCipherSpec = function() { - var rval = forge.util.createBuffer(); - rval.putByte(1); - return rval; - }; - tls.createFinished = function(c) { - var b = forge.util.createBuffer(); - b.putBuffer(c.session.md5.digest()); - b.putBuffer(c.session.sha1.digest()); - var client = c.entity === tls.ConnectionEnd.client; - var sp = c.session.sp; - var vdl = 12; - var prf = prf_TLS1; - var label = client ? "client finished" : "server finished"; - b = prf(sp.master_secret, label, b.getBytes(), vdl); - var rval = forge.util.createBuffer(); - rval.putByte(tls.HandshakeType.finished); - rval.putInt24(b.length()); - rval.putBuffer(b); - return rval; - }; - tls.createHeartbeat = function(type, payload, payloadLength) { - if (typeof payloadLength === "undefined") { - payloadLength = payload.length; - } - var rval = forge.util.createBuffer(); - rval.putByte(type); - rval.putInt16(payloadLength); - rval.putBytes(payload); - var plaintextLength = rval.length(); - var paddingLength = Math.max(16, plaintextLength - payloadLength - 3); - rval.putBytes(forge.random.getBytes(paddingLength)); - return rval; - }; - tls.queue = function(c, record) { - if (!record) { - return; - } - if (record.fragment.length() === 0) { - if (record.type === tls.ContentType.handshake || record.type === tls.ContentType.alert || record.type === tls.ContentType.change_cipher_spec) { - return; - } - } - if (record.type === tls.ContentType.handshake) { - var bytes = record.fragment.bytes(); - c.session.md5.update(bytes); - c.session.sha1.update(bytes); - bytes = null; - } - var records; - if (record.fragment.length() <= tls.MaxFragment) { - records = [record]; - } else { - records = []; - var data = record.fragment.bytes(); - while (data.length > tls.MaxFragment) { - records.push(tls.createRecord(c, { - type: record.type, - data: forge.util.createBuffer(data.slice(0, tls.MaxFragment)) - })); - data = data.slice(tls.MaxFragment); - } - if (data.length > 0) { - records.push(tls.createRecord(c, { - type: record.type, - data: forge.util.createBuffer(data) - })); - } - } - for (var i = 0; i < records.length && !c.fail; ++i) { - var rec = records[i]; - var s = c.state.current.write; - if (s.update(c, rec)) { - c.records.push(rec); - } - } - }; - tls.flush = function(c) { - for (var i = 0; i < c.records.length; ++i) { - var record = c.records[i]; - c.tlsData.putByte(record.type); - c.tlsData.putByte(record.version.major); - c.tlsData.putByte(record.version.minor); - c.tlsData.putInt16(record.fragment.length()); - c.tlsData.putBuffer(c.records[i].fragment); - } - c.records = []; - return c.tlsDataReady(c); - }; - var _certErrorToAlertDesc = function(error3) { - switch (error3) { - case true: - return true; - case forge.pki.certificateError.bad_certificate: - return tls.Alert.Description.bad_certificate; - case forge.pki.certificateError.unsupported_certificate: - return tls.Alert.Description.unsupported_certificate; - case forge.pki.certificateError.certificate_revoked: - return tls.Alert.Description.certificate_revoked; - case forge.pki.certificateError.certificate_expired: - return tls.Alert.Description.certificate_expired; - case forge.pki.certificateError.certificate_unknown: - return tls.Alert.Description.certificate_unknown; - case forge.pki.certificateError.unknown_ca: - return tls.Alert.Description.unknown_ca; - default: - return tls.Alert.Description.bad_certificate; - } - }; - var _alertDescToCertError = function(desc) { - switch (desc) { - case true: - return true; - case tls.Alert.Description.bad_certificate: - return forge.pki.certificateError.bad_certificate; - case tls.Alert.Description.unsupported_certificate: - return forge.pki.certificateError.unsupported_certificate; - case tls.Alert.Description.certificate_revoked: - return forge.pki.certificateError.certificate_revoked; - case tls.Alert.Description.certificate_expired: - return forge.pki.certificateError.certificate_expired; - case tls.Alert.Description.certificate_unknown: - return forge.pki.certificateError.certificate_unknown; - case tls.Alert.Description.unknown_ca: - return forge.pki.certificateError.unknown_ca; - default: - return forge.pki.certificateError.bad_certificate; - } - }; - tls.verifyCertificateChain = function(c, chain) { - try { - var options = {}; - for (var key2 in c.verifyOptions) { - options[key2] = c.verifyOptions[key2]; - } - options.verify = function(vfd, depth, chain2) { - var desc = _certErrorToAlertDesc(vfd); - var ret = c.verify(c, vfd, depth, chain2); - if (ret !== true) { - if (typeof ret === "object" && !forge.util.isArray(ret)) { - var error3 = new Error("The application rejected the certificate."); - error3.send = true; - error3.alert = { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.bad_certificate - }; - if (ret.message) { - error3.message = ret.message; - } - if (ret.alert) { - error3.alert.description = ret.alert; - } - throw error3; - } - if (ret !== vfd) { - ret = _alertDescToCertError(ret); - } - } - return ret; - }; - forge.pki.verifyCertificateChain(c.caStore, chain, options); - } catch (ex) { - var err = ex; - if (typeof err !== "object" || forge.util.isArray(err)) { - err = { - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: _certErrorToAlertDesc(ex) - } - }; - } - if (!("send" in err)) { - err.send = true; - } - if (!("alert" in err)) { - err.alert = { - level: tls.Alert.Level.fatal, - description: _certErrorToAlertDesc(err.error) - }; - } - c.error(c, err); - } - return !c.fail; - }; - tls.createSessionCache = function(cache, capacity) { - var rval = null; - if (cache && cache.getSession && cache.setSession && cache.order) { - rval = cache; - } else { - rval = {}; - rval.cache = cache || {}; - rval.capacity = Math.max(capacity || 100, 1); - rval.order = []; - for (var key2 in cache) { - if (rval.order.length <= capacity) { - rval.order.push(key2); - } else { - delete cache[key2]; - } - } - rval.getSession = function(sessionId) { - var session = null; - var key3 = null; - if (sessionId) { - key3 = forge.util.bytesToHex(sessionId); - } else if (rval.order.length > 0) { - key3 = rval.order[0]; - } - if (key3 !== null && key3 in rval.cache) { - session = rval.cache[key3]; - delete rval.cache[key3]; - for (var i in rval.order) { - if (rval.order[i] === key3) { - rval.order.splice(i, 1); - break; - } - } - } - return session; - }; - rval.setSession = function(sessionId, session) { - if (rval.order.length === rval.capacity) { - var key3 = rval.order.shift(); - delete rval.cache[key3]; - } - var key3 = forge.util.bytesToHex(sessionId); - rval.order.push(key3); - rval.cache[key3] = session; - }; - } - return rval; - }; - tls.createConnection = function(options) { - var caStore = null; - if (options.caStore) { - if (forge.util.isArray(options.caStore)) { - caStore = forge.pki.createCaStore(options.caStore); - } else { - caStore = options.caStore; - } - } else { - caStore = forge.pki.createCaStore(); - } - var cipherSuites = options.cipherSuites || null; - if (cipherSuites === null) { - cipherSuites = []; - for (var key2 in tls.CipherSuites) { - cipherSuites.push(tls.CipherSuites[key2]); - } - } - var entity = options.server || false ? tls.ConnectionEnd.server : tls.ConnectionEnd.client; - var sessionCache = options.sessionCache ? tls.createSessionCache(options.sessionCache) : null; - var c = { - version: { major: tls.Version.major, minor: tls.Version.minor }, - entity, - sessionId: options.sessionId, - caStore, - sessionCache, - cipherSuites, - connected: options.connected, - virtualHost: options.virtualHost || null, - verifyClient: options.verifyClient || false, - verify: options.verify || function(cn, vfd, dpth, cts) { - return vfd; - }, - verifyOptions: options.verifyOptions || {}, - getCertificate: options.getCertificate || null, - getPrivateKey: options.getPrivateKey || null, - getSignature: options.getSignature || null, - input: forge.util.createBuffer(), - tlsData: forge.util.createBuffer(), - data: forge.util.createBuffer(), - tlsDataReady: options.tlsDataReady, - dataReady: options.dataReady, - heartbeatReceived: options.heartbeatReceived, - closed: options.closed, - error: function(c2, ex) { - ex.origin = ex.origin || (c2.entity === tls.ConnectionEnd.client ? "client" : "server"); - if (ex.send) { - tls.queue(c2, tls.createAlert(c2, ex.alert)); - tls.flush(c2); - } - var fatal = ex.fatal !== false; - if (fatal) { - c2.fail = true; - } - options.error(c2, ex); - if (fatal) { - c2.close(false); - } - }, - deflate: options.deflate || null, - inflate: options.inflate || null - }; - c.reset = function(clearFail) { - c.version = { major: tls.Version.major, minor: tls.Version.minor }; - c.record = null; - c.session = null; - c.peerCertificate = null; - c.state = { - pending: null, - current: null - }; - c.expect = c.entity === tls.ConnectionEnd.client ? SHE : CHE; - c.fragmented = null; - c.records = []; - c.open = false; - c.handshakes = 0; - c.handshaking = false; - c.isConnected = false; - c.fail = !(clearFail || typeof clearFail === "undefined"); - c.input.clear(); - c.tlsData.clear(); - c.data.clear(); - c.state.current = tls.createConnectionState(c); - }; - c.reset(); - var _update = function(c2, record) { - var aligned = record.type - tls.ContentType.change_cipher_spec; - var handlers = ctTable[c2.entity][c2.expect]; - if (aligned in handlers) { - handlers[aligned](c2, record); - } else { - tls.handleUnexpected(c2, record); - } - }; - var _readRecordHeader = function(c2) { - var rval = 0; - var b = c2.input; - var len = b.length(); - if (len < 5) { - rval = 5 - len; - } else { - c2.record = { - type: b.getByte(), - version: { - major: b.getByte(), - minor: b.getByte() - }, - length: b.getInt16(), - fragment: forge.util.createBuffer(), - ready: false - }; - var compatibleVersion = c2.record.version.major === c2.version.major; - if (compatibleVersion && c2.session && c2.session.version) { - compatibleVersion = c2.record.version.minor === c2.version.minor; - } - if (!compatibleVersion) { - c2.error(c2, { - message: "Incompatible TLS version.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.protocol_version - } - }); - } - } - return rval; - }; - var _readRecord = function(c2) { - var rval = 0; - var b = c2.input; - var len = b.length(); - if (len < c2.record.length) { - rval = c2.record.length - len; - } else { - c2.record.fragment.putBytes(b.getBytes(c2.record.length)); - b.compact(); - var s = c2.state.current.read; - if (s.update(c2, c2.record)) { - if (c2.fragmented !== null) { - if (c2.fragmented.type === c2.record.type) { - c2.fragmented.fragment.putBuffer(c2.record.fragment); - c2.record = c2.fragmented; - } else { - c2.error(c2, { - message: "Invalid fragmented record.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.unexpected_message - } - }); - } - } - c2.record.ready = true; - } - } - return rval; - }; - c.handshake = function(sessionId) { - if (c.entity !== tls.ConnectionEnd.client) { - c.error(c, { - message: "Cannot initiate handshake as a server.", - fatal: false - }); - } else if (c.handshaking) { - c.error(c, { - message: "Handshake already in progress.", - fatal: false - }); - } else { - if (c.fail && !c.open && c.handshakes === 0) { - c.fail = false; - } - c.handshaking = true; - sessionId = sessionId || ""; - var session = null; - if (sessionId.length > 0) { - if (c.sessionCache) { - session = c.sessionCache.getSession(sessionId); - } - if (session === null) { - sessionId = ""; - } - } - if (sessionId.length === 0 && c.sessionCache) { - session = c.sessionCache.getSession(); - if (session !== null) { - sessionId = session.id; - } - } - c.session = { - id: sessionId, - version: null, - cipherSuite: null, - compressionMethod: null, - serverCertificate: null, - certificateRequest: null, - clientCertificate: null, - sp: {}, - md5: forge.md.md5.create(), - sha1: forge.md.sha1.create() - }; - if (session) { - c.version = session.version; - c.session.sp = session.sp; - } - c.session.sp.client_random = tls.createRandom().getBytes(); - c.open = true; - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createClientHello(c) - })); - tls.flush(c); - } - }; - c.process = function(data) { - var rval = 0; - if (data) { - c.input.putBytes(data); - } - if (!c.fail) { - if (c.record !== null && c.record.ready && c.record.fragment.isEmpty()) { - c.record = null; - } - if (c.record === null) { - rval = _readRecordHeader(c); - } - if (!c.fail && c.record !== null && !c.record.ready) { - rval = _readRecord(c); - } - if (!c.fail && c.record !== null && c.record.ready) { - _update(c, c.record); - } - } - return rval; - }; - c.prepare = function(data) { - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.application_data, - data: forge.util.createBuffer(data) - })); - return tls.flush(c); - }; - c.prepareHeartbeatRequest = function(payload, payloadLength) { - if (payload instanceof forge.util.ByteBuffer) { - payload = payload.bytes(); - } - if (typeof payloadLength === "undefined") { - payloadLength = payload.length; - } - c.expectedHeartbeatPayload = payload; - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.heartbeat, - data: tls.createHeartbeat( - tls.HeartbeatMessageType.heartbeat_request, - payload, - payloadLength - ) - })); - return tls.flush(c); - }; - c.close = function(clearFail) { - if (!c.fail && c.sessionCache && c.session) { - var session = { - id: c.session.id, - version: c.session.version, - sp: c.session.sp - }; - session.sp.keys = null; - c.sessionCache.setSession(session.id, session); - } - if (c.open) { - c.open = false; - c.input.clear(); - if (c.isConnected || c.handshaking) { - c.isConnected = c.handshaking = false; - tls.queue(c, tls.createAlert(c, { - level: tls.Alert.Level.warning, - description: tls.Alert.Description.close_notify - })); - tls.flush(c); - } - c.closed(c); - } - c.reset(clearFail); - }; - return c; - }; - module2.exports = forge.tls = forge.tls || {}; - for (key in tls) { - if (typeof tls[key] !== "function") { - forge.tls[key] = tls[key]; - } - } - var key; - forge.tls.prf_tls1 = prf_TLS1; - forge.tls.hmac_sha1 = hmac_sha1; - forge.tls.createSessionCache = tls.createSessionCache; - forge.tls.createConnection = tls.createConnection; - } -}); - -// node_modules/node-forge/lib/aesCipherSuites.js -var require_aesCipherSuites = __commonJS({ - "node_modules/node-forge/lib/aesCipherSuites.js"(exports2, module2) { - var forge = require_forge(); - require_aes(); - require_tls(); - var tls = module2.exports = forge.tls; - tls.CipherSuites["TLS_RSA_WITH_AES_128_CBC_SHA"] = { - id: [0, 47], - name: "TLS_RSA_WITH_AES_128_CBC_SHA", - initSecurityParameters: function(sp) { - sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes; - sp.cipher_type = tls.CipherType.block; - sp.enc_key_length = 16; - sp.block_length = 16; - sp.fixed_iv_length = 16; - sp.record_iv_length = 16; - sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1; - sp.mac_length = 20; - sp.mac_key_length = 20; - }, - initConnectionState - }; - tls.CipherSuites["TLS_RSA_WITH_AES_256_CBC_SHA"] = { - id: [0, 53], - name: "TLS_RSA_WITH_AES_256_CBC_SHA", - initSecurityParameters: function(sp) { - sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes; - sp.cipher_type = tls.CipherType.block; - sp.enc_key_length = 32; - sp.block_length = 16; - sp.fixed_iv_length = 16; - sp.record_iv_length = 16; - sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1; - sp.mac_length = 20; - sp.mac_key_length = 20; - }, - initConnectionState - }; - function initConnectionState(state, c, sp) { - var client = c.entity === forge.tls.ConnectionEnd.client; - state.read.cipherState = { - init: false, - cipher: forge.cipher.createDecipher("AES-CBC", client ? sp.keys.server_write_key : sp.keys.client_write_key), - iv: client ? sp.keys.server_write_IV : sp.keys.client_write_IV - }; - state.write.cipherState = { - init: false, - cipher: forge.cipher.createCipher("AES-CBC", client ? sp.keys.client_write_key : sp.keys.server_write_key), - iv: client ? sp.keys.client_write_IV : sp.keys.server_write_IV - }; - state.read.cipherFunction = decrypt_aes_cbc_sha1; - state.write.cipherFunction = encrypt_aes_cbc_sha1; - state.read.macLength = state.write.macLength = sp.mac_length; - state.read.macFunction = state.write.macFunction = tls.hmac_sha1; - } - function encrypt_aes_cbc_sha1(record, s) { - var rval = false; - var mac = s.macFunction(s.macKey, s.sequenceNumber, record); - record.fragment.putBytes(mac); - s.updateSequenceNumber(); - var iv; - if (record.version.minor === tls.Versions.TLS_1_0.minor) { - iv = s.cipherState.init ? null : s.cipherState.iv; - } else { - iv = forge.random.getBytesSync(16); - } - s.cipherState.init = true; - var cipher = s.cipherState.cipher; - cipher.start({ iv }); - if (record.version.minor >= tls.Versions.TLS_1_1.minor) { - cipher.output.putBytes(iv); - } - cipher.update(record.fragment); - if (cipher.finish(encrypt_aes_cbc_sha1_padding)) { - record.fragment = cipher.output; - record.length = record.fragment.length(); - rval = true; - } - return rval; - } - function encrypt_aes_cbc_sha1_padding(blockSize, input, decrypt) { - if (!decrypt) { - var padding = blockSize - input.length() % blockSize; - input.fillWithByte(padding - 1, padding); - } - return true; - } - function decrypt_aes_cbc_sha1_padding(blockSize, output, decrypt) { - var rval = true; - if (decrypt) { - var len = output.length(); - var paddingLength = output.last(); - for (var i = len - 1 - paddingLength; i < len - 1; ++i) { - rval = rval && output.at(i) == paddingLength; - } - if (rval) { - output.truncate(paddingLength + 1); - } - } - return rval; - } - function decrypt_aes_cbc_sha1(record, s) { - var rval = false; - var iv; - if (record.version.minor === tls.Versions.TLS_1_0.minor) { - iv = s.cipherState.init ? null : s.cipherState.iv; - } else { - iv = record.fragment.getBytes(16); - } - s.cipherState.init = true; - var cipher = s.cipherState.cipher; - cipher.start({ iv }); - cipher.update(record.fragment); - rval = cipher.finish(decrypt_aes_cbc_sha1_padding); - var macLen = s.macLength; - var mac = forge.random.getBytesSync(macLen); - var len = cipher.output.length(); - if (len >= macLen) { - record.fragment = cipher.output.getBytes(len - macLen); - mac = cipher.output.getBytes(macLen); - } else { - record.fragment = cipher.output.getBytes(); - } - record.fragment = forge.util.createBuffer(record.fragment); - record.length = record.fragment.length(); - var mac2 = s.macFunction(s.macKey, s.sequenceNumber, record); - s.updateSequenceNumber(); - rval = compareMacs(s.macKey, mac, mac2) && rval; - return rval; - } - function compareMacs(key, mac1, mac2) { - var hmac = forge.hmac.create(); - hmac.start("SHA1", key); - hmac.update(mac1); - mac1 = hmac.digest().getBytes(); - hmac.start(null, null); - hmac.update(mac2); - mac2 = hmac.digest().getBytes(); - return mac1 === mac2; - } - } -}); - -// node_modules/node-forge/lib/sha512.js -var require_sha512 = __commonJS({ - "node_modules/node-forge/lib/sha512.js"(exports2, module2) { - var forge = require_forge(); - require_md(); - require_util13(); - var sha512 = module2.exports = forge.sha512 = forge.sha512 || {}; - forge.md.sha512 = forge.md.algorithms.sha512 = sha512; - var sha384 = forge.sha384 = forge.sha512.sha384 = forge.sha512.sha384 || {}; - sha384.create = function() { - return sha512.create("SHA-384"); - }; - forge.md.sha384 = forge.md.algorithms.sha384 = sha384; - forge.sha512.sha256 = forge.sha512.sha256 || { - create: function() { - return sha512.create("SHA-512/256"); - } - }; - forge.md["sha512/256"] = forge.md.algorithms["sha512/256"] = forge.sha512.sha256; - forge.sha512.sha224 = forge.sha512.sha224 || { - create: function() { - return sha512.create("SHA-512/224"); - } - }; - forge.md["sha512/224"] = forge.md.algorithms["sha512/224"] = forge.sha512.sha224; - sha512.create = function(algorithm) { - if (!_initialized) { - _init(); - } - if (typeof algorithm === "undefined") { - algorithm = "SHA-512"; - } - if (!(algorithm in _states)) { - throw new Error("Invalid SHA-512 algorithm: " + algorithm); - } - var _state = _states[algorithm]; - var _h = null; - var _input = forge.util.createBuffer(); - var _w = new Array(80); - for (var wi = 0; wi < 80; ++wi) { - _w[wi] = new Array(2); - } - var digestLength = 64; - switch (algorithm) { - case "SHA-384": - digestLength = 48; - break; - case "SHA-512/256": - digestLength = 32; - break; - case "SHA-512/224": - digestLength = 28; - break; - } - var md2 = { - // SHA-512 => sha512 - algorithm: algorithm.replace("-", "").toLowerCase(), - blockLength: 128, - digestLength, - // 56-bit length of message so far (does not including padding) - messageLength: 0, - // true message length - fullMessageLength: null, - // size of message length in bytes - messageLengthSize: 16 - }; - md2.start = function() { - md2.messageLength = 0; - md2.fullMessageLength = md2.messageLength128 = []; - var int32s = md2.messageLengthSize / 4; - for (var i = 0; i < int32s; ++i) { - md2.fullMessageLength.push(0); - } - _input = forge.util.createBuffer(); - _h = new Array(_state.length); - for (var i = 0; i < _state.length; ++i) { - _h[i] = _state[i].slice(0); - } - return md2; - }; - md2.start(); - md2.update = function(msg, encoding) { - if (encoding === "utf8") { - msg = forge.util.encodeUtf8(msg); - } - var len = msg.length; - md2.messageLength += len; - len = [len / 4294967296 >>> 0, len >>> 0]; - for (var i = md2.fullMessageLength.length - 1; i >= 0; --i) { - md2.fullMessageLength[i] += len[1]; - len[1] = len[0] + (md2.fullMessageLength[i] / 4294967296 >>> 0); - md2.fullMessageLength[i] = md2.fullMessageLength[i] >>> 0; - len[0] = len[1] / 4294967296 >>> 0; - } - _input.putBytes(msg); - _update(_h, _w, _input); - if (_input.read > 2048 || _input.length() === 0) { - _input.compact(); - } - return md2; - }; - md2.digest = function() { - var finalBlock = forge.util.createBuffer(); - finalBlock.putBytes(_input.bytes()); - var remaining = md2.fullMessageLength[md2.fullMessageLength.length - 1] + md2.messageLengthSize; - var overflow = remaining & md2.blockLength - 1; - finalBlock.putBytes(_padding.substr(0, md2.blockLength - overflow)); - var next, carry; - var bits = md2.fullMessageLength[0] * 8; - for (var i = 0; i < md2.fullMessageLength.length - 1; ++i) { - next = md2.fullMessageLength[i + 1] * 8; - carry = next / 4294967296 >>> 0; - bits += carry; - finalBlock.putInt32(bits >>> 0); - bits = next >>> 0; - } - finalBlock.putInt32(bits); - var h = new Array(_h.length); - for (var i = 0; i < _h.length; ++i) { - h[i] = _h[i].slice(0); - } - _update(h, _w, finalBlock); - var rval = forge.util.createBuffer(); - var hlen; - if (algorithm === "SHA-512") { - hlen = h.length; - } else if (algorithm === "SHA-384") { - hlen = h.length - 2; - } else { - hlen = h.length - 4; - } - for (var i = 0; i < hlen; ++i) { - rval.putInt32(h[i][0]); - if (i !== hlen - 1 || algorithm !== "SHA-512/224") { - rval.putInt32(h[i][1]); - } - } - return rval; - }; - return md2; - }; - var _padding = null; - var _initialized = false; - var _k = null; - var _states = null; - function _init() { - _padding = String.fromCharCode(128); - _padding += forge.util.fillString(String.fromCharCode(0), 128); - _k = [ - [1116352408, 3609767458], - [1899447441, 602891725], - [3049323471, 3964484399], - [3921009573, 2173295548], - [961987163, 4081628472], - [1508970993, 3053834265], - [2453635748, 2937671579], - [2870763221, 3664609560], - [3624381080, 2734883394], - [310598401, 1164996542], - [607225278, 1323610764], - [1426881987, 3590304994], - [1925078388, 4068182383], - [2162078206, 991336113], - [2614888103, 633803317], - [3248222580, 3479774868], - [3835390401, 2666613458], - [4022224774, 944711139], - [264347078, 2341262773], - [604807628, 2007800933], - [770255983, 1495990901], - [1249150122, 1856431235], - [1555081692, 3175218132], - [1996064986, 2198950837], - [2554220882, 3999719339], - [2821834349, 766784016], - [2952996808, 2566594879], - [3210313671, 3203337956], - [3336571891, 1034457026], - [3584528711, 2466948901], - [113926993, 3758326383], - [338241895, 168717936], - [666307205, 1188179964], - [773529912, 1546045734], - [1294757372, 1522805485], - [1396182291, 2643833823], - [1695183700, 2343527390], - [1986661051, 1014477480], - [2177026350, 1206759142], - [2456956037, 344077627], - [2730485921, 1290863460], - [2820302411, 3158454273], - [3259730800, 3505952657], - [3345764771, 106217008], - [3516065817, 3606008344], - [3600352804, 1432725776], - [4094571909, 1467031594], - [275423344, 851169720], - [430227734, 3100823752], - [506948616, 1363258195], - [659060556, 3750685593], - [883997877, 3785050280], - [958139571, 3318307427], - [1322822218, 3812723403], - [1537002063, 2003034995], - [1747873779, 3602036899], - [1955562222, 1575990012], - [2024104815, 1125592928], - [2227730452, 2716904306], - [2361852424, 442776044], - [2428436474, 593698344], - [2756734187, 3733110249], - [3204031479, 2999351573], - [3329325298, 3815920427], - [3391569614, 3928383900], - [3515267271, 566280711], - [3940187606, 3454069534], - [4118630271, 4000239992], - [116418474, 1914138554], - [174292421, 2731055270], - [289380356, 3203993006], - [460393269, 320620315], - [685471733, 587496836], - [852142971, 1086792851], - [1017036298, 365543100], - [1126000580, 2618297676], - [1288033470, 3409855158], - [1501505948, 4234509866], - [1607167915, 987167468], - [1816402316, 1246189591] - ]; - _states = {}; - _states["SHA-512"] = [ - [1779033703, 4089235720], - [3144134277, 2227873595], - [1013904242, 4271175723], - [2773480762, 1595750129], - [1359893119, 2917565137], - [2600822924, 725511199], - [528734635, 4215389547], - [1541459225, 327033209] - ]; - _states["SHA-384"] = [ - [3418070365, 3238371032], - [1654270250, 914150663], - [2438529370, 812702999], - [355462360, 4144912697], - [1731405415, 4290775857], - [2394180231, 1750603025], - [3675008525, 1694076839], - [1203062813, 3204075428] - ]; - _states["SHA-512/256"] = [ - [573645204, 4230739756], - [2673172387, 3360449730], - [596883563, 1867755857], - [2520282905, 1497426621], - [2519219938, 2827943907], - [3193839141, 1401305490], - [721525244, 746961066], - [246885852, 2177182882] - ]; - _states["SHA-512/224"] = [ - [2352822216, 424955298], - [1944164710, 2312950998], - [502970286, 855612546], - [1738396948, 1479516111], - [258812777, 2077511080], - [2011393907, 79989058], - [1067287976, 1780299464], - [286451373, 2446758561] - ]; - _initialized = true; - } - function _update(s, w, bytes) { - var t1_hi, t1_lo; - var t2_hi, t2_lo; - var s0_hi, s0_lo; - var s1_hi, s1_lo; - var ch_hi, ch_lo; - var maj_hi, maj_lo; - var a_hi, a_lo; - var b_hi, b_lo; - var c_hi, c_lo; - var d_hi, d_lo; - var e_hi, e_lo; - var f_hi, f_lo; - var g_hi, g_lo; - var h_hi, h_lo; - var i, hi, lo, w2, w7, w15, w16; - var len = bytes.length(); - while (len >= 128) { - for (i = 0; i < 16; ++i) { - w[i][0] = bytes.getInt32() >>> 0; - w[i][1] = bytes.getInt32() >>> 0; - } - for (; i < 80; ++i) { - w2 = w[i - 2]; - hi = w2[0]; - lo = w2[1]; - t1_hi = ((hi >>> 19 | lo << 13) ^ // ROTR 19 - (lo >>> 29 | hi << 3) ^ // ROTR 61/(swap + ROTR 29) - hi >>> 6) >>> 0; - t1_lo = ((hi << 13 | lo >>> 19) ^ // ROTR 19 - (lo << 3 | hi >>> 29) ^ // ROTR 61/(swap + ROTR 29) - (hi << 26 | lo >>> 6)) >>> 0; - w15 = w[i - 15]; - hi = w15[0]; - lo = w15[1]; - t2_hi = ((hi >>> 1 | lo << 31) ^ // ROTR 1 - (hi >>> 8 | lo << 24) ^ // ROTR 8 - hi >>> 7) >>> 0; - t2_lo = ((hi << 31 | lo >>> 1) ^ // ROTR 1 - (hi << 24 | lo >>> 8) ^ // ROTR 8 - (hi << 25 | lo >>> 7)) >>> 0; - w7 = w[i - 7]; - w16 = w[i - 16]; - lo = t1_lo + w7[1] + t2_lo + w16[1]; - w[i][0] = t1_hi + w7[0] + t2_hi + w16[0] + (lo / 4294967296 >>> 0) >>> 0; - w[i][1] = lo >>> 0; - } - a_hi = s[0][0]; - a_lo = s[0][1]; - b_hi = s[1][0]; - b_lo = s[1][1]; - c_hi = s[2][0]; - c_lo = s[2][1]; - d_hi = s[3][0]; - d_lo = s[3][1]; - e_hi = s[4][0]; - e_lo = s[4][1]; - f_hi = s[5][0]; - f_lo = s[5][1]; - g_hi = s[6][0]; - g_lo = s[6][1]; - h_hi = s[7][0]; - h_lo = s[7][1]; - for (i = 0; i < 80; ++i) { - s1_hi = ((e_hi >>> 14 | e_lo << 18) ^ // ROTR 14 - (e_hi >>> 18 | e_lo << 14) ^ // ROTR 18 - (e_lo >>> 9 | e_hi << 23)) >>> 0; - s1_lo = ((e_hi << 18 | e_lo >>> 14) ^ // ROTR 14 - (e_hi << 14 | e_lo >>> 18) ^ // ROTR 18 - (e_lo << 23 | e_hi >>> 9)) >>> 0; - ch_hi = (g_hi ^ e_hi & (f_hi ^ g_hi)) >>> 0; - ch_lo = (g_lo ^ e_lo & (f_lo ^ g_lo)) >>> 0; - s0_hi = ((a_hi >>> 28 | a_lo << 4) ^ // ROTR 28 - (a_lo >>> 2 | a_hi << 30) ^ // ROTR 34/(swap + ROTR 2) - (a_lo >>> 7 | a_hi << 25)) >>> 0; - s0_lo = ((a_hi << 4 | a_lo >>> 28) ^ // ROTR 28 - (a_lo << 30 | a_hi >>> 2) ^ // ROTR 34/(swap + ROTR 2) - (a_lo << 25 | a_hi >>> 7)) >>> 0; - maj_hi = (a_hi & b_hi | c_hi & (a_hi ^ b_hi)) >>> 0; - maj_lo = (a_lo & b_lo | c_lo & (a_lo ^ b_lo)) >>> 0; - lo = h_lo + s1_lo + ch_lo + _k[i][1] + w[i][1]; - t1_hi = h_hi + s1_hi + ch_hi + _k[i][0] + w[i][0] + (lo / 4294967296 >>> 0) >>> 0; - t1_lo = lo >>> 0; - lo = s0_lo + maj_lo; - t2_hi = s0_hi + maj_hi + (lo / 4294967296 >>> 0) >>> 0; - t2_lo = lo >>> 0; - h_hi = g_hi; - h_lo = g_lo; - g_hi = f_hi; - g_lo = f_lo; - f_hi = e_hi; - f_lo = e_lo; - lo = d_lo + t1_lo; - e_hi = d_hi + t1_hi + (lo / 4294967296 >>> 0) >>> 0; - e_lo = lo >>> 0; - d_hi = c_hi; - d_lo = c_lo; - c_hi = b_hi; - c_lo = b_lo; - b_hi = a_hi; - b_lo = a_lo; - lo = t1_lo + t2_lo; - a_hi = t1_hi + t2_hi + (lo / 4294967296 >>> 0) >>> 0; - a_lo = lo >>> 0; - } - lo = s[0][1] + a_lo; - s[0][0] = s[0][0] + a_hi + (lo / 4294967296 >>> 0) >>> 0; - s[0][1] = lo >>> 0; - lo = s[1][1] + b_lo; - s[1][0] = s[1][0] + b_hi + (lo / 4294967296 >>> 0) >>> 0; - s[1][1] = lo >>> 0; - lo = s[2][1] + c_lo; - s[2][0] = s[2][0] + c_hi + (lo / 4294967296 >>> 0) >>> 0; - s[2][1] = lo >>> 0; - lo = s[3][1] + d_lo; - s[3][0] = s[3][0] + d_hi + (lo / 4294967296 >>> 0) >>> 0; - s[3][1] = lo >>> 0; - lo = s[4][1] + e_lo; - s[4][0] = s[4][0] + e_hi + (lo / 4294967296 >>> 0) >>> 0; - s[4][1] = lo >>> 0; - lo = s[5][1] + f_lo; - s[5][0] = s[5][0] + f_hi + (lo / 4294967296 >>> 0) >>> 0; - s[5][1] = lo >>> 0; - lo = s[6][1] + g_lo; - s[6][0] = s[6][0] + g_hi + (lo / 4294967296 >>> 0) >>> 0; - s[6][1] = lo >>> 0; - lo = s[7][1] + h_lo; - s[7][0] = s[7][0] + h_hi + (lo / 4294967296 >>> 0) >>> 0; - s[7][1] = lo >>> 0; - len -= 128; - } - } - } -}); - -// node_modules/node-forge/lib/asn1-validator.js -var require_asn1_validator = __commonJS({ - "node_modules/node-forge/lib/asn1-validator.js"(exports2) { - var forge = require_forge(); - require_asn1(); - var asn1 = forge.asn1; - exports2.privateKeyValidator = { - // PrivateKeyInfo - name: "PrivateKeyInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - // Version (INTEGER) - name: "PrivateKeyInfo.version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyVersion" - }, { - // privateKeyAlgorithm - name: "PrivateKeyInfo.privateKeyAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "AlgorithmIdentifier.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "privateKeyOid" - }] - }, { - // PrivateKey - name: "PrivateKeyInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "privateKey" - }] - }; - exports2.publicKeyValidator = { - name: "SubjectPublicKeyInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "subjectPublicKeyInfo", - value: [ - { - name: "SubjectPublicKeyInfo.AlgorithmIdentifier", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "AlgorithmIdentifier.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "publicKeyOid" - }] - }, - // capture group for ed25519PublicKey - { - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - composed: true, - captureBitStringValue: "ed25519PublicKey" - } - // FIXME: this is capture group for rsaPublicKey, use it in this API or - // discard? - /* { - // subjectPublicKey - name: 'SubjectPublicKeyInfo.subjectPublicKey', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - value: [{ - // RSAPublicKey - name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - optional: true, - captureAsn1: 'rsaPublicKey' - }] - } */ - ] - }; - } -}); - -// node_modules/node-forge/lib/ed25519.js -var require_ed25519 = __commonJS({ - "node_modules/node-forge/lib/ed25519.js"(exports2, module2) { - var forge = require_forge(); - require_jsbn(); - require_random(); - require_sha512(); - require_util13(); - var asn1Validator = require_asn1_validator(); - var publicKeyValidator = asn1Validator.publicKeyValidator; - var privateKeyValidator = asn1Validator.privateKeyValidator; - if (typeof BigInteger === "undefined") { - BigInteger = forge.jsbn.BigInteger; - } - var BigInteger; - var ByteBuffer = forge.util.ByteBuffer; - var NativeBuffer = typeof Buffer === "undefined" ? Uint8Array : Buffer; - forge.pki = forge.pki || {}; - module2.exports = forge.pki.ed25519 = forge.ed25519 = forge.ed25519 || {}; - var ed25519 = forge.ed25519; - ed25519.constants = {}; - ed25519.constants.PUBLIC_KEY_BYTE_LENGTH = 32; - ed25519.constants.PRIVATE_KEY_BYTE_LENGTH = 64; - ed25519.constants.SEED_BYTE_LENGTH = 32; - ed25519.constants.SIGN_BYTE_LENGTH = 64; - ed25519.constants.HASH_BYTE_LENGTH = 64; - ed25519.generateKeyPair = function(options) { - options = options || {}; - var seed = options.seed; - if (seed === void 0) { - seed = forge.random.getBytesSync(ed25519.constants.SEED_BYTE_LENGTH); - } else if (typeof seed === "string") { - if (seed.length !== ed25519.constants.SEED_BYTE_LENGTH) { - throw new TypeError( - '"seed" must be ' + ed25519.constants.SEED_BYTE_LENGTH + " bytes in length." - ); - } - } else if (!(seed instanceof Uint8Array)) { - throw new TypeError( - '"seed" must be a node.js Buffer, Uint8Array, or a binary string.' - ); - } - seed = messageToNativeBuffer({ message: seed, encoding: "binary" }); - var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); - var sk = new NativeBuffer(ed25519.constants.PRIVATE_KEY_BYTE_LENGTH); - for (var i = 0; i < 32; ++i) { - sk[i] = seed[i]; - } - crypto_sign_keypair(pk, sk); - return { publicKey: pk, privateKey: sk }; - }; - ed25519.privateKeyFromAsn1 = function(obj) { - var capture = {}; - var errors = []; - var valid = forge.asn1.validate(obj, privateKeyValidator, capture, errors); - if (!valid) { - var error3 = new Error("Invalid Key."); - error3.errors = errors; - throw error3; - } - var oid = forge.asn1.derToOid(capture.privateKeyOid); - var ed25519Oid = forge.oids.EdDSA25519; - if (oid !== ed25519Oid) { - throw new Error('Invalid OID "' + oid + '"; OID must be "' + ed25519Oid + '".'); - } - var privateKey = capture.privateKey; - var privateKeyBytes = messageToNativeBuffer({ - message: forge.asn1.fromDer(privateKey).value, - encoding: "binary" - }); - return { privateKeyBytes }; - }; - ed25519.publicKeyFromAsn1 = function(obj) { - var capture = {}; - var errors = []; - var valid = forge.asn1.validate(obj, publicKeyValidator, capture, errors); - if (!valid) { - var error3 = new Error("Invalid Key."); - error3.errors = errors; - throw error3; - } - var oid = forge.asn1.derToOid(capture.publicKeyOid); - var ed25519Oid = forge.oids.EdDSA25519; - if (oid !== ed25519Oid) { - throw new Error('Invalid OID "' + oid + '"; OID must be "' + ed25519Oid + '".'); - } - var publicKeyBytes = capture.ed25519PublicKey; - if (publicKeyBytes.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) { - throw new Error("Key length is invalid."); - } - return messageToNativeBuffer({ - message: publicKeyBytes, - encoding: "binary" - }); - }; - ed25519.publicKeyFromPrivateKey = function(options) { - options = options || {}; - var privateKey = messageToNativeBuffer({ - message: options.privateKey, - encoding: "binary" - }); - if (privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) { - throw new TypeError( - '"options.privateKey" must have a byte length of ' + ed25519.constants.PRIVATE_KEY_BYTE_LENGTH - ); - } - var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); - for (var i = 0; i < pk.length; ++i) { - pk[i] = privateKey[32 + i]; - } - return pk; - }; - ed25519.sign = function(options) { - options = options || {}; - var msg = messageToNativeBuffer(options); - var privateKey = messageToNativeBuffer({ - message: options.privateKey, - encoding: "binary" - }); - if (privateKey.length === ed25519.constants.SEED_BYTE_LENGTH) { - var keyPair = ed25519.generateKeyPair({ seed: privateKey }); - privateKey = keyPair.privateKey; - } else if (privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) { - throw new TypeError( - '"options.privateKey" must have a byte length of ' + ed25519.constants.SEED_BYTE_LENGTH + " or " + ed25519.constants.PRIVATE_KEY_BYTE_LENGTH - ); - } - var signedMsg = new NativeBuffer( - ed25519.constants.SIGN_BYTE_LENGTH + msg.length - ); - crypto_sign(signedMsg, msg, msg.length, privateKey); - var sig = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH); - for (var i = 0; i < sig.length; ++i) { - sig[i] = signedMsg[i]; - } - return sig; - }; - ed25519.verify = function(options) { - options = options || {}; - var msg = messageToNativeBuffer(options); - if (options.signature === void 0) { - throw new TypeError( - '"options.signature" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a binary string.' - ); - } - var sig = messageToNativeBuffer({ - message: options.signature, - encoding: "binary" - }); - if (sig.length !== ed25519.constants.SIGN_BYTE_LENGTH) { - throw new TypeError( - '"options.signature" must have a byte length of ' + ed25519.constants.SIGN_BYTE_LENGTH - ); - } - var publicKey = messageToNativeBuffer({ - message: options.publicKey, - encoding: "binary" - }); - if (publicKey.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) { - throw new TypeError( - '"options.publicKey" must have a byte length of ' + ed25519.constants.PUBLIC_KEY_BYTE_LENGTH - ); - } - var sm = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length); - var m = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length); - var i; - for (i = 0; i < ed25519.constants.SIGN_BYTE_LENGTH; ++i) { - sm[i] = sig[i]; - } - for (i = 0; i < msg.length; ++i) { - sm[i + ed25519.constants.SIGN_BYTE_LENGTH] = msg[i]; - } - return crypto_sign_open(m, sm, sm.length, publicKey) >= 0; - }; - function messageToNativeBuffer(options) { - var message = options.message; - if (message instanceof Uint8Array || message instanceof NativeBuffer) { - return message; - } - var encoding = options.encoding; - if (message === void 0) { - if (options.md) { - message = options.md.digest().getBytes(); - encoding = "binary"; - } else { - throw new TypeError('"options.message" or "options.md" not specified.'); - } - } - if (typeof message === "string" && !encoding) { - throw new TypeError('"options.encoding" must be "binary" or "utf8".'); - } - if (typeof message === "string") { - if (typeof Buffer !== "undefined") { - return Buffer.from(message, encoding); - } - message = new ByteBuffer(message, encoding); - } else if (!(message instanceof ByteBuffer)) { - throw new TypeError( - '"options.message" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a string with "options.encoding" specifying its encoding.' - ); - } - var buffer = new NativeBuffer(message.length()); - for (var i = 0; i < buffer.length; ++i) { - buffer[i] = message.at(i); - } - return buffer; - } - var gf0 = gf(); - var gf1 = gf([1]); - var D = gf([ - 30883, - 4953, - 19914, - 30187, - 55467, - 16705, - 2637, - 112, - 59544, - 30585, - 16505, - 36039, - 65139, - 11119, - 27886, - 20995 - ]); - var D2 = gf([ - 61785, - 9906, - 39828, - 60374, - 45398, - 33411, - 5274, - 224, - 53552, - 61171, - 33010, - 6542, - 64743, - 22239, - 55772, - 9222 - ]); - var X = gf([ - 54554, - 36645, - 11616, - 51542, - 42930, - 38181, - 51040, - 26924, - 56412, - 64982, - 57905, - 49316, - 21502, - 52590, - 14035, - 8553 - ]); - var Y = gf([ - 26200, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214 - ]); - var L = new Float64Array([ - 237, - 211, - 245, - 92, - 26, - 99, - 18, - 88, - 214, - 156, - 247, - 162, - 222, - 249, - 222, - 20, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 16 - ]); - var I = gf([ - 41136, - 18958, - 6951, - 50414, - 58488, - 44335, - 6150, - 12099, - 55207, - 15867, - 153, - 11085, - 57099, - 20417, - 9344, - 11139 - ]); - function sha512(msg, msgLen) { - var md2 = forge.md.sha512.create(); - var buffer = new ByteBuffer(msg); - md2.update(buffer.getBytes(msgLen), "binary"); - var hash = md2.digest().getBytes(); - if (typeof Buffer !== "undefined") { - return Buffer.from(hash, "binary"); - } - var out = new NativeBuffer(ed25519.constants.HASH_BYTE_LENGTH); - for (var i = 0; i < 64; ++i) { - out[i] = hash.charCodeAt(i); - } - return out; - } - function crypto_sign_keypair(pk, sk) { - var p = [gf(), gf(), gf(), gf()]; - var i; - var d = sha512(sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; - scalarbase(p, d); - pack2(pk, p); - for (i = 0; i < 32; ++i) { - sk[i + 32] = pk[i]; - } - return 0; - } - function crypto_sign(sm, m, n, sk) { - var i, j, x = new Float64Array(64); - var p = [gf(), gf(), gf(), gf()]; - var d = sha512(sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; - var smlen = n + 64; - for (i = 0; i < n; ++i) { - sm[64 + i] = m[i]; - } - for (i = 0; i < 32; ++i) { - sm[32 + i] = d[32 + i]; - } - var r = sha512(sm.subarray(32), n + 32); - reduce(r); - scalarbase(p, r); - pack2(sm, p); - for (i = 32; i < 64; ++i) { - sm[i] = sk[i]; - } - var h = sha512(sm, n + 64); - reduce(h); - for (i = 32; i < 64; ++i) { - x[i] = 0; - } - for (i = 0; i < 32; ++i) { - x[i] = r[i]; - } - for (i = 0; i < 32; ++i) { - for (j = 0; j < 32; j++) { - x[i + j] += h[i] * d[j]; - } - } - modL(sm.subarray(32), x); - return smlen; - } - function crypto_sign_open(m, sm, n, pk) { - var i, mlen; - var t = new NativeBuffer(32); - var p = [gf(), gf(), gf(), gf()], q = [gf(), gf(), gf(), gf()]; - mlen = -1; - if (n < 64) { - return -1; - } - if (unpackneg(q, pk)) { - return -1; - } - if (!_isCanonicalSignatureScalar(sm, 32)) { - return -1; - } - for (i = 0; i < n; ++i) { - m[i] = sm[i]; - } - for (i = 0; i < 32; ++i) { - m[i + 32] = pk[i]; - } - var h = sha512(m, n); - reduce(h); - scalarmult(p, q, h); - scalarbase(q, sm.subarray(32)); - add(p, q); - pack2(t, p); - n -= 64; - if (crypto_verify_32(sm, 0, t, 0)) { - for (i = 0; i < n; ++i) { - m[i] = 0; - } - return -1; - } - for (i = 0; i < n; ++i) { - m[i] = sm[i + 64]; - } - mlen = n; - return mlen; - } - function _isCanonicalSignatureScalar(bytes, offset) { - var i; - for (i = 31; i >= 0; --i) { - if (bytes[offset + i] < L[i]) { - return true; - } - if (bytes[offset + i] > L[i]) { - return false; - } - } - return false; - } - function modL(r, x) { - var carry, i, j, k; - for (i = 63; i >= 32; --i) { - carry = 0; - for (j = i - 32, k = i - 12; j < k; ++j) { - x[j] += carry - 16 * x[i] * L[j - (i - 32)]; - carry = x[j] + 128 >> 8; - x[j] -= carry * 256; - } - x[j] += carry; - x[i] = 0; - } - carry = 0; - for (j = 0; j < 32; ++j) { - x[j] += carry - (x[31] >> 4) * L[j]; - carry = x[j] >> 8; - x[j] &= 255; - } - for (j = 0; j < 32; ++j) { - x[j] -= carry * L[j]; - } - for (i = 0; i < 32; ++i) { - x[i + 1] += x[i] >> 8; - r[i] = x[i] & 255; - } - } - function reduce(r) { - var x = new Float64Array(64); - for (var i = 0; i < 64; ++i) { - x[i] = r[i]; - r[i] = 0; - } - modL(r, x); - } - function add(p, q) { - var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(), g = gf(), h = gf(), t = gf(); - Z(a, p[1], p[0]); - Z(t, q[1], q[0]); - M(a, a, t); - A(b, p[0], p[1]); - A(t, q[0], q[1]); - M(b, b, t); - M(c, p[3], q[3]); - M(c, c, D2); - M(d, p[2], q[2]); - A(d, d, d); - Z(e, b, a); - Z(f, d, c); - A(g, d, c); - A(h, b, a); - M(p[0], e, f); - M(p[1], h, g); - M(p[2], g, f); - M(p[3], e, h); - } - function cswap(p, q, b) { - for (var i = 0; i < 4; ++i) { - sel25519(p[i], q[i], b); - } - } - function pack2(r, p) { - var tx = gf(), ty = gf(), zi = gf(); - inv25519(zi, p[2]); - M(tx, p[0], zi); - M(ty, p[1], zi); - pack25519(r, ty); - r[31] ^= par25519(tx) << 7; - } - function pack25519(o, n) { - var i, j, b; - var m = gf(), t = gf(); - for (i = 0; i < 16; ++i) { - t[i] = n[i]; - } - car25519(t); - car25519(t); - car25519(t); - for (j = 0; j < 2; ++j) { - m[0] = t[0] - 65517; - for (i = 1; i < 15; ++i) { - m[i] = t[i] - 65535 - (m[i - 1] >> 16 & 1); - m[i - 1] &= 65535; - } - m[15] = t[15] - 32767 - (m[14] >> 16 & 1); - b = m[15] >> 16 & 1; - m[14] &= 65535; - sel25519(t, m, 1 - b); - } - for (i = 0; i < 16; i++) { - o[2 * i] = t[i] & 255; - o[2 * i + 1] = t[i] >> 8; - } - } - function unpackneg(r, p) { - var t = gf(), chk = gf(), num = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf(); - set25519(r[2], gf1); - unpack25519(r[1], p); - S(num, r[1]); - M(den, num, D); - Z(num, num, r[2]); - A(den, r[2], den); - S(den2, den); - S(den4, den2); - M(den6, den4, den2); - M(t, den6, num); - M(t, t, den); - pow2523(t, t); - M(t, t, num); - M(t, t, den); - M(t, t, den); - M(r[0], t, den); - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) { - M(r[0], r[0], I); - } - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) { - return -1; - } - if (par25519(r[0]) === p[31] >> 7) { - Z(r[0], gf0, r[0]); - } - M(r[3], r[0], r[1]); - return 0; - } - function unpack25519(o, n) { - var i; - for (i = 0; i < 16; ++i) { - o[i] = n[2 * i] + (n[2 * i + 1] << 8); - } - o[15] &= 32767; - } - function pow2523(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; ++a) { - c[a] = i[a]; - } - for (a = 250; a >= 0; --a) { - S(c, c); - if (a !== 1) { - M(c, c, i); - } - } - for (a = 0; a < 16; ++a) { - o[a] = c[a]; - } - } - function neq25519(a, b) { - var c = new NativeBuffer(32); - var d = new NativeBuffer(32); - pack25519(c, a); - pack25519(d, b); - return crypto_verify_32(c, 0, d, 0); - } - function crypto_verify_32(x, xi, y, yi) { - return vn(x, xi, y, yi, 32); - } - function vn(x, xi, y, yi, n) { - var i, d = 0; - for (i = 0; i < n; ++i) { - d |= x[xi + i] ^ y[yi + i]; - } - return (1 & d - 1 >>> 8) - 1; - } - function par25519(a) { - var d = new NativeBuffer(32); - pack25519(d, a); - return d[0] & 1; - } - function scalarmult(p, q, s) { - var b, i; - set25519(p[0], gf0); - set25519(p[1], gf1); - set25519(p[2], gf1); - set25519(p[3], gf0); - for (i = 255; i >= 0; --i) { - b = s[i / 8 | 0] >> (i & 7) & 1; - cswap(p, q, b); - add(q, p); - add(p, p); - cswap(p, q, b); - } - } - function scalarbase(p, s) { - var q = [gf(), gf(), gf(), gf()]; - set25519(q[0], X); - set25519(q[1], Y); - set25519(q[2], gf1); - M(q[3], X, Y); - scalarmult(p, q, s); - } - function set25519(r, a) { - var i; - for (i = 0; i < 16; i++) { - r[i] = a[i] | 0; - } - } - function inv25519(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; ++a) { - c[a] = i[a]; - } - for (a = 253; a >= 0; --a) { - S(c, c); - if (a !== 2 && a !== 4) { - M(c, c, i); - } - } - for (a = 0; a < 16; ++a) { - o[a] = c[a]; - } - } - function car25519(o) { - var i, v, c = 1; - for (i = 0; i < 16; ++i) { - v = o[i] + c + 65535; - c = Math.floor(v / 65536); - o[i] = v - c * 65536; - } - o[0] += c - 1 + 37 * (c - 1); - } - function sel25519(p, q, b) { - var t, c = ~(b - 1); - for (var i = 0; i < 16; ++i) { - t = c & (p[i] ^ q[i]); - p[i] ^= t; - q[i] ^= t; - } - } - function gf(init) { - var i, r = new Float64Array(16); - if (init) { - for (i = 0; i < init.length; ++i) { - r[i] = init[i]; - } - } - return r; - } - function A(o, a, b) { - for (var i = 0; i < 16; ++i) { - o[i] = a[i] + b[i]; - } - } - function Z(o, a, b) { - for (var i = 0; i < 16; ++i) { - o[i] = a[i] - b[i]; - } - } - function S(o, a) { - M(o, a, a); - } - function M(o, a, b) { - var v, c, t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3], b4 = b[4], b5 = b[5], b6 = b[6], b7 = b[7], b8 = b[8], b9 = b[9], b10 = b[10], b11 = b[11], b12 = b[12], b13 = b[13], b14 = b[14], b15 = b[15]; - v = a[0]; - t0 += v * b0; - t1 += v * b1; - t2 += v * b2; - t3 += v * b3; - t4 += v * b4; - t5 += v * b5; - t6 += v * b6; - t7 += v * b7; - t8 += v * b8; - t9 += v * b9; - t10 += v * b10; - t11 += v * b11; - t12 += v * b12; - t13 += v * b13; - t14 += v * b14; - t15 += v * b15; - v = a[1]; - t1 += v * b0; - t2 += v * b1; - t3 += v * b2; - t4 += v * b3; - t5 += v * b4; - t6 += v * b5; - t7 += v * b6; - t8 += v * b7; - t9 += v * b8; - t10 += v * b9; - t11 += v * b10; - t12 += v * b11; - t13 += v * b12; - t14 += v * b13; - t15 += v * b14; - t16 += v * b15; - v = a[2]; - t2 += v * b0; - t3 += v * b1; - t4 += v * b2; - t5 += v * b3; - t6 += v * b4; - t7 += v * b5; - t8 += v * b6; - t9 += v * b7; - t10 += v * b8; - t11 += v * b9; - t12 += v * b10; - t13 += v * b11; - t14 += v * b12; - t15 += v * b13; - t16 += v * b14; - t17 += v * b15; - v = a[3]; - t3 += v * b0; - t4 += v * b1; - t5 += v * b2; - t6 += v * b3; - t7 += v * b4; - t8 += v * b5; - t9 += v * b6; - t10 += v * b7; - t11 += v * b8; - t12 += v * b9; - t13 += v * b10; - t14 += v * b11; - t15 += v * b12; - t16 += v * b13; - t17 += v * b14; - t18 += v * b15; - v = a[4]; - t4 += v * b0; - t5 += v * b1; - t6 += v * b2; - t7 += v * b3; - t8 += v * b4; - t9 += v * b5; - t10 += v * b6; - t11 += v * b7; - t12 += v * b8; - t13 += v * b9; - t14 += v * b10; - t15 += v * b11; - t16 += v * b12; - t17 += v * b13; - t18 += v * b14; - t19 += v * b15; - v = a[5]; - t5 += v * b0; - t6 += v * b1; - t7 += v * b2; - t8 += v * b3; - t9 += v * b4; - t10 += v * b5; - t11 += v * b6; - t12 += v * b7; - t13 += v * b8; - t14 += v * b9; - t15 += v * b10; - t16 += v * b11; - t17 += v * b12; - t18 += v * b13; - t19 += v * b14; - t20 += v * b15; - v = a[6]; - t6 += v * b0; - t7 += v * b1; - t8 += v * b2; - t9 += v * b3; - t10 += v * b4; - t11 += v * b5; - t12 += v * b6; - t13 += v * b7; - t14 += v * b8; - t15 += v * b9; - t16 += v * b10; - t17 += v * b11; - t18 += v * b12; - t19 += v * b13; - t20 += v * b14; - t21 += v * b15; - v = a[7]; - t7 += v * b0; - t8 += v * b1; - t9 += v * b2; - t10 += v * b3; - t11 += v * b4; - t12 += v * b5; - t13 += v * b6; - t14 += v * b7; - t15 += v * b8; - t16 += v * b9; - t17 += v * b10; - t18 += v * b11; - t19 += v * b12; - t20 += v * b13; - t21 += v * b14; - t22 += v * b15; - v = a[8]; - t8 += v * b0; - t9 += v * b1; - t10 += v * b2; - t11 += v * b3; - t12 += v * b4; - t13 += v * b5; - t14 += v * b6; - t15 += v * b7; - t16 += v * b8; - t17 += v * b9; - t18 += v * b10; - t19 += v * b11; - t20 += v * b12; - t21 += v * b13; - t22 += v * b14; - t23 += v * b15; - v = a[9]; - t9 += v * b0; - t10 += v * b1; - t11 += v * b2; - t12 += v * b3; - t13 += v * b4; - t14 += v * b5; - t15 += v * b6; - t16 += v * b7; - t17 += v * b8; - t18 += v * b9; - t19 += v * b10; - t20 += v * b11; - t21 += v * b12; - t22 += v * b13; - t23 += v * b14; - t24 += v * b15; - v = a[10]; - t10 += v * b0; - t11 += v * b1; - t12 += v * b2; - t13 += v * b3; - t14 += v * b4; - t15 += v * b5; - t16 += v * b6; - t17 += v * b7; - t18 += v * b8; - t19 += v * b9; - t20 += v * b10; - t21 += v * b11; - t22 += v * b12; - t23 += v * b13; - t24 += v * b14; - t25 += v * b15; - v = a[11]; - t11 += v * b0; - t12 += v * b1; - t13 += v * b2; - t14 += v * b3; - t15 += v * b4; - t16 += v * b5; - t17 += v * b6; - t18 += v * b7; - t19 += v * b8; - t20 += v * b9; - t21 += v * b10; - t22 += v * b11; - t23 += v * b12; - t24 += v * b13; - t25 += v * b14; - t26 += v * b15; - v = a[12]; - t12 += v * b0; - t13 += v * b1; - t14 += v * b2; - t15 += v * b3; - t16 += v * b4; - t17 += v * b5; - t18 += v * b6; - t19 += v * b7; - t20 += v * b8; - t21 += v * b9; - t22 += v * b10; - t23 += v * b11; - t24 += v * b12; - t25 += v * b13; - t26 += v * b14; - t27 += v * b15; - v = a[13]; - t13 += v * b0; - t14 += v * b1; - t15 += v * b2; - t16 += v * b3; - t17 += v * b4; - t18 += v * b5; - t19 += v * b6; - t20 += v * b7; - t21 += v * b8; - t22 += v * b9; - t23 += v * b10; - t24 += v * b11; - t25 += v * b12; - t26 += v * b13; - t27 += v * b14; - t28 += v * b15; - v = a[14]; - t14 += v * b0; - t15 += v * b1; - t16 += v * b2; - t17 += v * b3; - t18 += v * b4; - t19 += v * b5; - t20 += v * b6; - t21 += v * b7; - t22 += v * b8; - t23 += v * b9; - t24 += v * b10; - t25 += v * b11; - t26 += v * b12; - t27 += v * b13; - t28 += v * b14; - t29 += v * b15; - v = a[15]; - t15 += v * b0; - t16 += v * b1; - t17 += v * b2; - t18 += v * b3; - t19 += v * b4; - t20 += v * b5; - t21 += v * b6; - t22 += v * b7; - t23 += v * b8; - t24 += v * b9; - t25 += v * b10; - t26 += v * b11; - t27 += v * b12; - t28 += v * b13; - t29 += v * b14; - t30 += v * b15; - t0 += 38 * t16; - t1 += 38 * t17; - t2 += 38 * t18; - t3 += 38 * t19; - t4 += 38 * t20; - t5 += 38 * t21; - t6 += 38 * t22; - t7 += 38 * t23; - t8 += 38 * t24; - t9 += 38 * t25; - t10 += 38 * t26; - t11 += 38 * t27; - t12 += 38 * t28; - t13 += 38 * t29; - t14 += 38 * t30; - c = 1; - v = t0 + c + 65535; - c = Math.floor(v / 65536); - t0 = v - c * 65536; - v = t1 + c + 65535; - c = Math.floor(v / 65536); - t1 = v - c * 65536; - v = t2 + c + 65535; - c = Math.floor(v / 65536); - t2 = v - c * 65536; - v = t3 + c + 65535; - c = Math.floor(v / 65536); - t3 = v - c * 65536; - v = t4 + c + 65535; - c = Math.floor(v / 65536); - t4 = v - c * 65536; - v = t5 + c + 65535; - c = Math.floor(v / 65536); - t5 = v - c * 65536; - v = t6 + c + 65535; - c = Math.floor(v / 65536); - t6 = v - c * 65536; - v = t7 + c + 65535; - c = Math.floor(v / 65536); - t7 = v - c * 65536; - v = t8 + c + 65535; - c = Math.floor(v / 65536); - t8 = v - c * 65536; - v = t9 + c + 65535; - c = Math.floor(v / 65536); - t9 = v - c * 65536; - v = t10 + c + 65535; - c = Math.floor(v / 65536); - t10 = v - c * 65536; - v = t11 + c + 65535; - c = Math.floor(v / 65536); - t11 = v - c * 65536; - v = t12 + c + 65535; - c = Math.floor(v / 65536); - t12 = v - c * 65536; - v = t13 + c + 65535; - c = Math.floor(v / 65536); - t13 = v - c * 65536; - v = t14 + c + 65535; - c = Math.floor(v / 65536); - t14 = v - c * 65536; - v = t15 + c + 65535; - c = Math.floor(v / 65536); - t15 = v - c * 65536; - t0 += c - 1 + 37 * (c - 1); - c = 1; - v = t0 + c + 65535; - c = Math.floor(v / 65536); - t0 = v - c * 65536; - v = t1 + c + 65535; - c = Math.floor(v / 65536); - t1 = v - c * 65536; - v = t2 + c + 65535; - c = Math.floor(v / 65536); - t2 = v - c * 65536; - v = t3 + c + 65535; - c = Math.floor(v / 65536); - t3 = v - c * 65536; - v = t4 + c + 65535; - c = Math.floor(v / 65536); - t4 = v - c * 65536; - v = t5 + c + 65535; - c = Math.floor(v / 65536); - t5 = v - c * 65536; - v = t6 + c + 65535; - c = Math.floor(v / 65536); - t6 = v - c * 65536; - v = t7 + c + 65535; - c = Math.floor(v / 65536); - t7 = v - c * 65536; - v = t8 + c + 65535; - c = Math.floor(v / 65536); - t8 = v - c * 65536; - v = t9 + c + 65535; - c = Math.floor(v / 65536); - t9 = v - c * 65536; - v = t10 + c + 65535; - c = Math.floor(v / 65536); - t10 = v - c * 65536; - v = t11 + c + 65535; - c = Math.floor(v / 65536); - t11 = v - c * 65536; - v = t12 + c + 65535; - c = Math.floor(v / 65536); - t12 = v - c * 65536; - v = t13 + c + 65535; - c = Math.floor(v / 65536); - t13 = v - c * 65536; - v = t14 + c + 65535; - c = Math.floor(v / 65536); - t14 = v - c * 65536; - v = t15 + c + 65535; - c = Math.floor(v / 65536); - t15 = v - c * 65536; - t0 += c - 1 + 37 * (c - 1); - o[0] = t0; - o[1] = t1; - o[2] = t2; - o[3] = t3; - o[4] = t4; - o[5] = t5; - o[6] = t6; - o[7] = t7; - o[8] = t8; - o[9] = t9; - o[10] = t10; - o[11] = t11; - o[12] = t12; - o[13] = t13; - o[14] = t14; - o[15] = t15; - } - } -}); - -// node_modules/node-forge/lib/kem.js -var require_kem = __commonJS({ - "node_modules/node-forge/lib/kem.js"(exports2, module2) { - var forge = require_forge(); - require_util13(); - require_random(); - require_jsbn(); - module2.exports = forge.kem = forge.kem || {}; - var BigInteger = forge.jsbn.BigInteger; - forge.kem.rsa = {}; - forge.kem.rsa.create = function(kdf, options) { - options = options || {}; - var prng = options.prng || forge.random; - var kem = {}; - kem.encrypt = function(publicKey, keyLength) { - var byteLength = Math.ceil(publicKey.n.bitLength() / 8); - var r; - do { - r = new BigInteger( - forge.util.bytesToHex(prng.getBytesSync(byteLength)), - 16 - ).mod(publicKey.n); - } while (r.compareTo(BigInteger.ONE) <= 0); - r = forge.util.hexToBytes(r.toString(16)); - var zeros = byteLength - r.length; - if (zeros > 0) { - r = forge.util.fillString(String.fromCharCode(0), zeros) + r; - } - var encapsulation = publicKey.encrypt(r, "NONE"); - var key = kdf.generate(r, keyLength); - return { encapsulation, key }; - }; - kem.decrypt = function(privateKey, encapsulation, keyLength) { - var r = privateKey.decrypt(encapsulation, "NONE"); - return kdf.generate(r, keyLength); - }; - return kem; - }; - forge.kem.kdf1 = function(md2, digestLength) { - _createKDF(this, md2, 0, digestLength || md2.digestLength); - }; - forge.kem.kdf2 = function(md2, digestLength) { - _createKDF(this, md2, 1, digestLength || md2.digestLength); - }; - function _createKDF(kdf, md2, counterStart, digestLength) { - kdf.generate = function(x, length) { - var key = new forge.util.ByteBuffer(); - var k = Math.ceil(length / digestLength) + counterStart; - var c = new forge.util.ByteBuffer(); - for (var i = counterStart; i < k; ++i) { - c.putInt32(i); - md2.start(); - md2.update(x + c.getBytes()); - var hash = md2.digest(); - key.putBytes(hash.getBytes(digestLength)); - } - key.truncate(key.length() - length); - return key.getBytes(); - }; - } - } -}); - -// node_modules/node-forge/lib/log.js -var require_log = __commonJS({ - "node_modules/node-forge/lib/log.js"(exports2, module2) { - var forge = require_forge(); - require_util13(); - module2.exports = forge.log = forge.log || {}; - forge.log.levels = [ - "none", - "error", - "warning", - "info", - "debug", - "verbose", - "max" - ]; - var sLevelInfo = {}; - var sLoggers = []; - var sConsoleLogger = null; - forge.log.LEVEL_LOCKED = 1 << 1; - forge.log.NO_LEVEL_CHECK = 1 << 2; - forge.log.INTERPOLATE = 1 << 3; - for (i = 0; i < forge.log.levels.length; ++i) { - level = forge.log.levels[i]; - sLevelInfo[level] = { - index: i, - name: level.toUpperCase() - }; - } - var level; - var i; - forge.log.logMessage = function(message) { - var messageLevelIndex = sLevelInfo[message.level].index; - for (var i2 = 0; i2 < sLoggers.length; ++i2) { - var logger2 = sLoggers[i2]; - if (logger2.flags & forge.log.NO_LEVEL_CHECK) { - logger2.f(message); - } else { - var loggerLevelIndex = sLevelInfo[logger2.level].index; - if (messageLevelIndex <= loggerLevelIndex) { - logger2.f(logger2, message); - } - } - } - }; - forge.log.prepareStandard = function(message) { - if (!("standard" in message)) { - message.standard = sLevelInfo[message.level].name + //' ' + +message.timestamp + - " [" + message.category + "] " + message.message; - } - }; - forge.log.prepareFull = function(message) { - if (!("full" in message)) { - var args = [message.message]; - args = args.concat([]); - message.full = forge.util.format.apply(this, args); - } - }; - forge.log.prepareStandardFull = function(message) { - if (!("standardFull" in message)) { - forge.log.prepareStandard(message); - message.standardFull = message.standard; - } - }; - if (true) { - levels = ["error", "warning", "info", "debug", "verbose"]; - for (i = 0; i < levels.length; ++i) { - (function(level2) { - forge.log[level2] = function(category, message) { - var args = Array.prototype.slice.call(arguments).slice(2); - var msg = { - timestamp: /* @__PURE__ */ new Date(), - level: level2, - category, - message, - "arguments": args - /*standard*/ - /*full*/ - /*fullMessage*/ - }; - forge.log.logMessage(msg); - }; - })(levels[i]); - } - } - var levels; - var i; - forge.log.makeLogger = function(logFunction) { - var logger2 = { - flags: 0, - f: logFunction - }; - forge.log.setLevel(logger2, "none"); - return logger2; - }; - forge.log.setLevel = function(logger2, level2) { - var rval = false; - if (logger2 && !(logger2.flags & forge.log.LEVEL_LOCKED)) { - for (var i2 = 0; i2 < forge.log.levels.length; ++i2) { - var aValidLevel = forge.log.levels[i2]; - if (level2 == aValidLevel) { - logger2.level = level2; - rval = true; - break; - } - } - } - return rval; - }; - forge.log.lock = function(logger2, lock2) { - if (typeof lock2 === "undefined" || lock2) { - logger2.flags |= forge.log.LEVEL_LOCKED; - } else { - logger2.flags &= ~forge.log.LEVEL_LOCKED; - } - }; - forge.log.addLogger = function(logger2) { - sLoggers.push(logger2); - }; - if (typeof console !== "undefined" && "log" in console) { - if (console.error && console.warn && console.info && console.debug) { - levelHandlers = { - error: console.error, - warning: console.warn, - info: console.info, - debug: console.debug, - verbose: console.debug - }; - f = function(logger2, message) { - forge.log.prepareStandard(message); - var handler2 = levelHandlers[message.level]; - var args = [message.standard]; - args = args.concat(message["arguments"].slice()); - handler2.apply(console, args); - }; - logger = forge.log.makeLogger(f); - } else { - f = function(logger2, message) { - forge.log.prepareStandardFull(message); - console.log(message.standardFull); - }; - logger = forge.log.makeLogger(f); - } - forge.log.setLevel(logger, "debug"); - forge.log.addLogger(logger); - sConsoleLogger = logger; - } else { - console = { - log: function() { - } - }; - } - var logger; - var levelHandlers; - var f; - if (sConsoleLogger !== null && typeof window !== "undefined" && window.location) { - query = new URL(window.location.href).searchParams; - if (query.has("console.level")) { - forge.log.setLevel( - sConsoleLogger, - query.get("console.level").slice(-1)[0] - ); - } - if (query.has("console.lock")) { - lock = query.get("console.lock").slice(-1)[0]; - if (lock == "true") { - forge.log.lock(sConsoleLogger); - } - } - } - var query; - var lock; - forge.log.consoleLogger = sConsoleLogger; - } -}); - -// node_modules/node-forge/lib/md.all.js -var require_md_all = __commonJS({ - "node_modules/node-forge/lib/md.all.js"(exports2, module2) { - module2.exports = require_md(); - require_md5(); - require_sha1(); - require_sha256(); - require_sha512(); - } -}); - -// node_modules/node-forge/lib/pkcs7.js -var require_pkcs7 = __commonJS({ - "node_modules/node-forge/lib/pkcs7.js"(exports2, module2) { - var forge = require_forge(); - require_aes(); - require_asn1(); - require_des(); - require_oids(); - require_pem(); - require_pkcs7asn1(); - require_random(); - require_util13(); - require_x509(); - var asn1 = forge.asn1; - var p7 = module2.exports = forge.pkcs7 = forge.pkcs7 || {}; - p7.messageFromPem = function(pem) { - var msg = forge.pem.decode(pem)[0]; - if (msg.type !== "PKCS7") { - var error3 = new Error('Could not convert PKCS#7 message from PEM; PEM header type is not "PKCS#7".'); - error3.headerType = msg.type; - throw error3; - } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error("Could not convert PKCS#7 message from PEM; PEM is encrypted."); - } - var obj = asn1.fromDer(msg.body); - return p7.messageFromAsn1(obj); - }; - p7.messageToPem = function(msg, maxline) { - var pemObj = { - type: "PKCS7", - body: asn1.toDer(msg.toAsn1()).getBytes() - }; - return forge.pem.encode(pemObj, { maxline }); - }; - p7.messageFromAsn1 = function(obj) { - var capture = {}; - var errors = []; - if (!asn1.validate(obj, p7.asn1.contentInfoValidator, capture, errors)) { - var error3 = new Error("Cannot read PKCS#7 message. ASN.1 object is not an PKCS#7 ContentInfo."); - error3.errors = errors; - throw error3; - } - var contentType = asn1.derToOid(capture.contentType); - var msg; - switch (contentType) { - case forge.pki.oids.envelopedData: - msg = p7.createEnvelopedData(); - break; - case forge.pki.oids.encryptedData: - msg = p7.createEncryptedData(); - break; - case forge.pki.oids.signedData: - msg = p7.createSignedData(); - break; - default: - throw new Error("Cannot read PKCS#7 message. ContentType with OID " + contentType + " is not (yet) supported."); - } - msg.fromAsn1(capture.content.value[0]); - return msg; - }; - p7.createSignedData = function() { - var msg = null; - msg = { - type: forge.pki.oids.signedData, - version: 1, - certificates: [], - crls: [], - // TODO: add json-formatted signer stuff here? - signers: [], - // populated during sign() - digestAlgorithmIdentifiers: [], - contentInfo: null, - signerInfos: [], - fromAsn1: function(obj) { - _fromAsn1(msg, obj, p7.asn1.signedDataValidator); - msg.certificates = []; - msg.crls = []; - msg.digestAlgorithmIdentifiers = []; - msg.contentInfo = null; - msg.signerInfos = []; - if (msg.rawCapture.certificates) { - var certs = msg.rawCapture.certificates.value; - for (var i = 0; i < certs.length; ++i) { - msg.certificates.push(forge.pki.certificateFromAsn1(certs[i])); - } - } - }, - toAsn1: function() { - if (!msg.contentInfo) { - msg.sign(); - } - var certs = []; - for (var i = 0; i < msg.certificates.length; ++i) { - certs.push(forge.pki.certificateToAsn1(msg.certificates[i])); - } - var crls = []; - var signedData = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Version - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(msg.version).getBytes() - ), - // DigestAlgorithmIdentifiers - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SET, - true, - msg.digestAlgorithmIdentifiers - ), - // ContentInfo - msg.contentInfo - ]) - ]); - if (certs.length > 0) { - signedData.value[0].value.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, certs) - ); - } - if (crls.length > 0) { - signedData.value[0].value.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, crls) - ); - } - signedData.value[0].value.push( - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SET, - true, - msg.signerInfos - ) - ); - return asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [ - // ContentType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(msg.type).getBytes() - ), - // [0] SignedData - signedData - ] - ); - }, - /** - * Add (another) entity to list of signers. - * - * Note: If authenticatedAttributes are provided, then, per RFC 2315, - * they must include at least two attributes: content type and - * message digest. The message digest attribute value will be - * auto-calculated during signing and will be ignored if provided. - * - * Here's an example of providing these two attributes: - * - * forge.pkcs7.createSignedData(); - * p7.addSigner({ - * issuer: cert.issuer.attributes, - * serialNumber: cert.serialNumber, - * key: privateKey, - * digestAlgorithm: forge.pki.oids.sha1, - * authenticatedAttributes: [{ - * type: forge.pki.oids.contentType, - * value: forge.pki.oids.data - * }, { - * type: forge.pki.oids.messageDigest - * }] - * }); - * - * TODO: Support [subjectKeyIdentifier] as signer's ID. - * - * @param signer the signer information: - * key the signer's private key. - * [certificate] a certificate containing the public key - * associated with the signer's private key; use this option as - * an alternative to specifying signer.issuer and - * signer.serialNumber. - * [issuer] the issuer attributes (eg: cert.issuer.attributes). - * [serialNumber] the signer's certificate's serial number in - * hexadecimal (eg: cert.serialNumber). - * [digestAlgorithm] the message digest OID, as a string, to use - * (eg: forge.pki.oids.sha1). - * [authenticatedAttributes] an optional array of attributes - * to also sign along with the content. - */ - addSigner: function(signer) { - var issuer = signer.issuer; - var serialNumber = signer.serialNumber; - if (signer.certificate) { - var cert = signer.certificate; - if (typeof cert === "string") { - cert = forge.pki.certificateFromPem(cert); - } - issuer = cert.issuer.attributes; - serialNumber = cert.serialNumber; - } - var key = signer.key; - if (!key) { - throw new Error( - "Could not add PKCS#7 signer; no private key specified." - ); - } - if (typeof key === "string") { - key = forge.pki.privateKeyFromPem(key); - } - var digestAlgorithm = signer.digestAlgorithm || forge.pki.oids.sha1; - switch (digestAlgorithm) { - case forge.pki.oids.sha1: - case forge.pki.oids.sha256: - case forge.pki.oids.sha384: - case forge.pki.oids.sha512: - case forge.pki.oids.md5: - break; - default: - throw new Error( - "Could not add PKCS#7 signer; unknown message digest algorithm: " + digestAlgorithm - ); - } - var authenticatedAttributes = signer.authenticatedAttributes || []; - if (authenticatedAttributes.length > 0) { - var contentType = false; - var messageDigest = false; - for (var i = 0; i < authenticatedAttributes.length; ++i) { - var attr = authenticatedAttributes[i]; - if (!contentType && attr.type === forge.pki.oids.contentType) { - contentType = true; - if (messageDigest) { - break; - } - continue; - } - if (!messageDigest && attr.type === forge.pki.oids.messageDigest) { - messageDigest = true; - if (contentType) { - break; - } - continue; - } - } - if (!contentType || !messageDigest) { - throw new Error("Invalid signer.authenticatedAttributes. If signer.authenticatedAttributes is specified, then it must contain at least two attributes, PKCS #9 content-type and PKCS #9 message-digest."); - } - } - msg.signers.push({ - key, - version: 1, - issuer, - serialNumber, - digestAlgorithm, - signatureAlgorithm: forge.pki.oids.rsaEncryption, - signature: null, - authenticatedAttributes, - unauthenticatedAttributes: [] - }); - }, - /** - * Signs the content. - * @param options Options to apply when signing: - * [detached] boolean. If signing should be done in detached mode. Defaults to false. - */ - sign: function(options) { - options = options || {}; - if (typeof msg.content !== "object" || msg.contentInfo === null) { - msg.contentInfo = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [ - // ContentType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(forge.pki.oids.data).getBytes() - ) - ] - ); - if ("content" in msg) { - var content; - if (msg.content instanceof forge.util.ByteBuffer) { - content = msg.content.bytes(); - } else if (typeof msg.content === "string") { - content = forge.util.encodeUtf8(msg.content); - } - if (options.detached) { - msg.detachedContent = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, content); - } else { - msg.contentInfo.value.push( - // [0] EXPLICIT content - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - content - ) - ]) - ); - } - } - } - if (msg.signers.length === 0) { - return; - } - var mds = addDigestAlgorithmIds(); - addSignerInfos(mds); - }, - verify: function() { - throw new Error("PKCS#7 signature verification not yet implemented."); - }, - /** - * Add a certificate. - * - * @param cert the certificate to add. - */ - addCertificate: function(cert) { - if (typeof cert === "string") { - cert = forge.pki.certificateFromPem(cert); - } - msg.certificates.push(cert); - }, - /** - * Add a certificate revokation list. - * - * @param crl the certificate revokation list to add. - */ - addCertificateRevokationList: function(crl) { - throw new Error("PKCS#7 CRL support not yet implemented."); - } - }; - return msg; - function addDigestAlgorithmIds() { - var mds = {}; - for (var i = 0; i < msg.signers.length; ++i) { - var signer = msg.signers[i]; - var oid = signer.digestAlgorithm; - if (!(oid in mds)) { - mds[oid] = forge.md[forge.pki.oids[oid]].create(); - } - if (signer.authenticatedAttributes.length === 0) { - signer.md = mds[oid]; - } else { - signer.md = forge.md[forge.pki.oids[oid]].create(); - } - } - msg.digestAlgorithmIdentifiers = []; - for (var oid in mds) { - msg.digestAlgorithmIdentifiers.push( - // AlgorithmIdentifier - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(oid).getBytes() - ), - // parameters (null) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]) - ); - } - return mds; - } - function addSignerInfos(mds) { - var content; - if (msg.detachedContent) { - content = msg.detachedContent; - } else { - content = msg.contentInfo.value[1]; - content = content.value[0]; - } - if (!content) { - throw new Error( - "Could not sign PKCS#7 message; there is no content to sign." - ); - } - var contentType = asn1.derToOid(msg.contentInfo.value[0].value); - var bytes = asn1.toDer(content); - bytes.getByte(); - asn1.getBerValueLength(bytes); - bytes = bytes.getBytes(); - for (var oid in mds) { - mds[oid].start().update(bytes); - } - var signingTime = /* @__PURE__ */ new Date(); - for (var i = 0; i < msg.signers.length; ++i) { - var signer = msg.signers[i]; - if (signer.authenticatedAttributes.length === 0) { - if (contentType !== forge.pki.oids.data) { - throw new Error( - "Invalid signer; authenticatedAttributes must be present when the ContentInfo content type is not PKCS#7 Data." - ); - } - } else { - signer.authenticatedAttributesAsn1 = asn1.create( - asn1.Class.CONTEXT_SPECIFIC, - 0, - true, - [] - ); - var attrsAsn1 = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SET, - true, - [] - ); - for (var ai = 0; ai < signer.authenticatedAttributes.length; ++ai) { - var attr = signer.authenticatedAttributes[ai]; - if (attr.type === forge.pki.oids.messageDigest) { - attr.value = mds[signer.digestAlgorithm].digest(); - } else if (attr.type === forge.pki.oids.signingTime) { - if (!attr.value) { - attr.value = signingTime; - } - } - attrsAsn1.value.push(_attributeToAsn1(attr)); - signer.authenticatedAttributesAsn1.value.push(_attributeToAsn1(attr)); - } - bytes = asn1.toDer(attrsAsn1).getBytes(); - signer.md.start().update(bytes); - } - signer.signature = signer.key.sign(signer.md, "RSASSA-PKCS1-V1_5"); - } - msg.signerInfos = _signersToAsn1(msg.signers); - } - }; - p7.createEncryptedData = function() { - var msg = null; - msg = { - type: forge.pki.oids.encryptedData, - version: 0, - encryptedContent: { - algorithm: forge.pki.oids["aes256-CBC"] - }, - /** - * Reads an EncryptedData content block (in ASN.1 format) - * - * @param obj The ASN.1 representation of the EncryptedData content block - */ - fromAsn1: function(obj) { - _fromAsn1(msg, obj, p7.asn1.encryptedDataValidator); - }, - /** - * Decrypt encrypted content - * - * @param key The (symmetric) key as a byte buffer - */ - decrypt: function(key) { - if (key !== void 0) { - msg.encryptedContent.key = key; - } - _decryptContent(msg); - } - }; - return msg; - }; - p7.createEnvelopedData = function() { - var msg = null; - msg = { - type: forge.pki.oids.envelopedData, - version: 0, - recipients: [], - encryptedContent: { - algorithm: forge.pki.oids["aes256-CBC"] - }, - /** - * Reads an EnvelopedData content block (in ASN.1 format) - * - * @param obj the ASN.1 representation of the EnvelopedData content block. - */ - fromAsn1: function(obj) { - var capture = _fromAsn1(msg, obj, p7.asn1.envelopedDataValidator); - msg.recipients = _recipientsFromAsn1(capture.recipientInfos.value); - }, - toAsn1: function() { - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // ContentType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(msg.type).getBytes() - ), - // [0] EnvelopedData - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Version - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(msg.version).getBytes() - ), - // RecipientInfos - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SET, - true, - _recipientsToAsn1(msg.recipients) - ), - // EncryptedContentInfo - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - _encryptedContentToAsn1(msg.encryptedContent) - ) - ]) - ]) - ]); - }, - /** - * Find recipient by X.509 certificate's issuer. - * - * @param cert the certificate with the issuer to look for. - * - * @return the recipient object. - */ - findRecipient: function(cert) { - var sAttr = cert.issuer.attributes; - for (var i = 0; i < msg.recipients.length; ++i) { - var r = msg.recipients[i]; - var rAttr = r.issuer; - if (r.serialNumber !== cert.serialNumber) { - continue; - } - if (rAttr.length !== sAttr.length) { - continue; - } - var match = true; - for (var j = 0; j < sAttr.length; ++j) { - if (rAttr[j].type !== sAttr[j].type || rAttr[j].value !== sAttr[j].value) { - match = false; - break; - } - } - if (match) { - return r; - } - } - return null; - }, - /** - * Decrypt enveloped content - * - * @param recipient The recipient object related to the private key - * @param privKey The (RSA) private key object - */ - decrypt: function(recipient, privKey) { - if (msg.encryptedContent.key === void 0 && recipient !== void 0 && privKey !== void 0) { - switch (recipient.encryptedContent.algorithm) { - case forge.pki.oids.rsaEncryption: - case forge.pki.oids.desCBC: - var key = privKey.decrypt(recipient.encryptedContent.content); - msg.encryptedContent.key = forge.util.createBuffer(key); - break; - default: - throw new Error("Unsupported asymmetric cipher, OID " + recipient.encryptedContent.algorithm); - } - } - _decryptContent(msg); - }, - /** - * Add (another) entity to list of recipients. - * - * @param cert The certificate of the entity to add. - */ - addRecipient: function(cert) { - msg.recipients.push({ - version: 0, - issuer: cert.issuer.attributes, - serialNumber: cert.serialNumber, - encryptedContent: { - // We simply assume rsaEncryption here, since forge.pki only - // supports RSA so far. If the PKI module supports other - // ciphers one day, we need to modify this one as well. - algorithm: forge.pki.oids.rsaEncryption, - key: cert.publicKey - } - }); - }, - /** - * Encrypt enveloped content. - * - * This function supports two optional arguments, cipher and key, which - * can be used to influence symmetric encryption. Unless cipher is - * provided, the cipher specified in encryptedContent.algorithm is used - * (defaults to AES-256-CBC). If no key is provided, encryptedContent.key - * is (re-)used. If that one's not set, a random key will be generated - * automatically. - * - * @param [key] The key to be used for symmetric encryption. - * @param [cipher] The OID of the symmetric cipher to use. - */ - encrypt: function(key, cipher) { - if (msg.encryptedContent.content === void 0) { - cipher = cipher || msg.encryptedContent.algorithm; - key = key || msg.encryptedContent.key; - var keyLen, ivLen, ciphFn; - switch (cipher) { - case forge.pki.oids["aes128-CBC"]: - keyLen = 16; - ivLen = 16; - ciphFn = forge.aes.createEncryptionCipher; - break; - case forge.pki.oids["aes192-CBC"]: - keyLen = 24; - ivLen = 16; - ciphFn = forge.aes.createEncryptionCipher; - break; - case forge.pki.oids["aes256-CBC"]: - keyLen = 32; - ivLen = 16; - ciphFn = forge.aes.createEncryptionCipher; - break; - case forge.pki.oids["des-EDE3-CBC"]: - keyLen = 24; - ivLen = 8; - ciphFn = forge.des.createEncryptionCipher; - break; - default: - throw new Error("Unsupported symmetric cipher, OID " + cipher); - } - if (key === void 0) { - key = forge.util.createBuffer(forge.random.getBytes(keyLen)); - } else if (key.length() != keyLen) { - throw new Error("Symmetric key has wrong length; got " + key.length() + " bytes, expected " + keyLen + "."); - } - msg.encryptedContent.algorithm = cipher; - msg.encryptedContent.key = key; - msg.encryptedContent.parameter = forge.util.createBuffer( - forge.random.getBytes(ivLen) - ); - var ciph = ciphFn(key); - ciph.start(msg.encryptedContent.parameter.copy()); - ciph.update(msg.content); - if (!ciph.finish()) { - throw new Error("Symmetric encryption failed."); - } - msg.encryptedContent.content = ciph.output; - } - for (var i = 0; i < msg.recipients.length; ++i) { - var recipient = msg.recipients[i]; - if (recipient.encryptedContent.content !== void 0) { - continue; - } - switch (recipient.encryptedContent.algorithm) { - case forge.pki.oids.rsaEncryption: - recipient.encryptedContent.content = recipient.encryptedContent.key.encrypt( - msg.encryptedContent.key.data - ); - break; - default: - throw new Error("Unsupported asymmetric cipher, OID " + recipient.encryptedContent.algorithm); - } - } - } - }; - return msg; - }; - function _recipientFromAsn1(obj) { - var capture = {}; - var errors = []; - if (!asn1.validate(obj, p7.asn1.recipientInfoValidator, capture, errors)) { - var error3 = new Error("Cannot read PKCS#7 RecipientInfo. ASN.1 object is not an PKCS#7 RecipientInfo."); - error3.errors = errors; - throw error3; - } - return { - version: capture.version.charCodeAt(0), - issuer: forge.pki.RDNAttributesAsArray(capture.issuer), - serialNumber: forge.util.createBuffer(capture.serial).toHex(), - encryptedContent: { - algorithm: asn1.derToOid(capture.encAlgorithm), - parameter: capture.encParameter ? capture.encParameter.value : void 0, - content: capture.encKey - } - }; - } - function _recipientToAsn1(obj) { - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Version - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(obj.version).getBytes() - ), - // IssuerAndSerialNumber - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Name - forge.pki.distinguishedNameToAsn1({ attributes: obj.issuer }), - // Serial - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - forge.util.hexToBytes(obj.serialNumber) - ) - ]), - // KeyEncryptionAlgorithmIdentifier - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(obj.encryptedContent.algorithm).getBytes() - ), - // Parameter, force NULL, only RSA supported for now. - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]), - // EncryptedKey - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - obj.encryptedContent.content - ) - ]); - } - function _recipientsFromAsn1(infos) { - var ret = []; - for (var i = 0; i < infos.length; ++i) { - ret.push(_recipientFromAsn1(infos[i])); - } - return ret; - } - function _recipientsToAsn1(recipients) { - var ret = []; - for (var i = 0; i < recipients.length; ++i) { - ret.push(_recipientToAsn1(recipients[i])); - } - return ret; - } - function _signerToAsn1(obj) { - var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // version - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(obj.version).getBytes() - ), - // issuerAndSerialNumber - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // name - forge.pki.distinguishedNameToAsn1({ attributes: obj.issuer }), - // serial - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - forge.util.hexToBytes(obj.serialNumber) - ) - ]), - // digestAlgorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(obj.digestAlgorithm).getBytes() - ), - // parameters (null) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]) - ]); - if (obj.authenticatedAttributesAsn1) { - rval.value.push(obj.authenticatedAttributesAsn1); - } - rval.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(obj.signatureAlgorithm).getBytes() - ), - // parameters (null) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ])); - rval.value.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - obj.signature - )); - if (obj.unauthenticatedAttributes.length > 0) { - var attrsAsn1 = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, []); - for (var i = 0; i < obj.unauthenticatedAttributes.length; ++i) { - var attr = obj.unauthenticatedAttributes[i]; - attrsAsn1.values.push(_attributeToAsn1(attr)); - } - rval.value.push(attrsAsn1); - } - return rval; - } - function _signersToAsn1(signers) { - var ret = []; - for (var i = 0; i < signers.length; ++i) { - ret.push(_signerToAsn1(signers[i])); - } - return ret; - } - function _attributeToAsn1(attr) { - var value; - if (attr.type === forge.pki.oids.contentType) { - value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(attr.value).getBytes() - ); - } else if (attr.type === forge.pki.oids.messageDigest) { - value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - attr.value.bytes() - ); - } else if (attr.type === forge.pki.oids.signingTime) { - var jan_1_1950 = /* @__PURE__ */ new Date("1950-01-01T00:00:00Z"); - var jan_1_2050 = /* @__PURE__ */ new Date("2050-01-01T00:00:00Z"); - var date = attr.value; - if (typeof date === "string") { - var timestamp = Date.parse(date); - if (!isNaN(timestamp)) { - date = new Date(timestamp); - } else if (date.length === 13) { - date = asn1.utcTimeToDate(date); - } else { - date = asn1.generalizedTimeToDate(date); - } - } - if (date >= jan_1_1950 && date < jan_1_2050) { - value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.UTCTIME, - false, - asn1.dateToUtcTime(date) - ); - } else { - value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.GENERALIZEDTIME, - false, - asn1.dateToGeneralizedTime(date) - ); - } - } - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // AttributeType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(attr.type).getBytes() - ), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ - // AttributeValue - value - ]) - ]); - } - function _encryptedContentToAsn1(ec) { - return [ - // ContentType, always Data for the moment - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(forge.pki.oids.data).getBytes() - ), - // ContentEncryptionAlgorithmIdentifier - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(ec.algorithm).getBytes() - ), - // Parameters (IV) - !ec.parameter ? void 0 : asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - ec.parameter.getBytes() - ) - ]), - // [0] EncryptedContent - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - ec.content.getBytes() - ) - ]) - ]; - } - function _fromAsn1(msg, obj, validator) { - var capture = {}; - var errors = []; - if (!asn1.validate(obj, validator, capture, errors)) { - var error3 = new Error("Cannot read PKCS#7 message. ASN.1 object is not a supported PKCS#7 message."); - error3.errors = error3; - throw error3; - } - var contentType = asn1.derToOid(capture.contentType); - if (contentType !== forge.pki.oids.data) { - throw new Error("Unsupported PKCS#7 message. Only wrapped ContentType Data supported."); - } - if (capture.encryptedContent) { - var content = ""; - if (forge.util.isArray(capture.encryptedContent)) { - for (var i = 0; i < capture.encryptedContent.length; ++i) { - if (capture.encryptedContent[i].type !== asn1.Type.OCTETSTRING) { - throw new Error("Malformed PKCS#7 message, expecting encrypted content constructed of only OCTET STRING objects."); - } - content += capture.encryptedContent[i].value; - } - } else { - content = capture.encryptedContent; - } - msg.encryptedContent = { - algorithm: asn1.derToOid(capture.encAlgorithm), - parameter: forge.util.createBuffer(capture.encParameter.value), - content: forge.util.createBuffer(content) - }; - } - if (capture.content) { - var content = ""; - if (forge.util.isArray(capture.content)) { - for (var i = 0; i < capture.content.length; ++i) { - if (capture.content[i].type !== asn1.Type.OCTETSTRING) { - throw new Error("Malformed PKCS#7 message, expecting content constructed of only OCTET STRING objects."); - } - content += capture.content[i].value; - } - } else { - content = capture.content; - } - msg.content = forge.util.createBuffer(content); - } - msg.version = capture.version.charCodeAt(0); - msg.rawCapture = capture; - return capture; - } - function _decryptContent(msg) { - if (msg.encryptedContent.key === void 0) { - throw new Error("Symmetric key not available."); - } - if (msg.content === void 0) { - var ciph; - switch (msg.encryptedContent.algorithm) { - case forge.pki.oids["aes128-CBC"]: - case forge.pki.oids["aes192-CBC"]: - case forge.pki.oids["aes256-CBC"]: - ciph = forge.aes.createDecryptionCipher(msg.encryptedContent.key); - break; - case forge.pki.oids["desCBC"]: - case forge.pki.oids["des-EDE3-CBC"]: - ciph = forge.des.createDecryptionCipher(msg.encryptedContent.key); - break; - default: - throw new Error("Unsupported symmetric cipher, OID " + msg.encryptedContent.algorithm); - } - ciph.start(msg.encryptedContent.parameter); - ciph.update(msg.encryptedContent.content); - if (!ciph.finish()) { - throw new Error("Symmetric decryption failed."); - } - msg.content = ciph.output; - } - } - } -}); - -// node_modules/node-forge/lib/ssh.js -var require_ssh2 = __commonJS({ - "node_modules/node-forge/lib/ssh.js"(exports2, module2) { - var forge = require_forge(); - require_aes(); - require_hmac(); - require_md5(); - require_sha1(); - require_util13(); - var ssh = module2.exports = forge.ssh = forge.ssh || {}; - ssh.privateKeyToPutty = function(privateKey, passphrase, comment) { - comment = comment || ""; - passphrase = passphrase || ""; - var algorithm = "ssh-rsa"; - var encryptionAlgorithm = passphrase === "" ? "none" : "aes256-cbc"; - var ppk = "PuTTY-User-Key-File-2: " + algorithm + "\r\n"; - ppk += "Encryption: " + encryptionAlgorithm + "\r\n"; - ppk += "Comment: " + comment + "\r\n"; - var pubbuffer = forge.util.createBuffer(); - _addStringToBuffer(pubbuffer, algorithm); - _addBigIntegerToBuffer(pubbuffer, privateKey.e); - _addBigIntegerToBuffer(pubbuffer, privateKey.n); - var pub = forge.util.encode64(pubbuffer.bytes(), 64); - var length = Math.floor(pub.length / 66) + 1; - ppk += "Public-Lines: " + length + "\r\n"; - ppk += pub; - var privbuffer = forge.util.createBuffer(); - _addBigIntegerToBuffer(privbuffer, privateKey.d); - _addBigIntegerToBuffer(privbuffer, privateKey.p); - _addBigIntegerToBuffer(privbuffer, privateKey.q); - _addBigIntegerToBuffer(privbuffer, privateKey.qInv); - var priv; - if (!passphrase) { - priv = forge.util.encode64(privbuffer.bytes(), 64); - } else { - var encLen = privbuffer.length() + 16 - 1; - encLen -= encLen % 16; - var padding = _sha1(privbuffer.bytes()); - padding.truncate(padding.length() - encLen + privbuffer.length()); - privbuffer.putBuffer(padding); - var aeskey = forge.util.createBuffer(); - aeskey.putBuffer(_sha1("\0\0\0\0", passphrase)); - aeskey.putBuffer(_sha1("\0\0\0", passphrase)); - var cipher = forge.aes.createEncryptionCipher(aeskey.truncate(8), "CBC"); - cipher.start(forge.util.createBuffer().fillWithByte(0, 16)); - cipher.update(privbuffer.copy()); - cipher.finish(); - var encrypted = cipher.output; - encrypted.truncate(16); - priv = forge.util.encode64(encrypted.bytes(), 64); - } - length = Math.floor(priv.length / 66) + 1; - ppk += "\r\nPrivate-Lines: " + length + "\r\n"; - ppk += priv; - var mackey = _sha1("putty-private-key-file-mac-key", passphrase); - var macbuffer = forge.util.createBuffer(); - _addStringToBuffer(macbuffer, algorithm); - _addStringToBuffer(macbuffer, encryptionAlgorithm); - _addStringToBuffer(macbuffer, comment); - macbuffer.putInt32(pubbuffer.length()); - macbuffer.putBuffer(pubbuffer); - macbuffer.putInt32(privbuffer.length()); - macbuffer.putBuffer(privbuffer); - var hmac = forge.hmac.create(); - hmac.start("sha1", mackey); - hmac.update(macbuffer.bytes()); - ppk += "\r\nPrivate-MAC: " + hmac.digest().toHex() + "\r\n"; - return ppk; - }; - ssh.publicKeyToOpenSSH = function(key, comment) { - var type = "ssh-rsa"; - comment = comment || ""; - var buffer = forge.util.createBuffer(); - _addStringToBuffer(buffer, type); - _addBigIntegerToBuffer(buffer, key.e); - _addBigIntegerToBuffer(buffer, key.n); - return type + " " + forge.util.encode64(buffer.bytes()) + " " + comment; - }; - ssh.privateKeyToOpenSSH = function(privateKey, passphrase) { - if (!passphrase) { - return forge.pki.privateKeyToPem(privateKey); - } - return forge.pki.encryptRsaPrivateKey( - privateKey, - passphrase, - { legacy: true, algorithm: "aes128" } - ); - }; - ssh.getPublicKeyFingerprint = function(key, options) { - options = options || {}; - var md2 = options.md || forge.md.md5.create(); - var type = "ssh-rsa"; - var buffer = forge.util.createBuffer(); - _addStringToBuffer(buffer, type); - _addBigIntegerToBuffer(buffer, key.e); - _addBigIntegerToBuffer(buffer, key.n); - md2.start(); - md2.update(buffer.getBytes()); - var digest = md2.digest(); - if (options.encoding === "hex") { - var hex = digest.toHex(); - if (options.delimiter) { - return hex.match(/.{2}/g).join(options.delimiter); - } - return hex; - } else if (options.encoding === "binary") { - return digest.getBytes(); - } else if (options.encoding) { - throw new Error('Unknown encoding "' + options.encoding + '".'); - } - return digest; - }; - function _addBigIntegerToBuffer(buffer, val) { - var hexVal = val.toString(16); - if (hexVal[0] >= "8") { - hexVal = "00" + hexVal; - } - var bytes = forge.util.hexToBytes(hexVal); - buffer.putInt32(bytes.length); - buffer.putBytes(bytes); - } - function _addStringToBuffer(buffer, val) { - buffer.putInt32(val.length); - buffer.putString(val); - } - function _sha1() { - var sha = forge.md.sha1.create(); - var num = arguments.length; - for (var i = 0; i < num; ++i) { - sha.update(arguments[i]); - } - return sha.digest(); - } - } -}); - -// node_modules/node-forge/lib/index.js -var require_lib6 = __commonJS({ - "node_modules/node-forge/lib/index.js"(exports2, module2) { - module2.exports = require_forge(); - require_aes(); - require_aesCipherSuites(); - require_asn1(); - require_cipher(); - require_des(); - require_ed25519(); - require_hmac(); - require_kem(); - require_log(); - require_md_all(); - require_mgf1(); - require_pbkdf2(); - require_pem(); - require_pkcs1(); - require_pkcs12(); - require_pkcs7(); - require_pki(); - require_prime(); - require_prng(); - require_pss(); - require_random(); - require_rc2(); - require_ssh2(); - require_tls(); - require_util13(); - } -}); - -// src/main.ts -var main_exports = {}; -__export(main_exports, { - DependabotErrorType: () => DependabotErrorType, - credentialsFromEnv: () => credentialsFromEnv, - getPackagesCredential: () => getPackagesCredential, - run: () => run -}); -module.exports = __toCommonJS(main_exports); -var core8 = __toESM(require_core()); - -// node_modules/@actions/github/lib/context.js -var import_fs = require("fs"); -var import_os = require("os"); -var Context = class { - /** - * Hydrate the context from the environment - */ - constructor() { - var _a, _b, _c; - this.payload = {}; - if (process.env.GITHUB_EVENT_PATH) { - if ((0, import_fs.existsSync)(process.env.GITHUB_EVENT_PATH)) { - this.payload = JSON.parse((0, import_fs.readFileSync)(process.env.GITHUB_EVENT_PATH, { encoding: "utf8" })); - } else { - const path = process.env.GITHUB_EVENT_PATH; - process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${import_os.EOL}`); - } - } - this.eventName = process.env.GITHUB_EVENT_NAME; - this.sha = process.env.GITHUB_SHA; - this.ref = process.env.GITHUB_REF; - this.workflow = process.env.GITHUB_WORKFLOW; - this.action = process.env.GITHUB_ACTION; - this.actor = process.env.GITHUB_ACTOR; - this.job = process.env.GITHUB_JOB; - this.runAttempt = parseInt(process.env.GITHUB_RUN_ATTEMPT, 10); - this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10); - this.runId = parseInt(process.env.GITHUB_RUN_ID, 10); - this.apiUrl = (_a = process.env.GITHUB_API_URL) !== null && _a !== void 0 ? _a : `https://api.github.com`; - this.serverUrl = (_b = process.env.GITHUB_SERVER_URL) !== null && _b !== void 0 ? _b : `https://github.com`; - this.graphqlUrl = (_c = process.env.GITHUB_GRAPHQL_URL) !== null && _c !== void 0 ? _c : `https://api.github.com/graphql`; - } - get issue() { - const payload = this.payload; - return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number }); - } - get repo() { - if (process.env.GITHUB_REPOSITORY) { - const [owner, repo] = process.env.GITHUB_REPOSITORY.split("/"); - return { owner, repo }; - } - if (this.payload.repository) { - return { - owner: this.payload.repository.owner.login, - repo: this.payload.repository.name - }; - } - throw new Error("context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'"); - } -}; - -// node_modules/@actions/github/lib/internal/utils.js -var httpClient = __toESM(require_lib2(), 1); -var import_undici = __toESM(require_undici(), 1); -var __awaiter = function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); - } - return new (P || (P = 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 getProxyAgent(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgent(destinationUrl); -} -function getProxyAgentDispatcher(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgentDispatcher(destinationUrl); -} -function getProxyFetch(destinationUrl) { - const httpDispatcher = getProxyAgentDispatcher(destinationUrl); - const proxyFetch = (url, opts) => __awaiter(this, void 0, void 0, function* () { - return (0, import_undici.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); - }); - return proxyFetch; -} -function getApiBaseUrl() { - return process.env["GITHUB_API_URL"] || "https://api.github.com"; -} - -// node_modules/universal-user-agent/index.js -function getUserAgent() { - if (typeof navigator === "object" && "userAgent" in navigator) { - return navigator.userAgent; - } - if (typeof process === "object" && process.version !== void 0) { - return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; - } - return ""; -} - -// node_modules/before-after-hook/lib/register.js -function register(state, name, method, options) { - if (typeof method !== "function") { - throw new Error("method for before hook must be a function"); - } - if (!options) { - options = {}; - } - if (Array.isArray(name)) { - return name.reverse().reduce((callback, name2) => { - return register.bind(null, state, name2, callback, options); - }, method)(); - } - return Promise.resolve().then(() => { - if (!state.registry[name]) { - return method(options); - } - return state.registry[name].reduce((method2, registered) => { - return registered.hook.bind(null, method2, options); - }, method)(); - }); -} - -// node_modules/before-after-hook/lib/add.js -function addHook(state, kind, name, hook2) { - const orig = hook2; - if (!state.registry[name]) { - state.registry[name] = []; - } - if (kind === "before") { - hook2 = (method, options) => { - return Promise.resolve().then(orig.bind(null, options)).then(method.bind(null, options)); - }; - } - if (kind === "after") { - hook2 = (method, options) => { - let result; - return Promise.resolve().then(method.bind(null, options)).then((result_) => { - result = result_; - return orig(result, options); - }).then(() => { - return result; - }); - }; - } - if (kind === "error") { - hook2 = (method, options) => { - return Promise.resolve().then(method.bind(null, options)).catch((error3) => { - return orig(error3, options); - }); - }; - } - state.registry[name].push({ - hook: hook2, - orig - }); -} - -// node_modules/before-after-hook/lib/remove.js -function removeHook(state, name, method) { - if (!state.registry[name]) { - return; - } - const index = state.registry[name].map((registered) => { - return registered.orig; - }).indexOf(method); - if (index === -1) { - return; - } - state.registry[name].splice(index, 1); -} - -// node_modules/before-after-hook/index.js -var bind = Function.bind; -var bindable = bind.bind(bind); -function bindApi(hook2, state, name) { - const removeHookRef = bindable(removeHook, null).apply( - null, - name ? [state, name] : [state] - ); - hook2.api = { remove: removeHookRef }; - hook2.remove = removeHookRef; - ["before", "error", "after", "wrap"].forEach((kind) => { - const args = name ? [state, kind, name] : [state, kind]; - hook2[kind] = hook2.api[kind] = bindable(addHook, null).apply(null, args); - }); -} -function Singular() { - const singularHookName = /* @__PURE__ */ Symbol("Singular"); - const singularHookState = { - registry: {} - }; - const singularHook = register.bind(null, singularHookState, singularHookName); - bindApi(singularHook, singularHookState, singularHookName); - return singularHook; -} -function Collection() { - const state = { - registry: {} - }; - const hook2 = register.bind(null, state); - bindApi(hook2, state); - return hook2; -} -var before_after_hook_default = { Singular, Collection }; - -// node_modules/@octokit/endpoint/dist-bundle/index.js -var VERSION = "0.0.0-development"; -var userAgent = `octokit-endpoint.js/${VERSION} ${getUserAgent()}`; -var DEFAULTS = { - method: "GET", - baseUrl: "https://api.github.com", - headers: { - accept: "application/vnd.github.v3+json", - "user-agent": userAgent - }, - mediaType: { - format: "" - } -}; -function lowercaseKeys(object) { - if (!object) { - return {}; - } - return Object.keys(object).reduce((newObj, key) => { - newObj[key.toLowerCase()] = object[key]; - return newObj; - }, {}); -} -function isPlainObject(value) { - if (typeof value !== "object" || value === null) return false; - if (Object.prototype.toString.call(value) !== "[object Object]") return false; - const proto = Object.getPrototypeOf(value); - if (proto === null) return true; - const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor; - return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value); -} -function mergeDeep(defaults2, options) { - const result = Object.assign({}, defaults2); - Object.keys(options).forEach((key) => { - if (isPlainObject(options[key])) { - if (!(key in defaults2)) Object.assign(result, { [key]: options[key] }); - else result[key] = mergeDeep(defaults2[key], options[key]); - } else { - Object.assign(result, { [key]: options[key] }); - } - }); - return result; -} -function removeUndefinedProperties(obj) { - for (const key in obj) { - if (obj[key] === void 0) { - delete obj[key]; - } - } - return obj; -} -function merge(defaults2, route, options) { - if (typeof route === "string") { - let [method, url] = route.split(" "); - options = Object.assign(url ? { method, url } : { url: method }, options); - } else { - options = Object.assign({}, route); - } - options.headers = lowercaseKeys(options.headers); - removeUndefinedProperties(options); - removeUndefinedProperties(options.headers); - const mergedOptions = mergeDeep(defaults2 || {}, options); - if (options.url === "/graphql") { - if (defaults2 && defaults2.mediaType.previews?.length) { - mergedOptions.mediaType.previews = defaults2.mediaType.previews.filter( - (preview) => !mergedOptions.mediaType.previews.includes(preview) - ).concat(mergedOptions.mediaType.previews); - } - mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, "")); - } - return mergedOptions; -} -function addQueryParameters(url, parameters) { - const separator = /\?/.test(url) ? "&" : "?"; - const names = Object.keys(parameters); - if (names.length === 0) { - return url; - } - return url + separator + names.map((name) => { - if (name === "q") { - return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); - } - return `${name}=${encodeURIComponent(parameters[name])}`; - }).join("&"); -} -var urlVariableRegex = /\{[^{}}]+\}/g; -function removeNonChars(variableName) { - return variableName.replace(/(?:^\W+)|(?:(? a.concat(b), []); -} -function omit(object, keysToOmit) { - const result = { __proto__: null }; - for (const key of Object.keys(object)) { - if (keysToOmit.indexOf(key) === -1) { - result[key] = object[key]; - } - } - return result; -} -function encodeReserved(str) { - return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) { - if (!/%[0-9A-Fa-f]/.test(part)) { - part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); - } - return part; - }).join(""); -} -function encodeUnreserved(str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { - return "%" + c.charCodeAt(0).toString(16).toUpperCase(); - }); -} -function encodeValue(operator, value, key) { - value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); - if (key) { - return encodeUnreserved(key) + "=" + value; - } else { - return value; - } -} -function isDefined(value) { - return value !== void 0 && value !== null; -} -function isKeyOperator(operator) { - return operator === ";" || operator === "&" || operator === "?"; -} -function getValues(context3, operator, key, modifier) { - var value = context3[key], result = []; - if (isDefined(value) && value !== "") { - if (typeof value === "string" || typeof value === "number" || typeof value === "bigint" || typeof value === "boolean") { - value = value.toString(); - if (modifier && modifier !== "*") { - value = value.substring(0, parseInt(modifier, 10)); - } - result.push( - encodeValue(operator, value, isKeyOperator(operator) ? key : "") - ); - } else { - if (modifier === "*") { - if (Array.isArray(value)) { - value.filter(isDefined).forEach(function(value2) { - result.push( - encodeValue(operator, value2, isKeyOperator(operator) ? key : "") - ); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined(value[k])) { - result.push(encodeValue(operator, value[k], k)); - } - }); - } - } else { - const tmp = []; - if (Array.isArray(value)) { - value.filter(isDefined).forEach(function(value2) { - tmp.push(encodeValue(operator, value2)); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined(value[k])) { - tmp.push(encodeUnreserved(k)); - tmp.push(encodeValue(operator, value[k].toString())); - } - }); - } - if (isKeyOperator(operator)) { - result.push(encodeUnreserved(key) + "=" + tmp.join(",")); - } else if (tmp.length !== 0) { - result.push(tmp.join(",")); - } - } - } - } else { - if (operator === ";") { - if (isDefined(value)) { - result.push(encodeUnreserved(key)); - } - } else if (value === "" && (operator === "&" || operator === "?")) { - result.push(encodeUnreserved(key) + "="); - } else if (value === "") { - result.push(""); - } - } - return result; -} -function parseUrl(template) { - return { - expand: expand.bind(null, template) - }; -} -function expand(template, context3) { - var operators = ["+", "#", ".", "/", ";", "?", "&"]; - template = template.replace( - /\{([^\{\}]+)\}|([^\{\}]+)/g, - function(_, expression, literal) { - if (expression) { - let operator = ""; - const values = []; - if (operators.indexOf(expression.charAt(0)) !== -1) { - operator = expression.charAt(0); - expression = expression.substr(1); - } - expression.split(/,/g).forEach(function(variable) { - var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); - values.push(getValues(context3, operator, tmp[1], tmp[2] || tmp[3])); - }); - if (operator && operator !== "+") { - var separator = ","; - if (operator === "?") { - separator = "&"; - } else if (operator !== "#") { - separator = operator; - } - return (values.length !== 0 ? operator : "") + values.join(separator); - } else { - return values.join(","); - } - } else { - return encodeReserved(literal); - } - } - ); - if (template === "/") { - return template; - } else { - return template.replace(/\/$/, ""); - } -} -function parse(options) { - let method = options.method.toUpperCase(); - let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); - let headers = Object.assign({}, options.headers); - let body; - let parameters = omit(options, [ - "method", - "baseUrl", - "url", - "headers", - "request", - "mediaType" - ]); - const urlVariableNames = extractUrlVariableNames(url); - url = parseUrl(url).expand(parameters); - if (!/^http/.test(url)) { - url = options.baseUrl + url; - } - const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl"); - const remainingParameters = omit(parameters, omittedParameters); - const isBinaryRequest = /application\/octet-stream/i.test(headers.accept); - if (!isBinaryRequest) { - if (options.mediaType.format) { - headers.accept = headers.accept.split(/,/).map( - (format) => format.replace( - /application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, - `application/vnd$1$2.${options.mediaType.format}` - ) - ).join(","); - } - if (url.endsWith("/graphql")) { - if (options.mediaType.previews?.length) { - const previewsFromAcceptHeader = headers.accept.match(/(? { - const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; - return `application/vnd.github.${preview}-preview${format}`; - }).join(","); - } - } - } - if (["GET", "HEAD"].includes(method)) { - url = addQueryParameters(url, remainingParameters); - } else { - if ("data" in remainingParameters) { - body = remainingParameters.data; - } else { - if (Object.keys(remainingParameters).length) { - body = remainingParameters; - } - } - } - if (!headers["content-type"] && typeof body !== "undefined") { - headers["content-type"] = "application/json; charset=utf-8"; - } - if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { - body = ""; - } - return Object.assign( - { method, url, headers }, - typeof body !== "undefined" ? { body } : null, - options.request ? { request: options.request } : null - ); -} -function endpointWithDefaults(defaults2, route, options) { - return parse(merge(defaults2, route, options)); -} -function withDefaults(oldDefaults, newDefaults) { - const DEFAULTS2 = merge(oldDefaults, newDefaults); - const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2); - return Object.assign(endpoint2, { - DEFAULTS: DEFAULTS2, - defaults: withDefaults.bind(null, DEFAULTS2), - merge: merge.bind(null, DEFAULTS2), - parse - }); -} -var endpoint = withDefaults(null, DEFAULTS); - -// node_modules/@octokit/request/node_modules/content-type/dist/index.js -var NullObject = /* @__PURE__ */ (() => { - const C = function() { - }; - C.prototype = /* @__PURE__ */ Object.create(null); - return C; -})(); -function parse2(header, options) { - const stopChar = options?.comma === true ? COMMA : 65536; - const len = header.length; - let index = skipOWS(header, options?.start ?? 0, len); - const valueStart = index; - index = skipValue(header, index, len, stopChar); - const valueEnd = trailingOWS(header, valueStart, index); - const type = header.slice(valueStart, valueEnd).toLowerCase(); - if (options?.parameters === false) { - return { type, index, parameters: new NullObject() }; - } - return parseParameters(header, type, index, len, stopChar); -} -var SP = 32; -var HTAB = 9; -var SEMI = 59; -var EQ = 61; -var DQUOTE = 34; -var BSLASH = 92; -var COMMA = 44; -function parseParameters(header, type, index, len, stopChar) { - const parameters = new NullObject(); - parameter: while (index < len) { - if (header.charCodeAt(index) === stopChar) - break; - index = skipOWS(header, index + 1, len); - const keyStart = index; - while (index < len) { - const code = header.charCodeAt(index); - if (code === stopChar) - break parameter; - if (code === SEMI) - continue parameter; - if (code === EQ) { - const keyEnd = trailingOWS(header, keyStart, index); - const key = header.slice(keyStart, keyEnd).toLowerCase(); - index = skipOWS(header, index + 1, len); - if (index < len && header.charCodeAt(index) === DQUOTE) { - index++; - let value = ""; - while (index < len) { - const code2 = header.charCodeAt(index++); - if (code2 === DQUOTE) { - index = skipValue(header, index, len, stopChar); - if (parameters[key] === void 0) - parameters[key] = value; - break; - } - if (code2 === BSLASH && index < len) { - value += header[index++]; - continue; - } - value += String.fromCharCode(code2); - } - continue parameter; - } - const valueStart = index; - index = skipValue(header, index, len, stopChar); - if (parameters[key] === void 0) { - const valueEnd = trailingOWS(header, valueStart, index); - parameters[key] = header.slice(valueStart, valueEnd); - } - continue parameter; - } - index++; - } - } - return { type, index, parameters }; -} -function skipValue(str, index, len, stopChar) { - while (index < len) { - const code = str.charCodeAt(index); - if (code === SEMI || code === stopChar) - break; - index++; - } - return index; -} -function skipOWS(header, index, len) { - while (index < len) { - const char = header.charCodeAt(index); - if (char !== SP && char !== HTAB) - break; - index++; - } - return index; -} -function trailingOWS(header, start, end) { - while (end > start) { - const char = header.charCodeAt(end - 1); - if (char !== SP && char !== HTAB) - break; - end--; - } - return end; -} - -// node_modules/json-with-bigint/json-with-bigint.js -var intRegex = /^-?\d+$/; -var noiseValue = /^-?\d+n+$/; -var originalStringify = JSON.stringify; -var originalParse = JSON.parse; -var customFormat = /^-?\d+n$/; -var bigIntsStringify = /([\[:])?"(-?\d+)n"($|\s*[,\}\]])/g; -var noiseStringify = /([\[:])?("-?\d+n+)n("$|"\s*[,\}\]])/g; -var isUnstringifiable = (val) => val === void 0 || typeof val === "function" || typeof val === "symbol"; -var isRawJSON = (val) => val !== null && typeof val === "object" && val.constructor && val.constructor.name === "RawJSON"; -var stringifyIteratively = (rootValue, replacer, spaceParam) => { - let space = ""; - if (typeof spaceParam === "number") { - space = " ".repeat(Math.min(10, Math.max(0, Math.floor(spaceParam)))); - } else if (typeof spaceParam === "string") { - space = spaceParam.slice(0, 10); - } - const isFunctionReplacer = typeof replacer === "function"; - const propertyList = Array.isArray(replacer) ? new Set(replacer.map(String)) : null; - const prepareVal = (parent, key, val) => { - const isObject = val !== null && typeof val === "object"; - const hasToJSON = isObject && typeof val.toJSON === "function"; - if (hasToJSON) { - val = val.toJSON(key); - } - const isNoise = typeof val === "string" && noiseValue.test(val); - if (isNoise) return val + "n"; - const isBigInt = typeof val === "bigint"; - if (isBigInt) { - const supportsRawJSON = "rawJSON" in JSON; - if (supportsRawJSON) return JSON.rawJSON(val.toString()); - return val.toString() + "n"; - } - if (isFunctionReplacer) { - val = replacer.call(parent, key, val); - } - const isPostReplacerObject = val !== null && typeof val === "object"; - if (isPostReplacerObject) { - const isPrimitiveWrapper = val instanceof Number || val instanceof String || val instanceof Boolean; - if (isPrimitiveWrapper) { - val = val.valueOf(); - } - } - return val; - }; - const rootProcessed = prepareVal({ "": rootValue }, "", rootValue); - if (isUnstringifiable(rootProcessed)) { - return void 0; - } - const isRootPrimitive = rootProcessed === null || typeof rootProcessed !== "object"; - const isRootNativeRawJSON = isRawJSON(rootProcessed); - if (isRootPrimitive || isRootNativeRawJSON) { - return originalStringify(rootProcessed); - } - const chunks = []; - let level = 0; - const stack = [ - { - parent: { "": rootProcessed }, - key: "", - val: rootProcessed, - isArray: Array.isArray(rootProcessed), - keys: Array.isArray(rootProcessed) ? null : Object.keys(rootProcessed), - index: 0, - first: true - } - ]; - const visited = new WeakSet([rootProcessed]); - while (stack.length > 0) { - const node = stack[stack.length - 1]; - if (node.index === 0) { - chunks.push(node.isArray ? "[" : "{"); - level++; - } - let isDone = false; - if (node.isArray) { - if (node.index < node.val.length) { - if (!node.first) chunks.push(","); - if (space) chunks.push("\n" + space.repeat(level)); - const childRaw = node.val[node.index]; - const childVal = prepareVal(node.val, String(node.index), childRaw); - if (isUnstringifiable(childVal)) { - chunks.push("null"); - node.first = false; - node.index++; - } else { - const isComplexObject = childVal !== null && typeof childVal === "object"; - const isNativeRaw = isRawJSON(childVal); - if (isComplexObject && !isNativeRaw) { - if (visited.has(childVal)) { - throw new TypeError("Converting circular structure to JSON"); - } - visited.add(childVal); - stack.push({ - parent: node.val, - key: String(node.index), - val: childVal, - isArray: Array.isArray(childVal), - keys: Array.isArray(childVal) ? null : Object.keys(childVal), - index: 0, - first: true - }); - node.first = false; - node.index++; - } else { - chunks.push(originalStringify(childVal)); - node.first = false; - node.index++; - } - } - } else { - isDone = true; - } - } else { - while (node.index < node.keys.length) { - const k = node.keys[node.index++]; - const isFilteredOutByArray = propertyList && !propertyList.has(k); - if (isFilteredOutByArray) continue; - const childRaw = node.val[k]; - const childVal = prepareVal(node.val, k, childRaw); - if (isUnstringifiable(childVal)) continue; - if (!node.first) chunks.push(","); - if (space) { - chunks.push("\n" + space.repeat(level) + originalStringify(k) + ": "); - } else { - chunks.push(originalStringify(k) + ":"); - } - const isComplexObject = childVal !== null && typeof childVal === "object"; - const isNativeRaw = isRawJSON(childVal); - if (isComplexObject && !isNativeRaw) { - if (visited.has(childVal)) { - throw new TypeError("Converting circular structure to JSON"); - } - visited.add(childVal); - stack.push({ - parent: node.val, - key: k, - val: childVal, - isArray: Array.isArray(childVal), - keys: Array.isArray(childVal) ? null : Object.keys(childVal), - index: 0, - first: true - }); - node.first = false; - break; - } else { - chunks.push(originalStringify(childVal)); - node.first = false; - } - } - const isNodeFullyProcessed = node.index >= node.keys.length && stack[stack.length - 1] === node; - if (isNodeFullyProcessed) { - isDone = true; - } - } - if (isDone) { - level--; - if (!node.first && space) chunks.push("\n" + space.repeat(level)); - chunks.push(node.isArray ? "]" : "}"); - visited.delete(node.val); - stack.pop(); - } - } - return chunks.join(""); -}; -var JSONStringify = (value, replacer, space) => { - try { - const supportsRawJSON = "rawJSON" in JSON; - if (supportsRawJSON) { - return originalStringify( - value, - (key, val) => { - if (typeof val === "bigint") return JSON.rawJSON(val.toString()); - const hasFunctionReplacer = typeof replacer === "function"; - if (hasFunctionReplacer) return replacer(key, val); - const isKeyInArrayReplacer = Array.isArray(replacer) && replacer.includes(key); - if (isKeyInArrayReplacer) return val; - return val; - }, - space - ); - } - if (!value) return originalStringify(value, replacer, space); - const convertedToCustomJSON = originalStringify( - value, - (key, val) => { - const isNoise = typeof val === "string" && noiseValue.test(val); - if (isNoise) return val.toString() + "n"; - if (typeof val === "bigint") return val.toString() + "n"; - const hasFunctionReplacer = typeof replacer === "function"; - if (hasFunctionReplacer) return replacer(key, val); - const isKeyInArrayReplacer = Array.isArray(replacer) && replacer.includes(key); - if (isKeyInArrayReplacer) return val; - return val; - }, - space - ); - const processedJSON = convertedToCustomJSON.replace( - bigIntsStringify, - "$1$2$3" - ); - const denoisedJSON = processedJSON.replace(noiseStringify, "$1$2$3"); - return denoisedJSON; - } catch (error3) { - if (error3 instanceof RangeError) { - const convertedJSON = stringifyIteratively(value, replacer, space); - if (convertedJSON === void 0) return void 0; - const supportsRawJSON = "rawJSON" in JSON; - if (supportsRawJSON) return convertedJSON; - const processedJSON = convertedJSON.replace(bigIntsStringify, "$1$2$3"); - return processedJSON.replace(noiseStringify, "$1$2$3"); - } - throw error3; - } -}; -var featureCache = /* @__PURE__ */ new Map(); -var isContextSourceSupported = () => { - const parseFingerprint = JSON.parse.toString(); - if (featureCache.has(parseFingerprint)) { - return featureCache.get(parseFingerprint); - } - try { - const result = JSON.parse( - "1", - (_, __, context3) => !!context3?.source && context3.source === "1" - ); - featureCache.set(parseFingerprint, result); - return result; - } catch { - featureCache.set(parseFingerprint, false); - return false; - } -}; -var convertMarkedBigIntsReviver = (key, value, context3, userReviver) => { - const isCustomFormatBigInt = typeof value === "string" && customFormat.test(value); - if (isCustomFormatBigInt) return BigInt(value.slice(0, -1)); - const isNoiseValue = typeof value === "string" && noiseValue.test(value); - if (isNoiseValue) return value.slice(0, -1); - const hasUserReviver = typeof userReviver === "function"; - if (!hasUserReviver) return value; - return userReviver(key, value, context3); -}; -var JSONParseV2 = (text, reviver) => { - return JSON.parse(text, (key, value, context3) => { - const isNumber = typeof value === "number"; - const isOutOfBounds = value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER; - const isBigNumber = isNumber && isOutOfBounds; - const isInt = context3 && intRegex.test(context3.source); - const isBigInt = isBigNumber && isInt; - if (isBigInt) return BigInt(context3.source); - const hasCustomReviver = typeof reviver === "function"; - if (!hasCustomReviver) return value; - return reviver(key, value, context3); - }); -}; -var MAX_INT = Number.MAX_SAFE_INTEGER.toString(); -var MAX_DIGITS = MAX_INT.length; -var stringsOrLargeNumbers = /"(?:[^"\\]|\\.)*"|-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/g; -var noiseValueWithQuotes = /^"-?\d+n+"$/; -var applyReviverIteratively = (parsed, userReviver) => { - const rootHolder = { "": parsed }; - const stack = [{ parent: rootHolder, key: "", visited: false }]; - while (stack.length > 0) { - const node = stack[stack.length - 1]; - if (!node.visited) { - node.visited = true; - const value = node.parent[node.key]; - const isComplexObject = value !== null && typeof value === "object"; - if (isComplexObject) { - const keys = Object.keys(value); - for (let i = keys.length - 1; i >= 0; i--) { - stack.push({ parent: value, key: keys[i], visited: false }); - } - } - } else { - const { parent, key } = node; - let value = parent[key]; - if (typeof value === "string") { - const isCustomFormatBigInt = customFormat.test(value); - if (isCustomFormatBigInt) { - value = BigInt(value.slice(0, -1)); - } else { - const isNoise = noiseValue.test(value); - if (isNoise) value = value.slice(0, -1); - } - } - const hasUserReviver = typeof userReviver === "function"; - if (hasUserReviver) { - value = userReviver.call(parent, key, value); - } - const isDeleted = value === void 0; - if (isDeleted) { - delete parent[key]; - } else { - parent[key] = value; - } - stack.pop(); - } - } - return rootHolder[""]; -}; -var serializeBigInts = (text) => { - return text.replace( - stringsOrLargeNumbers, - (match, digits, fractional, exponential) => { - const isString = match[0] === '"'; - const isNoise = isString && noiseValueWithQuotes.test(match); - if (isNoise) return match.substring(0, match.length - 1) + 'n"'; - const hasFractionalOrExponential = fractional || exponential; - const isLessThanMaxSafeInt = digits && (digits.length < MAX_DIGITS || digits.length === MAX_DIGITS && digits <= MAX_INT); - const isStandardValue = isString || hasFractionalOrExponential || isLessThanMaxSafeInt; - if (isStandardValue) return match; - return '"' + match + 'n"'; - } - ); -}; -var JSONParse = (text, reviver) => { - if (!text) return originalParse(text, reviver); - try { - if (isContextSourceSupported()) return JSONParseV2(text, reviver); - const serializedData = serializeBigInts(text); - return originalParse( - serializedData, - (key, value, context3) => convertMarkedBigIntsReviver(key, value, context3, reviver) - ); - } catch (error3) { - if (error3 instanceof RangeError) { - const serializedData = serializeBigInts(text); - const parsed = originalParse(serializedData); - return applyReviverIteratively(parsed, reviver); - } - throw error3; - } -}; - -// node_modules/@octokit/request-error/dist-src/index.js -var RequestError = class extends Error { - name; - /** - * http status code - */ - status; - /** - * Request options that lead to the error. - */ - request; - /** - * Response object if a response was received - */ - response; - constructor(message, statusCode, options) { - super(message, { cause: options.cause }); - this.name = "HttpError"; - this.status = Number.parseInt(statusCode); - if (Number.isNaN(this.status)) { - this.status = 0; - } - if ("response" in options) { - this.response = options.response; - } - const requestCopy = Object.assign({}, options.request); - if (options.request.headers.authorization) { - requestCopy.headers = Object.assign({}, options.request.headers, { - authorization: options.request.headers.authorization.replace( - /(? ""; -async function fetchWrapper(requestOptions) { - const fetch3 = requestOptions.request?.fetch || globalThis.fetch; - if (!fetch3) { - throw new Error( - "fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing" - ); - } - const log = requestOptions.request?.log || console; - const parseSuccessResponseBody = requestOptions.request?.parseSuccessResponseBody !== false; - const body = isPlainObject2(requestOptions.body) || Array.isArray(requestOptions.body) ? JSONStringify(requestOptions.body) : requestOptions.body; - const requestHeaders = Object.fromEntries( - Object.entries(requestOptions.headers).map(([name, value]) => [ - name, - String(value) - ]) - ); - let fetchResponse; - try { - fetchResponse = await fetch3(requestOptions.url, { - method: requestOptions.method, - body, - redirect: requestOptions.request?.redirect, - headers: requestHeaders, - signal: requestOptions.request?.signal, - // duplex must be set if request.body is ReadableStream or Async Iterables. - // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex. - ...requestOptions.body && { duplex: "half" } - }); - } catch (error3) { - let message = "Unknown Error"; - if (error3 instanceof Error) { - if (error3.name === "AbortError") { - error3.status = 500; - throw error3; - } - message = error3.message; - if (error3.name === "TypeError" && "cause" in error3) { - if (error3.cause instanceof Error) { - message = error3.cause.message; - } else if (typeof error3.cause === "string") { - message = error3.cause; - } - } - } - const requestError = new RequestError(message, 500, { - request: requestOptions - }); - requestError.cause = error3; - throw requestError; - } - const status = fetchResponse.status; - const url = fetchResponse.url; - const responseHeaders = {}; - for (const [key, value] of fetchResponse.headers) { - responseHeaders[key] = value; - } - const octokitResponse = { - url, - status, - headers: responseHeaders, - data: "" - }; - if ("deprecation" in responseHeaders) { - const matches = responseHeaders.link && responseHeaders.link.match(/<([^<>]+)>; rel="deprecation"/); - const deprecationLink = matches && matches.pop(); - log.warn( - `[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${responseHeaders.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` - ); - } - if (status === 204 || status === 205) { - return octokitResponse; - } - if (requestOptions.method === "HEAD") { - if (status < 400) { - return octokitResponse; - } - throw new RequestError(fetchResponse.statusText, status, { - response: octokitResponse, - request: requestOptions - }); - } - if (status === 304) { - octokitResponse.data = await getResponseData(fetchResponse); - throw new RequestError("Not modified", status, { - response: octokitResponse, - request: requestOptions - }); - } - if (status >= 400) { - octokitResponse.data = await getResponseData(fetchResponse); - throw new RequestError(toErrorMessage(octokitResponse.data), status, { - response: octokitResponse, - request: requestOptions - }); - } - octokitResponse.data = parseSuccessResponseBody ? await getResponseData(fetchResponse) : fetchResponse.body; - return octokitResponse; -} -async function getResponseData(response) { - const contentType = response.headers.get("content-type"); - if (!contentType) { - return response.text().catch(noop); - } - const mimetype = parse2(contentType); - if (isJSONResponse(mimetype)) { - let text = ""; - try { - text = await response.text(); - return JSONParse(text); - } catch (err) { - return text; - } - } else if (mimetype.type.startsWith("text/") || // `application/octet-stream` is the canonical "arbitrary binary" type - // (RFC 2046) and must never be decoded as text, even when the response - // carries a (misleading) `charset=utf-8` parameter — see #751. - mimetype.parameters.charset?.toLowerCase() === "utf-8" && mimetype.type !== "application/octet-stream") { - return response.text().catch(noop); - } else { - return response.arrayBuffer().catch( - /* v8 ignore next -- @preserve */ - () => new ArrayBuffer(0) - ); - } -} -function isJSONResponse(mimetype) { - return mimetype.type === "application/json" || mimetype.type === "application/scim+json"; -} -function toErrorMessage(data) { - if (typeof data === "string") { - return data; - } - if (data instanceof ArrayBuffer) { - return "Unknown error"; - } - if (typeof data === "object" && data !== null && "message" in data) { - const objectData = data; - const suffix = "documentation_url" in objectData ? ` - ${objectData.documentation_url}` : ""; - return Array.isArray(objectData.errors) ? `${objectData.message}: ${objectData.errors.map((v) => JSON.stringify(v)).join(", ")}${suffix}` : `${objectData.message}${suffix}`; - } - return `Unknown error: ${JSON.stringify(data)}`; -} -function withDefaults2(oldEndpoint, newDefaults) { - const endpoint2 = oldEndpoint.defaults(newDefaults); - const newApi = function(route, parameters) { - const endpointOptions = endpoint2.merge(route, parameters); - if (!endpointOptions.request || !endpointOptions.request.hook) { - return fetchWrapper(endpoint2.parse(endpointOptions)); - } - const request2 = (route2, parameters2) => { - return fetchWrapper( - endpoint2.parse(endpoint2.merge(route2, parameters2)) - ); - }; - Object.assign(request2, { - endpoint: endpoint2, - defaults: withDefaults2.bind(null, endpoint2) - }); - return endpointOptions.request.hook(request2, endpointOptions); - }; - return Object.assign(newApi, { - endpoint: endpoint2, - defaults: withDefaults2.bind(null, endpoint2) - }); -} -var request = withDefaults2(endpoint, defaults_default); - -// node_modules/@octokit/graphql/dist-bundle/index.js -var VERSION3 = "0.0.0-development"; -function _buildMessageForResponseErrors(data) { - return `Request failed due to following response errors: -` + data.errors.map((e) => ` - ${e.message}`).join("\n"); -} -var GraphqlResponseError = class extends Error { - constructor(request2, headers, response) { - super(_buildMessageForResponseErrors(response)); - this.request = request2; - this.headers = headers; - this.response = response; - this.errors = response.errors; - this.data = response.data; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - } - request; - headers; - response; - name = "GraphqlResponseError"; - errors; - data; -}; -var NON_VARIABLE_OPTIONS = [ - "method", - "baseUrl", - "url", - "headers", - "request", - "query", - "mediaType", - "operationName" -]; -var FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"]; -var GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; -function graphql(request2, query, options) { - if (options) { - if (typeof query === "string" && "query" in options) { - return Promise.reject( - new Error(`[@octokit/graphql] "query" cannot be used as variable name`) - ); - } - for (const key in options) { - if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue; - return Promise.reject( - new Error( - `[@octokit/graphql] "${key}" cannot be used as variable name` - ) - ); - } - } - const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query; - const requestOptions = Object.keys( - parsedOptions - ).reduce((result, key) => { - if (NON_VARIABLE_OPTIONS.includes(key)) { - result[key] = parsedOptions[key]; - return result; - } - if (!result.variables) { - result.variables = {}; - } - result.variables[key] = parsedOptions[key]; - return result; - }, {}); - const baseUrl2 = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl; - if (GHES_V3_SUFFIX_REGEX.test(baseUrl2)) { - requestOptions.url = baseUrl2.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql"); - } - return request2(requestOptions).then((response) => { - if (response.data.errors) { - const headers = {}; - for (const key of Object.keys(response.headers)) { - headers[key] = response.headers[key]; - } - throw new GraphqlResponseError( - requestOptions, - headers, - response.data - ); - } - return response.data.data; - }); -} -function withDefaults3(request2, newDefaults) { - const newRequest = request2.defaults(newDefaults); - const newApi = (query, options) => { - return graphql(newRequest, query, options); - }; - return Object.assign(newApi, { - defaults: withDefaults3.bind(null, newRequest), - endpoint: newRequest.endpoint - }); -} -var graphql2 = withDefaults3(request, { - headers: { - "user-agent": `octokit-graphql.js/${VERSION3} ${getUserAgent()}` - }, - method: "POST", - url: "/graphql" -}); -function withCustomRequest(customRequest) { - return withDefaults3(customRequest, { - method: "POST", - url: "/graphql" - }); -} - -// node_modules/@octokit/auth-token/dist-bundle/index.js -var b64url = "(?:[a-zA-Z0-9_-]+)"; -var sep = "\\."; -var jwtRE = new RegExp(`^${b64url}${sep}${b64url}${sep}${b64url}$`); -var isJWT = jwtRE.test.bind(jwtRE); -async function auth(token) { - const isApp = isJWT(token); - const isInstallation = token.startsWith("v1.") || token.startsWith("ghs_"); - const isUserToServer = token.startsWith("ghu_"); - const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth"; - return { - type: "token", - token, - tokenType - }; -} -function withAuthorizationPrefix(token) { - if (token.split(/\./).length === 3) { - return `bearer ${token}`; - } - return `token ${token}`; -} -async function hook(token, request2, route, parameters) { - const endpoint2 = request2.endpoint.merge( - route, - parameters - ); - endpoint2.headers.authorization = withAuthorizationPrefix(token); - return request2(endpoint2); -} -var createTokenAuth = function createTokenAuth2(token) { - if (!token) { - throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); - } - if (typeof token !== "string") { - throw new Error( - "[@octokit/auth-token] Token passed to createTokenAuth is not a string" - ); - } - token = token.replace(/^(token|bearer) +/i, ""); - return Object.assign(auth.bind(null, token), { - hook: hook.bind(null, token) - }); -}; - -// node_modules/@octokit/core/dist-src/version.js -var VERSION4 = "7.0.7"; - -// node_modules/@octokit/core/dist-src/index.js -var noop2 = () => { -}; -var consoleWarn = console.warn.bind(console); -var consoleError = console.error.bind(console); -function createLogger(logger = {}) { - if (typeof logger.debug !== "function") { - logger.debug = noop2; - } - if (typeof logger.info !== "function") { - logger.info = noop2; - } - if (typeof logger.warn !== "function") { - logger.warn = consoleWarn; - } - if (typeof logger.error !== "function") { - logger.error = consoleError; - } - return logger; -} -var userAgentTrail = `octokit-core.js/${VERSION4} ${getUserAgent()}`; -var Octokit = class { - static VERSION = VERSION4; - static defaults(defaults2) { - const OctokitWithDefaults = class extends this { - constructor(...args) { - const options = args[0] || {}; - if (typeof defaults2 === "function") { - super(defaults2(options)); - return; - } - super( - Object.assign( - {}, - defaults2, - options, - options.userAgent && defaults2.userAgent ? { - userAgent: `${options.userAgent} ${defaults2.userAgent}` - } : null - ) - ); - } - }; - return OctokitWithDefaults; - } - static plugins = []; - /** - * Attach a plugin (or many) to your Octokit instance. - * - * @example - * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) - */ - static plugin(...newPlugins) { - const currentPlugins = this.plugins; - const NewOctokit = class extends this { - static plugins = currentPlugins.concat( - newPlugins.filter((plugin) => !currentPlugins.includes(plugin)) - ); - }; - return NewOctokit; - } - constructor(options = {}) { - const hook2 = new before_after_hook_default.Collection(); - const requestDefaults = { - baseUrl: request.endpoint.DEFAULTS.baseUrl, - headers: {}, - request: Object.assign({}, options.request, { - // @ts-ignore internal usage only, no need to type - hook: hook2.bind(null, "request") - }), - mediaType: { - previews: [], - format: "" - } - }; - requestDefaults.headers["user-agent"] = options.userAgent ? `${options.userAgent} ${userAgentTrail}` : userAgentTrail; - if (options.baseUrl) { - requestDefaults.baseUrl = options.baseUrl; - } - if (options.previews) { - requestDefaults.mediaType.previews = options.previews; - } - if (options.timeZone) { - requestDefaults.headers["time-zone"] = options.timeZone; - } - this.request = request.defaults(requestDefaults); - this.graphql = withCustomRequest(this.request).defaults(requestDefaults); - this.log = createLogger(options.log); - this.hook = hook2; - if (!options.authStrategy) { - if (!options.auth) { - this.auth = async () => ({ - type: "unauthenticated" - }); - } else { - const auth2 = createTokenAuth(options.auth); - hook2.wrap("request", auth2.hook); - this.auth = auth2; - } - } else { - const { authStrategy, ...otherOptions } = options; - const auth2 = authStrategy( - Object.assign( - { - request: this.request, - log: this.log, - // we pass the current octokit instance as well as its constructor options - // to allow for authentication strategies that return a new octokit instance - // that shares the same internal state as the current one. The original - // requirement for this was the "event-octokit" authentication strategy - // of https://github.com/probot/octokit-auth-probot. - octokit: this, - octokitOptions: otherOptions - }, - options.auth - ) - ); - hook2.wrap("request", auth2.hook); - this.auth = auth2; - } - const classConstructor = this.constructor; - for (let i = 0; i < classConstructor.plugins.length; ++i) { - Object.assign(this, classConstructor.plugins[i](this, options)); - } - } - // assigned during constructor - request; - graphql; - log; - hook; - // TODO: type `octokit.auth` based on passed options.authStrategy - auth; -}; - -// node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/version.js -var VERSION5 = "17.0.0"; - -// node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/generated/endpoints.js -var Endpoints = { - actions: { - addCustomLabelsToSelfHostedRunnerForOrg: [ - "POST /orgs/{org}/actions/runners/{runner_id}/labels" - ], - addCustomLabelsToSelfHostedRunnerForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - addRepoAccessToSelfHostedRunnerGroupInOrg: [ - "PUT /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories/{repository_id}" - ], - addSelectedRepoToOrgSecret: [ - "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" - ], - addSelectedRepoToOrgVariable: [ - "PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" - ], - approveWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve" - ], - cancelWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel" - ], - createEnvironmentVariable: [ - "POST /repos/{owner}/{repo}/environments/{environment_name}/variables" - ], - createHostedRunnerForOrg: ["POST /orgs/{org}/actions/hosted-runners"], - createOrUpdateEnvironmentSecret: [ - "PUT /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}" - ], - createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], - createOrUpdateRepoSecret: [ - "PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}" - ], - createOrgVariable: ["POST /orgs/{org}/actions/variables"], - createRegistrationTokenForOrg: [ - "POST /orgs/{org}/actions/runners/registration-token" - ], - createRegistrationTokenForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/registration-token" - ], - createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], - createRemoveTokenForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/remove-token" - ], - createRepoVariable: ["POST /repos/{owner}/{repo}/actions/variables"], - createWorkflowDispatch: [ - "POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches" - ], - deleteActionsCacheById: [ - "DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}" - ], - deleteActionsCacheByKey: [ - "DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}" - ], - deleteArtifact: [ - "DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}" - ], - deleteCustomImageFromOrg: [ - "DELETE /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}" - ], - deleteCustomImageVersionFromOrg: [ - "DELETE /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions/{version}" - ], - deleteEnvironmentSecret: [ - "DELETE /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}" - ], - deleteEnvironmentVariable: [ - "DELETE /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}" - ], - deleteHostedRunnerForOrg: [ - "DELETE /orgs/{org}/actions/hosted-runners/{hosted_runner_id}" - ], - deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"], - deleteOrgVariable: ["DELETE /orgs/{org}/actions/variables/{name}"], - deleteRepoSecret: [ - "DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}" - ], - deleteRepoVariable: [ - "DELETE /repos/{owner}/{repo}/actions/variables/{name}" - ], - deleteSelfHostedRunnerFromOrg: [ - "DELETE /orgs/{org}/actions/runners/{runner_id}" - ], - deleteSelfHostedRunnerFromRepo: [ - "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}" - ], - deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"], - deleteWorkflowRunLogs: [ - "DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs" - ], - disableSelectedRepositoryGithubActionsOrganization: [ - "DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}" - ], - disableWorkflow: [ - "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable" - ], - downloadArtifact: [ - "GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}" - ], - downloadJobLogsForWorkflowRun: [ - "GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs" - ], - downloadWorkflowRunAttemptLogs: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs" - ], - downloadWorkflowRunLogs: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs" - ], - enableSelectedRepositoryGithubActionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/repositories/{repository_id}" - ], - enableWorkflow: [ - "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable" - ], - forceCancelWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel" - ], - generateRunnerJitconfigForOrg: [ - "POST /orgs/{org}/actions/runners/generate-jitconfig" - ], - generateRunnerJitconfigForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig" - ], - getActionsCacheList: ["GET /repos/{owner}/{repo}/actions/caches"], - getActionsCacheUsage: ["GET /repos/{owner}/{repo}/actions/cache/usage"], - getActionsCacheUsageByRepoForOrg: [ - "GET /orgs/{org}/actions/cache/usage-by-repository" - ], - getActionsCacheUsageForOrg: ["GET /orgs/{org}/actions/cache/usage"], - getAllowedActionsOrganization: [ - "GET /orgs/{org}/actions/permissions/selected-actions" - ], - getAllowedActionsRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions/selected-actions" - ], - getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], - getCustomImageForOrg: [ - "GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}" - ], - getCustomImageVersionForOrg: [ - "GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions/{version}" - ], - getCustomOidcSubClaimForRepo: [ - "GET /repos/{owner}/{repo}/actions/oidc/customization/sub" - ], - getEnvironmentPublicKey: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/public-key" - ], - getEnvironmentSecret: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}" - ], - getEnvironmentVariable: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}" - ], - getGithubActionsDefaultWorkflowPermissionsOrganization: [ - "GET /orgs/{org}/actions/permissions/workflow" - ], - getGithubActionsDefaultWorkflowPermissionsRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions/workflow" - ], - getGithubActionsPermissionsOrganization: [ - "GET /orgs/{org}/actions/permissions" - ], - getGithubActionsPermissionsRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions" - ], - getHostedRunnerForOrg: [ - "GET /orgs/{org}/actions/hosted-runners/{hosted_runner_id}" - ], - getHostedRunnersGithubOwnedImagesForOrg: [ - "GET /orgs/{org}/actions/hosted-runners/images/github-owned" - ], - getHostedRunnersLimitsForOrg: [ - "GET /orgs/{org}/actions/hosted-runners/limits" - ], - getHostedRunnersMachineSpecsForOrg: [ - "GET /orgs/{org}/actions/hosted-runners/machine-sizes" - ], - getHostedRunnersPartnerImagesForOrg: [ - "GET /orgs/{org}/actions/hosted-runners/images/partner" - ], - getHostedRunnersPlatformsForOrg: [ - "GET /orgs/{org}/actions/hosted-runners/platforms" - ], - getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"], - getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"], - getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"], - getOrgVariable: ["GET /orgs/{org}/actions/variables/{name}"], - getPendingDeploymentsForRun: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" - ], - getRepoPermissions: [ - "GET /repos/{owner}/{repo}/actions/permissions", - {}, - { renamed: ["actions", "getGithubActionsPermissionsRepository"] } - ], - getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"], - getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"], - getRepoVariable: ["GET /repos/{owner}/{repo}/actions/variables/{name}"], - getReviewsForRun: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals" - ], - getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"], - getSelfHostedRunnerForRepo: [ - "GET /repos/{owner}/{repo}/actions/runners/{runner_id}" - ], - getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"], - getWorkflowAccessToRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions/access" - ], - getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"], - getWorkflowRunAttempt: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}" - ], - getWorkflowRunUsage: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing" - ], - getWorkflowUsage: [ - "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing" - ], - listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"], - listCustomImageVersionsForOrg: [ - "GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions" - ], - listCustomImagesForOrg: [ - "GET /orgs/{org}/actions/hosted-runners/images/custom" - ], - listEnvironmentSecrets: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/secrets" - ], - listEnvironmentVariables: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/variables" - ], - listGithubHostedRunnersInGroupForOrg: [ - "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/hosted-runners" - ], - listHostedRunnersForOrg: ["GET /orgs/{org}/actions/hosted-runners"], - listJobsForWorkflowRun: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs" - ], - listJobsForWorkflowRunAttempt: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs" - ], - listLabelsForSelfHostedRunnerForOrg: [ - "GET /orgs/{org}/actions/runners/{runner_id}/labels" - ], - listLabelsForSelfHostedRunnerForRepo: [ - "GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - listOrgSecrets: ["GET /orgs/{org}/actions/secrets"], - listOrgVariables: ["GET /orgs/{org}/actions/variables"], - listRepoOrganizationSecrets: [ - "GET /repos/{owner}/{repo}/actions/organization-secrets" - ], - listRepoOrganizationVariables: [ - "GET /repos/{owner}/{repo}/actions/organization-variables" - ], - listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"], - listRepoVariables: ["GET /repos/{owner}/{repo}/actions/variables"], - listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"], - listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"], - listRunnerApplicationsForRepo: [ - "GET /repos/{owner}/{repo}/actions/runners/downloads" - ], - listSelectedReposForOrgSecret: [ - "GET /orgs/{org}/actions/secrets/{secret_name}/repositories" - ], - listSelectedReposForOrgVariable: [ - "GET /orgs/{org}/actions/variables/{name}/repositories" - ], - listSelectedRepositoriesEnabledGithubActionsOrganization: [ - "GET /orgs/{org}/actions/permissions/repositories" - ], - listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"], - listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"], - listWorkflowRunArtifacts: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts" - ], - listWorkflowRuns: [ - "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs" - ], - listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"], - reRunJobForWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun" - ], - reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"], - reRunWorkflowFailedJobs: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs" - ], - removeAllCustomLabelsFromSelfHostedRunnerForOrg: [ - "DELETE /orgs/{org}/actions/runners/{runner_id}/labels" - ], - removeAllCustomLabelsFromSelfHostedRunnerForRepo: [ - "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - removeCustomLabelFromSelfHostedRunnerForOrg: [ - "DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}" - ], - removeCustomLabelFromSelfHostedRunnerForRepo: [ - "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}" - ], - removeSelectedRepoFromOrgSecret: [ - "DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" - ], - removeSelectedRepoFromOrgVariable: [ - "DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" - ], - reviewCustomGatesForRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule" - ], - reviewPendingDeploymentsForRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" - ], - setAllowedActionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/selected-actions" - ], - setAllowedActionsRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions/selected-actions" - ], - setCustomLabelsForSelfHostedRunnerForOrg: [ - "PUT /orgs/{org}/actions/runners/{runner_id}/labels" - ], - setCustomLabelsForSelfHostedRunnerForRepo: [ - "PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - setCustomOidcSubClaimForRepo: [ - "PUT /repos/{owner}/{repo}/actions/oidc/customization/sub" - ], - setGithubActionsDefaultWorkflowPermissionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/workflow" - ], - setGithubActionsDefaultWorkflowPermissionsRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions/workflow" - ], - setGithubActionsPermissionsOrganization: [ - "PUT /orgs/{org}/actions/permissions" - ], - setGithubActionsPermissionsRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions" - ], - setSelectedReposForOrgSecret: [ - "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories" - ], - setSelectedReposForOrgVariable: [ - "PUT /orgs/{org}/actions/variables/{name}/repositories" - ], - setSelectedRepositoriesEnabledGithubActionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/repositories" - ], - setWorkflowAccessToRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions/access" - ], - updateEnvironmentVariable: [ - "PATCH /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}" - ], - updateHostedRunnerForOrg: [ - "PATCH /orgs/{org}/actions/hosted-runners/{hosted_runner_id}" - ], - updateOrgVariable: ["PATCH /orgs/{org}/actions/variables/{name}"], - updateRepoVariable: [ - "PATCH /repos/{owner}/{repo}/actions/variables/{name}" - ] - }, - activity: { - checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"], - deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"], - deleteThreadSubscription: [ - "DELETE /notifications/threads/{thread_id}/subscription" - ], - getFeeds: ["GET /feeds"], - getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"], - getThread: ["GET /notifications/threads/{thread_id}"], - getThreadSubscriptionForAuthenticatedUser: [ - "GET /notifications/threads/{thread_id}/subscription" - ], - listEventsForAuthenticatedUser: ["GET /users/{username}/events"], - listNotificationsForAuthenticatedUser: ["GET /notifications"], - listOrgEventsForAuthenticatedUser: [ - "GET /users/{username}/events/orgs/{org}" - ], - listPublicEvents: ["GET /events"], - listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"], - listPublicEventsForUser: ["GET /users/{username}/events/public"], - listPublicOrgEvents: ["GET /orgs/{org}/events"], - listReceivedEventsForUser: ["GET /users/{username}/received_events"], - listReceivedPublicEventsForUser: [ - "GET /users/{username}/received_events/public" - ], - listRepoEvents: ["GET /repos/{owner}/{repo}/events"], - listRepoNotificationsForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/notifications" - ], - listReposStarredByAuthenticatedUser: ["GET /user/starred"], - listReposStarredByUser: ["GET /users/{username}/starred"], - listReposWatchedByUser: ["GET /users/{username}/subscriptions"], - listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"], - listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"], - listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"], - markNotificationsAsRead: ["PUT /notifications"], - markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"], - markThreadAsDone: ["DELETE /notifications/threads/{thread_id}"], - markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"], - setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"], - setThreadSubscription: [ - "PUT /notifications/threads/{thread_id}/subscription" - ], - starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"], - unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"] - }, - apps: { - addRepoToInstallation: [ - "PUT /user/installations/{installation_id}/repositories/{repository_id}", - {}, - { renamed: ["apps", "addRepoToInstallationForAuthenticatedUser"] } - ], - addRepoToInstallationForAuthenticatedUser: [ - "PUT /user/installations/{installation_id}/repositories/{repository_id}" - ], - checkToken: ["POST /applications/{client_id}/token"], - createFromManifest: ["POST /app-manifests/{code}/conversions"], - createInstallationAccessToken: [ - "POST /app/installations/{installation_id}/access_tokens" - ], - deleteAuthorization: ["DELETE /applications/{client_id}/grant"], - deleteInstallation: ["DELETE /app/installations/{installation_id}"], - deleteToken: ["DELETE /applications/{client_id}/token"], - getAuthenticated: ["GET /app"], - getBySlug: ["GET /apps/{app_slug}"], - getInstallation: ["GET /app/installations/{installation_id}"], - getOrgInstallation: ["GET /orgs/{org}/installation"], - getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"], - getSubscriptionPlanForAccount: [ - "GET /marketplace_listing/accounts/{account_id}" - ], - getSubscriptionPlanForAccountStubbed: [ - "GET /marketplace_listing/stubbed/accounts/{account_id}" - ], - getUserInstallation: ["GET /users/{username}/installation"], - getWebhookConfigForApp: ["GET /app/hook/config"], - getWebhookDelivery: ["GET /app/hook/deliveries/{delivery_id}"], - listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"], - listAccountsForPlanStubbed: [ - "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts" - ], - listInstallationReposForAuthenticatedUser: [ - "GET /user/installations/{installation_id}/repositories" - ], - listInstallationRequestsForAuthenticatedApp: [ - "GET /app/installation-requests" - ], - listInstallations: ["GET /app/installations"], - listInstallationsForAuthenticatedUser: ["GET /user/installations"], - listPlans: ["GET /marketplace_listing/plans"], - listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"], - listReposAccessibleToInstallation: ["GET /installation/repositories"], - listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"], - listSubscriptionsForAuthenticatedUserStubbed: [ - "GET /user/marketplace_purchases/stubbed" - ], - listWebhookDeliveries: ["GET /app/hook/deliveries"], - redeliverWebhookDelivery: [ - "POST /app/hook/deliveries/{delivery_id}/attempts" - ], - removeRepoFromInstallation: [ - "DELETE /user/installations/{installation_id}/repositories/{repository_id}", - {}, - { renamed: ["apps", "removeRepoFromInstallationForAuthenticatedUser"] } - ], - removeRepoFromInstallationForAuthenticatedUser: [ - "DELETE /user/installations/{installation_id}/repositories/{repository_id}" - ], - resetToken: ["PATCH /applications/{client_id}/token"], - revokeInstallationAccessToken: ["DELETE /installation/token"], - scopeToken: ["POST /applications/{client_id}/token/scoped"], - suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"], - unsuspendInstallation: [ - "DELETE /app/installations/{installation_id}/suspended" - ], - updateWebhookConfigForApp: ["PATCH /app/hook/config"] - }, - billing: { - getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"], - getGithubActionsBillingUser: [ - "GET /users/{username}/settings/billing/actions" - ], - getGithubBillingPremiumRequestUsageReportOrg: [ - "GET /organizations/{org}/settings/billing/premium_request/usage" - ], - getGithubBillingPremiumRequestUsageReportUser: [ - "GET /users/{username}/settings/billing/premium_request/usage" - ], - getGithubBillingUsageReportOrg: [ - "GET /organizations/{org}/settings/billing/usage" - ], - getGithubBillingUsageReportUser: [ - "GET /users/{username}/settings/billing/usage" - ], - getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"], - getGithubPackagesBillingUser: [ - "GET /users/{username}/settings/billing/packages" - ], - getSharedStorageBillingOrg: [ - "GET /orgs/{org}/settings/billing/shared-storage" - ], - getSharedStorageBillingUser: [ - "GET /users/{username}/settings/billing/shared-storage" - ] - }, - campaigns: { - createCampaign: ["POST /orgs/{org}/campaigns"], - deleteCampaign: ["DELETE /orgs/{org}/campaigns/{campaign_number}"], - getCampaignSummary: ["GET /orgs/{org}/campaigns/{campaign_number}"], - listOrgCampaigns: ["GET /orgs/{org}/campaigns"], - updateCampaign: ["PATCH /orgs/{org}/campaigns/{campaign_number}"] - }, - checks: { - create: ["POST /repos/{owner}/{repo}/check-runs"], - createSuite: ["POST /repos/{owner}/{repo}/check-suites"], - get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"], - getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"], - listAnnotations: [ - "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations" - ], - listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"], - listForSuite: [ - "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs" - ], - listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"], - rerequestRun: [ - "POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest" - ], - rerequestSuite: [ - "POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest" - ], - setSuitesPreferences: [ - "PATCH /repos/{owner}/{repo}/check-suites/preferences" - ], - update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"] - }, - codeScanning: { - commitAutofix: [ - "POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix/commits" - ], - createAutofix: [ - "POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix" - ], - createVariantAnalysis: [ - "POST /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses" - ], - deleteAnalysis: [ - "DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}" - ], - deleteCodeqlDatabase: [ - "DELETE /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}" - ], - getAlert: [ - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", - {}, - { renamedParameters: { alert_id: "alert_number" } } - ], - getAnalysis: [ - "GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}" - ], - getAutofix: [ - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix" - ], - getCodeqlDatabase: [ - "GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}" - ], - getDefaultSetup: ["GET /repos/{owner}/{repo}/code-scanning/default-setup"], - getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"], - getVariantAnalysis: [ - "GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}" - ], - getVariantAnalysisRepoTask: [ - "GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}/repos/{repo_owner}/{repo_name}" - ], - listAlertInstances: [ - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances" - ], - listAlertsForOrg: ["GET /orgs/{org}/code-scanning/alerts"], - listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"], - listAlertsInstances: [ - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", - {}, - { renamed: ["codeScanning", "listAlertInstances"] } - ], - listCodeqlDatabases: [ - "GET /repos/{owner}/{repo}/code-scanning/codeql/databases" - ], - listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"], - updateAlert: [ - "PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}" - ], - updateDefaultSetup: [ - "PATCH /repos/{owner}/{repo}/code-scanning/default-setup" - ], - uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"] - }, - codeSecurity: { - attachConfiguration: [ - "POST /orgs/{org}/code-security/configurations/{configuration_id}/attach" - ], - attachEnterpriseConfiguration: [ - "POST /enterprises/{enterprise}/code-security/configurations/{configuration_id}/attach" - ], - createConfiguration: ["POST /orgs/{org}/code-security/configurations"], - createConfigurationForEnterprise: [ - "POST /enterprises/{enterprise}/code-security/configurations" - ], - deleteConfiguration: [ - "DELETE /orgs/{org}/code-security/configurations/{configuration_id}" - ], - deleteConfigurationForEnterprise: [ - "DELETE /enterprises/{enterprise}/code-security/configurations/{configuration_id}" - ], - detachConfiguration: [ - "DELETE /orgs/{org}/code-security/configurations/detach" - ], - getConfiguration: [ - "GET /orgs/{org}/code-security/configurations/{configuration_id}" - ], - getConfigurationForRepository: [ - "GET /repos/{owner}/{repo}/code-security-configuration" - ], - getConfigurationsForEnterprise: [ - "GET /enterprises/{enterprise}/code-security/configurations" - ], - getConfigurationsForOrg: ["GET /orgs/{org}/code-security/configurations"], - getDefaultConfigurations: [ - "GET /orgs/{org}/code-security/configurations/defaults" - ], - getDefaultConfigurationsForEnterprise: [ - "GET /enterprises/{enterprise}/code-security/configurations/defaults" - ], - getRepositoriesForConfiguration: [ - "GET /orgs/{org}/code-security/configurations/{configuration_id}/repositories" - ], - getRepositoriesForEnterpriseConfiguration: [ - "GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}/repositories" - ], - getSingleConfigurationForEnterprise: [ - "GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}" - ], - setConfigurationAsDefault: [ - "PUT /orgs/{org}/code-security/configurations/{configuration_id}/defaults" - ], - setConfigurationAsDefaultForEnterprise: [ - "PUT /enterprises/{enterprise}/code-security/configurations/{configuration_id}/defaults" - ], - updateConfiguration: [ - "PATCH /orgs/{org}/code-security/configurations/{configuration_id}" - ], - updateEnterpriseConfiguration: [ - "PATCH /enterprises/{enterprise}/code-security/configurations/{configuration_id}" - ] - }, - codesOfConduct: { - getAllCodesOfConduct: ["GET /codes_of_conduct"], - getConductCode: ["GET /codes_of_conduct/{key}"] - }, - codespaces: { - addRepositoryForSecretForAuthenticatedUser: [ - "PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - addSelectedRepoToOrgSecret: [ - "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - checkPermissionsForDevcontainer: [ - "GET /repos/{owner}/{repo}/codespaces/permissions_check" - ], - codespaceMachinesForAuthenticatedUser: [ - "GET /user/codespaces/{codespace_name}/machines" - ], - createForAuthenticatedUser: ["POST /user/codespaces"], - createOrUpdateOrgSecret: [ - "PUT /orgs/{org}/codespaces/secrets/{secret_name}" - ], - createOrUpdateRepoSecret: [ - "PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" - ], - createOrUpdateSecretForAuthenticatedUser: [ - "PUT /user/codespaces/secrets/{secret_name}" - ], - createWithPrForAuthenticatedUser: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces" - ], - createWithRepoForAuthenticatedUser: [ - "POST /repos/{owner}/{repo}/codespaces" - ], - deleteForAuthenticatedUser: ["DELETE /user/codespaces/{codespace_name}"], - deleteFromOrganization: [ - "DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}" - ], - deleteOrgSecret: ["DELETE /orgs/{org}/codespaces/secrets/{secret_name}"], - deleteRepoSecret: [ - "DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" - ], - deleteSecretForAuthenticatedUser: [ - "DELETE /user/codespaces/secrets/{secret_name}" - ], - exportForAuthenticatedUser: [ - "POST /user/codespaces/{codespace_name}/exports" - ], - getCodespacesForUserInOrg: [ - "GET /orgs/{org}/members/{username}/codespaces" - ], - getExportDetailsForAuthenticatedUser: [ - "GET /user/codespaces/{codespace_name}/exports/{export_id}" - ], - getForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}"], - getOrgPublicKey: ["GET /orgs/{org}/codespaces/secrets/public-key"], - getOrgSecret: ["GET /orgs/{org}/codespaces/secrets/{secret_name}"], - getPublicKeyForAuthenticatedUser: [ - "GET /user/codespaces/secrets/public-key" - ], - getRepoPublicKey: [ - "GET /repos/{owner}/{repo}/codespaces/secrets/public-key" - ], - getRepoSecret: [ - "GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" - ], - getSecretForAuthenticatedUser: [ - "GET /user/codespaces/secrets/{secret_name}" - ], - listDevcontainersInRepositoryForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces/devcontainers" - ], - listForAuthenticatedUser: ["GET /user/codespaces"], - listInOrganization: [ - "GET /orgs/{org}/codespaces", - {}, - { renamedParameters: { org_id: "org" } } - ], - listInRepositoryForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces" - ], - listOrgSecrets: ["GET /orgs/{org}/codespaces/secrets"], - listRepoSecrets: ["GET /repos/{owner}/{repo}/codespaces/secrets"], - listRepositoriesForSecretForAuthenticatedUser: [ - "GET /user/codespaces/secrets/{secret_name}/repositories" - ], - listSecretsForAuthenticatedUser: ["GET /user/codespaces/secrets"], - listSelectedReposForOrgSecret: [ - "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories" - ], - preFlightWithRepoForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces/new" - ], - publishForAuthenticatedUser: [ - "POST /user/codespaces/{codespace_name}/publish" - ], - removeRepositoryForSecretForAuthenticatedUser: [ - "DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - removeSelectedRepoFromOrgSecret: [ - "DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - repoMachinesForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces/machines" - ], - setRepositoriesForSecretForAuthenticatedUser: [ - "PUT /user/codespaces/secrets/{secret_name}/repositories" - ], - setSelectedReposForOrgSecret: [ - "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories" - ], - startForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/start"], - stopForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/stop"], - stopInOrganization: [ - "POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop" - ], - updateForAuthenticatedUser: ["PATCH /user/codespaces/{codespace_name}"] - }, - copilot: { - addCopilotSeatsForTeams: [ - "POST /orgs/{org}/copilot/billing/selected_teams" - ], - addCopilotSeatsForUsers: [ - "POST /orgs/{org}/copilot/billing/selected_users" - ], - cancelCopilotSeatAssignmentForTeams: [ - "DELETE /orgs/{org}/copilot/billing/selected_teams" - ], - cancelCopilotSeatAssignmentForUsers: [ - "DELETE /orgs/{org}/copilot/billing/selected_users" - ], - copilotMetricsForOrganization: ["GET /orgs/{org}/copilot/metrics"], - copilotMetricsForTeam: ["GET /orgs/{org}/team/{team_slug}/copilot/metrics"], - getCopilotOrganizationDetails: ["GET /orgs/{org}/copilot/billing"], - getCopilotSeatDetailsForUser: [ - "GET /orgs/{org}/members/{username}/copilot" - ], - listCopilotSeats: ["GET /orgs/{org}/copilot/billing/seats"] - }, - credentials: { revoke: ["POST /credentials/revoke"] }, - dependabot: { - addSelectedRepoToOrgSecret: [ - "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" - ], - createOrUpdateOrgSecret: [ - "PUT /orgs/{org}/dependabot/secrets/{secret_name}" - ], - createOrUpdateRepoSecret: [ - "PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" - ], - deleteOrgSecret: ["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"], - deleteRepoSecret: [ - "DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" - ], - getAlert: ["GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"], - getOrgPublicKey: ["GET /orgs/{org}/dependabot/secrets/public-key"], - getOrgSecret: ["GET /orgs/{org}/dependabot/secrets/{secret_name}"], - getRepoPublicKey: [ - "GET /repos/{owner}/{repo}/dependabot/secrets/public-key" - ], - getRepoSecret: [ - "GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" - ], - listAlertsForEnterprise: [ - "GET /enterprises/{enterprise}/dependabot/alerts" - ], - listAlertsForOrg: ["GET /orgs/{org}/dependabot/alerts"], - listAlertsForRepo: ["GET /repos/{owner}/{repo}/dependabot/alerts"], - listOrgSecrets: ["GET /orgs/{org}/dependabot/secrets"], - listRepoSecrets: ["GET /repos/{owner}/{repo}/dependabot/secrets"], - listSelectedReposForOrgSecret: [ - "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories" - ], - removeSelectedRepoFromOrgSecret: [ - "DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" - ], - repositoryAccessForOrg: [ - "GET /organizations/{org}/dependabot/repository-access" - ], - setRepositoryAccessDefaultLevel: [ - "PUT /organizations/{org}/dependabot/repository-access/default-level" - ], - setSelectedReposForOrgSecret: [ - "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories" - ], - updateAlert: [ - "PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}" - ], - updateRepositoryAccessForOrg: [ - "PATCH /organizations/{org}/dependabot/repository-access" - ] - }, - dependencyGraph: { - createRepositorySnapshot: [ - "POST /repos/{owner}/{repo}/dependency-graph/snapshots" - ], - diffRange: [ - "GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}" - ], - exportSbom: ["GET /repos/{owner}/{repo}/dependency-graph/sbom"] - }, - emojis: { get: ["GET /emojis"] }, - enterpriseTeamMemberships: { - add: [ - "PUT /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}" - ], - bulkAdd: [ - "POST /enterprises/{enterprise}/teams/{enterprise-team}/memberships/add" - ], - bulkRemove: [ - "POST /enterprises/{enterprise}/teams/{enterprise-team}/memberships/remove" - ], - get: [ - "GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}" - ], - list: ["GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships"], - remove: [ - "DELETE /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}" - ] - }, - enterpriseTeamOrganizations: { - add: [ - "PUT /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}" - ], - bulkAdd: [ - "POST /enterprises/{enterprise}/teams/{enterprise-team}/organizations/add" - ], - bulkRemove: [ - "POST /enterprises/{enterprise}/teams/{enterprise-team}/organizations/remove" - ], - delete: [ - "DELETE /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}" - ], - getAssignment: [ - "GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}" - ], - getAssignments: [ - "GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations" - ] - }, - enterpriseTeams: { - create: ["POST /enterprises/{enterprise}/teams"], - delete: ["DELETE /enterprises/{enterprise}/teams/{team_slug}"], - get: ["GET /enterprises/{enterprise}/teams/{team_slug}"], - list: ["GET /enterprises/{enterprise}/teams"], - update: ["PATCH /enterprises/{enterprise}/teams/{team_slug}"] - }, - gists: { - checkIsStarred: ["GET /gists/{gist_id}/star"], - create: ["POST /gists"], - createComment: ["POST /gists/{gist_id}/comments"], - delete: ["DELETE /gists/{gist_id}"], - deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"], - fork: ["POST /gists/{gist_id}/forks"], - get: ["GET /gists/{gist_id}"], - getComment: ["GET /gists/{gist_id}/comments/{comment_id}"], - getRevision: ["GET /gists/{gist_id}/{sha}"], - list: ["GET /gists"], - listComments: ["GET /gists/{gist_id}/comments"], - listCommits: ["GET /gists/{gist_id}/commits"], - listForUser: ["GET /users/{username}/gists"], - listForks: ["GET /gists/{gist_id}/forks"], - listPublic: ["GET /gists/public"], - listStarred: ["GET /gists/starred"], - star: ["PUT /gists/{gist_id}/star"], - unstar: ["DELETE /gists/{gist_id}/star"], - update: ["PATCH /gists/{gist_id}"], - updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"] - }, - git: { - createBlob: ["POST /repos/{owner}/{repo}/git/blobs"], - createCommit: ["POST /repos/{owner}/{repo}/git/commits"], - createRef: ["POST /repos/{owner}/{repo}/git/refs"], - createTag: ["POST /repos/{owner}/{repo}/git/tags"], - createTree: ["POST /repos/{owner}/{repo}/git/trees"], - deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"], - getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"], - getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"], - getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"], - getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"], - getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"], - listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"], - updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"] - }, - gitignore: { - getAllTemplates: ["GET /gitignore/templates"], - getTemplate: ["GET /gitignore/templates/{name}"] - }, - hostedCompute: { - createNetworkConfigurationForOrg: [ - "POST /orgs/{org}/settings/network-configurations" - ], - deleteNetworkConfigurationFromOrg: [ - "DELETE /orgs/{org}/settings/network-configurations/{network_configuration_id}" - ], - getNetworkConfigurationForOrg: [ - "GET /orgs/{org}/settings/network-configurations/{network_configuration_id}" - ], - getNetworkSettingsForOrg: [ - "GET /orgs/{org}/settings/network-settings/{network_settings_id}" - ], - listNetworkConfigurationsForOrg: [ - "GET /orgs/{org}/settings/network-configurations" - ], - updateNetworkConfigurationForOrg: [ - "PATCH /orgs/{org}/settings/network-configurations/{network_configuration_id}" - ] - }, - interactions: { - getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"], - getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"], - getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"], - getRestrictionsForYourPublicRepos: [ - "GET /user/interaction-limits", - {}, - { renamed: ["interactions", "getRestrictionsForAuthenticatedUser"] } - ], - removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"], - removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"], - removeRestrictionsForRepo: [ - "DELETE /repos/{owner}/{repo}/interaction-limits" - ], - removeRestrictionsForYourPublicRepos: [ - "DELETE /user/interaction-limits", - {}, - { renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"] } - ], - setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"], - setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"], - setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"], - setRestrictionsForYourPublicRepos: [ - "PUT /user/interaction-limits", - {}, - { renamed: ["interactions", "setRestrictionsForAuthenticatedUser"] } - ] - }, - issues: { - addAssignees: [ - "POST /repos/{owner}/{repo}/issues/{issue_number}/assignees" - ], - addBlockedByDependency: [ - "POST /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by" - ], - addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"], - addSubIssue: [ - "POST /repos/{owner}/{repo}/issues/{issue_number}/sub_issues" - ], - checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"], - checkUserCanBeAssignedToIssue: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}" - ], - create: ["POST /repos/{owner}/{repo}/issues"], - createComment: [ - "POST /repos/{owner}/{repo}/issues/{issue_number}/comments" - ], - createLabel: ["POST /repos/{owner}/{repo}/labels"], - createMilestone: ["POST /repos/{owner}/{repo}/milestones"], - deleteComment: [ - "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}" - ], - deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"], - deleteMilestone: [ - "DELETE /repos/{owner}/{repo}/milestones/{milestone_number}" - ], - get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"], - getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"], - getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"], - getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"], - getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"], - getParent: ["GET /repos/{owner}/{repo}/issues/{issue_number}/parent"], - list: ["GET /issues"], - listAssignees: ["GET /repos/{owner}/{repo}/assignees"], - listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"], - listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"], - listDependenciesBlockedBy: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by" - ], - listDependenciesBlocking: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocking" - ], - listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"], - listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"], - listEventsForTimeline: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline" - ], - listForAuthenticatedUser: ["GET /user/issues"], - listForOrg: ["GET /orgs/{org}/issues"], - listForRepo: ["GET /repos/{owner}/{repo}/issues"], - listLabelsForMilestone: [ - "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels" - ], - listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"], - listLabelsOnIssue: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/labels" - ], - listMilestones: ["GET /repos/{owner}/{repo}/milestones"], - listSubIssues: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/sub_issues" - ], - lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"], - removeAllLabels: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels" - ], - removeAssignees: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees" - ], - removeDependencyBlockedBy: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by/{issue_id}" - ], - removeLabel: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}" - ], - removeSubIssue: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/sub_issue" - ], - reprioritizeSubIssue: [ - "PATCH /repos/{owner}/{repo}/issues/{issue_number}/sub_issues/priority" - ], - setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"], - unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"], - update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"], - updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"], - updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"], - updateMilestone: [ - "PATCH /repos/{owner}/{repo}/milestones/{milestone_number}" - ] - }, - licenses: { - get: ["GET /licenses/{license}"], - getAllCommonlyUsed: ["GET /licenses"], - getForRepo: ["GET /repos/{owner}/{repo}/license"] - }, - markdown: { - render: ["POST /markdown"], - renderRaw: [ - "POST /markdown/raw", - { headers: { "content-type": "text/plain; charset=utf-8" } } - ] - }, - meta: { - get: ["GET /meta"], - getAllVersions: ["GET /versions"], - getOctocat: ["GET /octocat"], - getZen: ["GET /zen"], - root: ["GET /"] - }, - migrations: { - deleteArchiveForAuthenticatedUser: [ - "DELETE /user/migrations/{migration_id}/archive" - ], - deleteArchiveForOrg: [ - "DELETE /orgs/{org}/migrations/{migration_id}/archive" - ], - downloadArchiveForOrg: [ - "GET /orgs/{org}/migrations/{migration_id}/archive" - ], - getArchiveForAuthenticatedUser: [ - "GET /user/migrations/{migration_id}/archive" - ], - getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"], - getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"], - listForAuthenticatedUser: ["GET /user/migrations"], - listForOrg: ["GET /orgs/{org}/migrations"], - listReposForAuthenticatedUser: [ - "GET /user/migrations/{migration_id}/repositories" - ], - listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories"], - listReposForUser: [ - "GET /user/migrations/{migration_id}/repositories", - {}, - { renamed: ["migrations", "listReposForAuthenticatedUser"] } - ], - startForAuthenticatedUser: ["POST /user/migrations"], - startForOrg: ["POST /orgs/{org}/migrations"], - unlockRepoForAuthenticatedUser: [ - "DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock" - ], - unlockRepoForOrg: [ - "DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock" - ] + nacl.randomBytes = function(n) { + var b = new Uint8Array(n); + randombytes(b, n); + return b; + }; + nacl.secretbox = function(msg, nonce, key) { + checkArrayTypes(msg, nonce, key); + checkLengths(key, nonce); + var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); + var c = new Uint8Array(m.length); + for (var i = 0; i < msg.length; i++) m[i + crypto_secretbox_ZEROBYTES] = msg[i]; + crypto_secretbox(c, m, m.length, nonce, key); + return c.subarray(crypto_secretbox_BOXZEROBYTES); + }; + nacl.secretbox.open = function(box, nonce, key) { + checkArrayTypes(box, nonce, key); + checkLengths(key, nonce); + var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); + var m = new Uint8Array(c.length); + for (var i = 0; i < box.length; i++) c[i + crypto_secretbox_BOXZEROBYTES] = box[i]; + if (c.length < 32) return false; + if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return false; + return m.subarray(crypto_secretbox_ZEROBYTES); + }; + nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES; + nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; + nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; + nacl.scalarMult = function(n, p) { + checkArrayTypes(n, p); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error("bad n size"); + if (p.length !== crypto_scalarmult_BYTES) throw new Error("bad p size"); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult(q, n, p); + return q; + }; + nacl.scalarMult.base = function(n) { + checkArrayTypes(n); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error("bad n size"); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult_base(q, n); + return q; + }; + nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; + nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES; + nacl.box = function(msg, nonce, publicKey, secretKey) { + var k = nacl.box.before(publicKey, secretKey); + return nacl.secretbox(msg, nonce, k); + }; + nacl.box.before = function(publicKey, secretKey) { + checkArrayTypes(publicKey, secretKey); + checkBoxLengths(publicKey, secretKey); + var k = new Uint8Array(crypto_box_BEFORENMBYTES); + crypto_box_beforenm(k, publicKey, secretKey); + return k; + }; + nacl.box.after = nacl.secretbox; + nacl.box.open = function(msg, nonce, publicKey, secretKey) { + var k = nacl.box.before(publicKey, secretKey); + return nacl.secretbox.open(msg, nonce, k); + }; + nacl.box.open.after = nacl.secretbox.open; + nacl.box.keyPair = function() { + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); + crypto_box_keypair(pk, sk); + return { publicKey: pk, secretKey: sk }; + }; + nacl.box.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_box_SECRETKEYBYTES) + throw new Error("bad secret key size"); + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + crypto_scalarmult_base(pk, secretKey); + return { publicKey: pk, secretKey: new Uint8Array(secretKey) }; + }; + nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES; + nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES; + nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES; + nacl.box.nonceLength = crypto_box_NONCEBYTES; + nacl.box.overheadLength = nacl.secretbox.overheadLength; + nacl.sign = function(msg, secretKey) { + checkArrayTypes(msg, secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error("bad secret key size"); + var signedMsg = new Uint8Array(crypto_sign_BYTES + msg.length); + crypto_sign(signedMsg, msg, msg.length, secretKey); + return signedMsg; + }; + nacl.sign.open = function(signedMsg, publicKey) { + if (arguments.length !== 2) + throw new Error("nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?"); + checkArrayTypes(signedMsg, publicKey); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error("bad public key size"); + var tmp = new Uint8Array(signedMsg.length); + var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); + if (mlen < 0) return null; + var m = new Uint8Array(mlen); + for (var i = 0; i < m.length; i++) m[i] = tmp[i]; + return m; + }; + nacl.sign.detached = function(msg, secretKey) { + var signedMsg = nacl.sign(msg, secretKey); + var sig = new Uint8Array(crypto_sign_BYTES); + for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; + return sig; + }; + nacl.sign.detached.verify = function(msg, sig, publicKey) { + checkArrayTypes(msg, sig, publicKey); + if (sig.length !== crypto_sign_BYTES) + throw new Error("bad signature size"); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error("bad public key size"); + var sm = new Uint8Array(crypto_sign_BYTES + msg.length); + var m = new Uint8Array(crypto_sign_BYTES + msg.length); + var i; + for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; + for (i = 0; i < msg.length; i++) sm[i + crypto_sign_BYTES] = msg[i]; + return crypto_sign_open(m, sm, sm.length, publicKey) >= 0; + }; + nacl.sign.keyPair = function() { + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + crypto_sign_keypair(pk, sk); + return { publicKey: pk, secretKey: sk }; + }; + nacl.sign.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error("bad secret key size"); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32 + i]; + return { publicKey: pk, secretKey: new Uint8Array(secretKey) }; + }; + nacl.sign.keyPair.fromSeed = function(seed) { + checkArrayTypes(seed); + if (seed.length !== crypto_sign_SEEDBYTES) + throw new Error("bad seed size"); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + for (var i = 0; i < 32; i++) sk[i] = seed[i]; + crypto_sign_keypair(pk, sk, true); + return { publicKey: pk, secretKey: sk }; + }; + nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; + nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; + nacl.sign.seedLength = crypto_sign_SEEDBYTES; + nacl.sign.signatureLength = crypto_sign_BYTES; + nacl.hash = function(msg) { + checkArrayTypes(msg); + var h = new Uint8Array(crypto_hash_BYTES); + crypto_hash(h, msg, msg.length); + return h; + }; + nacl.hash.hashLength = crypto_hash_BYTES; + nacl.verify = function(x, y) { + checkArrayTypes(x, y); + if (x.length === 0 || y.length === 0) return false; + if (x.length !== y.length) return false; + return vn(x, 0, y, 0, x.length) === 0 ? true : false; + }; + nacl.setPRNG = function(fn) { + randombytes = fn; + }; + (function() { + var crypto = typeof self !== "undefined" ? self.crypto || self.msCrypto : null; + if (crypto && crypto.getRandomValues) { + var QUOTA = 65536; + nacl.setPRNG(function(x, n) { + var i, v = new Uint8Array(n); + for (i = 0; i < n; i += QUOTA) { + crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); + } + for (i = 0; i < n; i++) x[i] = v[i]; + cleanup(v); + }); + } else if (typeof require !== "undefined") { + crypto = require("crypto"); + if (crypto && crypto.randomBytes) { + nacl.setPRNG(function(x, n) { + var i, v = crypto.randomBytes(n); + for (i = 0; i < n; i++) x[i] = v[i]; + cleanup(v); + }); + } + } + })(); + })(typeof module2 !== "undefined" && module2.exports ? module2.exports : self.nacl = self.nacl || {}); + } +}); + +// node_modules/bcrypt-pbkdf/index.js +var require_bcrypt_pbkdf = __commonJS({ + "node_modules/bcrypt-pbkdf/index.js"(exports2, module2) { + "use strict"; + var crypto_hash_sha512 = require_nacl_fast().lowlevel.crypto_hash; + var BLF_J = 0; + var Blowfish = function() { + this.S = [ + new Uint32Array([ + 3509652390, + 2564797868, + 805139163, + 3491422135, + 3101798381, + 1780907670, + 3128725573, + 4046225305, + 614570311, + 3012652279, + 134345442, + 2240740374, + 1667834072, + 1901547113, + 2757295779, + 4103290238, + 227898511, + 1921955416, + 1904987480, + 2182433518, + 2069144605, + 3260701109, + 2620446009, + 720527379, + 3318853667, + 677414384, + 3393288472, + 3101374703, + 2390351024, + 1614419982, + 1822297739, + 2954791486, + 3608508353, + 3174124327, + 2024746970, + 1432378464, + 3864339955, + 2857741204, + 1464375394, + 1676153920, + 1439316330, + 715854006, + 3033291828, + 289532110, + 2706671279, + 2087905683, + 3018724369, + 1668267050, + 732546397, + 1947742710, + 3462151702, + 2609353502, + 2950085171, + 1814351708, + 2050118529, + 680887927, + 999245976, + 1800124847, + 3300911131, + 1713906067, + 1641548236, + 4213287313, + 1216130144, + 1575780402, + 4018429277, + 3917837745, + 3693486850, + 3949271944, + 596196993, + 3549867205, + 258830323, + 2213823033, + 772490370, + 2760122372, + 1774776394, + 2652871518, + 566650946, + 4142492826, + 1728879713, + 2882767088, + 1783734482, + 3629395816, + 2517608232, + 2874225571, + 1861159788, + 326777828, + 3124490320, + 2130389656, + 2716951837, + 967770486, + 1724537150, + 2185432712, + 2364442137, + 1164943284, + 2105845187, + 998989502, + 3765401048, + 2244026483, + 1075463327, + 1455516326, + 1322494562, + 910128902, + 469688178, + 1117454909, + 936433444, + 3490320968, + 3675253459, + 1240580251, + 122909385, + 2157517691, + 634681816, + 4142456567, + 3825094682, + 3061402683, + 2540495037, + 79693498, + 3249098678, + 1084186820, + 1583128258, + 426386531, + 1761308591, + 1047286709, + 322548459, + 995290223, + 1845252383, + 2603652396, + 3431023940, + 2942221577, + 3202600964, + 3727903485, + 1712269319, + 422464435, + 3234572375, + 1170764815, + 3523960633, + 3117677531, + 1434042557, + 442511882, + 3600875718, + 1076654713, + 1738483198, + 4213154764, + 2393238008, + 3677496056, + 1014306527, + 4251020053, + 793779912, + 2902807211, + 842905082, + 4246964064, + 1395751752, + 1040244610, + 2656851899, + 3396308128, + 445077038, + 3742853595, + 3577915638, + 679411651, + 2892444358, + 2354009459, + 1767581616, + 3150600392, + 3791627101, + 3102740896, + 284835224, + 4246832056, + 1258075500, + 768725851, + 2589189241, + 3069724005, + 3532540348, + 1274779536, + 3789419226, + 2764799539, + 1660621633, + 3471099624, + 4011903706, + 913787905, + 3497959166, + 737222580, + 2514213453, + 2928710040, + 3937242737, + 1804850592, + 3499020752, + 2949064160, + 2386320175, + 2390070455, + 2415321851, + 4061277028, + 2290661394, + 2416832540, + 1336762016, + 1754252060, + 3520065937, + 3014181293, + 791618072, + 3188594551, + 3933548030, + 2332172193, + 3852520463, + 3043980520, + 413987798, + 3465142937, + 3030929376, + 4245938359, + 2093235073, + 3534596313, + 375366246, + 2157278981, + 2479649556, + 555357303, + 3870105701, + 2008414854, + 3344188149, + 4221384143, + 3956125452, + 2067696032, + 3594591187, + 2921233993, + 2428461, + 544322398, + 577241275, + 1471733935, + 610547355, + 4027169054, + 1432588573, + 1507829418, + 2025931657, + 3646575487, + 545086370, + 48609733, + 2200306550, + 1653985193, + 298326376, + 1316178497, + 3007786442, + 2064951626, + 458293330, + 2589141269, + 3591329599, + 3164325604, + 727753846, + 2179363840, + 146436021, + 1461446943, + 4069977195, + 705550613, + 3059967265, + 3887724982, + 4281599278, + 3313849956, + 1404054877, + 2845806497, + 146425753, + 1854211946 + ]), + new Uint32Array([ + 1266315497, + 3048417604, + 3681880366, + 3289982499, + 290971e4, + 1235738493, + 2632868024, + 2414719590, + 3970600049, + 1771706367, + 1449415276, + 3266420449, + 422970021, + 1963543593, + 2690192192, + 3826793022, + 1062508698, + 1531092325, + 1804592342, + 2583117782, + 2714934279, + 4024971509, + 1294809318, + 4028980673, + 1289560198, + 2221992742, + 1669523910, + 35572830, + 157838143, + 1052438473, + 1016535060, + 1802137761, + 1753167236, + 1386275462, + 3080475397, + 2857371447, + 1040679964, + 2145300060, + 2390574316, + 1461121720, + 2956646967, + 4031777805, + 4028374788, + 33600511, + 2920084762, + 1018524850, + 629373528, + 3691585981, + 3515945977, + 2091462646, + 2486323059, + 586499841, + 988145025, + 935516892, + 3367335476, + 2599673255, + 2839830854, + 265290510, + 3972581182, + 2759138881, + 3795373465, + 1005194799, + 847297441, + 406762289, + 1314163512, + 1332590856, + 1866599683, + 4127851711, + 750260880, + 613907577, + 1450815602, + 3165620655, + 3734664991, + 3650291728, + 3012275730, + 3704569646, + 1427272223, + 778793252, + 1343938022, + 2676280711, + 2052605720, + 1946737175, + 3164576444, + 3914038668, + 3967478842, + 3682934266, + 1661551462, + 3294938066, + 4011595847, + 840292616, + 3712170807, + 616741398, + 312560963, + 711312465, + 1351876610, + 322626781, + 1910503582, + 271666773, + 2175563734, + 1594956187, + 70604529, + 3617834859, + 1007753275, + 1495573769, + 4069517037, + 2549218298, + 2663038764, + 504708206, + 2263041392, + 3941167025, + 2249088522, + 1514023603, + 1998579484, + 1312622330, + 694541497, + 2582060303, + 2151582166, + 1382467621, + 776784248, + 2618340202, + 3323268794, + 2497899128, + 2784771155, + 503983604, + 4076293799, + 907881277, + 423175695, + 432175456, + 1378068232, + 4145222326, + 3954048622, + 3938656102, + 3820766613, + 2793130115, + 2977904593, + 26017576, + 3274890735, + 3194772133, + 1700274565, + 1756076034, + 4006520079, + 3677328699, + 720338349, + 1533947780, + 354530856, + 688349552, + 3973924725, + 1637815568, + 332179504, + 3949051286, + 53804574, + 2852348879, + 3044236432, + 1282449977, + 3583942155, + 3416972820, + 4006381244, + 1617046695, + 2628476075, + 3002303598, + 1686838959, + 431878346, + 2686675385, + 1700445008, + 1080580658, + 1009431731, + 832498133, + 3223435511, + 2605976345, + 2271191193, + 2516031870, + 1648197032, + 4164389018, + 2548247927, + 300782431, + 375919233, + 238389289, + 3353747414, + 2531188641, + 2019080857, + 1475708069, + 455242339, + 2609103871, + 448939670, + 3451063019, + 1395535956, + 2413381860, + 1841049896, + 1491858159, + 885456874, + 4264095073, + 4001119347, + 1565136089, + 3898914787, + 1108368660, + 540939232, + 1173283510, + 2745871338, + 3681308437, + 4207628240, + 3343053890, + 4016749493, + 1699691293, + 1103962373, + 3625875870, + 2256883143, + 3830138730, + 1031889488, + 3479347698, + 1535977030, + 4236805024, + 3251091107, + 2132092099, + 1774941330, + 1199868427, + 1452454533, + 157007616, + 2904115357, + 342012276, + 595725824, + 1480756522, + 206960106, + 497939518, + 591360097, + 863170706, + 2375253569, + 3596610801, + 1814182875, + 2094937945, + 3421402208, + 1082520231, + 3463918190, + 2785509508, + 435703966, + 3908032597, + 1641649973, + 2842273706, + 3305899714, + 1510255612, + 2148256476, + 2655287854, + 3276092548, + 4258621189, + 236887753, + 3681803219, + 274041037, + 1734335097, + 3815195456, + 3317970021, + 1899903192, + 1026095262, + 4050517792, + 356393447, + 2410691914, + 3873677099, + 3682840055 + ]), + new Uint32Array([ + 3913112168, + 2491498743, + 4132185628, + 2489919796, + 1091903735, + 1979897079, + 3170134830, + 3567386728, + 3557303409, + 857797738, + 1136121015, + 1342202287, + 507115054, + 2535736646, + 337727348, + 3213592640, + 1301675037, + 2528481711, + 1895095763, + 1721773893, + 3216771564, + 62756741, + 2142006736, + 835421444, + 2531993523, + 1442658625, + 3659876326, + 2882144922, + 676362277, + 1392781812, + 170690266, + 3921047035, + 1759253602, + 3611846912, + 1745797284, + 664899054, + 1329594018, + 3901205900, + 3045908486, + 2062866102, + 2865634940, + 3543621612, + 3464012697, + 1080764994, + 553557557, + 3656615353, + 3996768171, + 991055499, + 499776247, + 1265440854, + 648242737, + 3940784050, + 980351604, + 3713745714, + 1749149687, + 3396870395, + 4211799374, + 3640570775, + 1161844396, + 3125318951, + 1431517754, + 545492359, + 4268468663, + 3499529547, + 1437099964, + 2702547544, + 3433638243, + 2581715763, + 2787789398, + 1060185593, + 1593081372, + 2418618748, + 4260947970, + 69676912, + 2159744348, + 86519011, + 2512459080, + 3838209314, + 1220612927, + 3339683548, + 133810670, + 1090789135, + 1078426020, + 1569222167, + 845107691, + 3583754449, + 4072456591, + 1091646820, + 628848692, + 1613405280, + 3757631651, + 526609435, + 236106946, + 48312990, + 2942717905, + 3402727701, + 1797494240, + 859738849, + 992217954, + 4005476642, + 2243076622, + 3870952857, + 3732016268, + 765654824, + 3490871365, + 2511836413, + 1685915746, + 3888969200, + 1414112111, + 2273134842, + 3281911079, + 4080962846, + 172450625, + 2569994100, + 980381355, + 4109958455, + 2819808352, + 2716589560, + 2568741196, + 3681446669, + 3329971472, + 1835478071, + 660984891, + 3704678404, + 4045999559, + 3422617507, + 3040415634, + 1762651403, + 1719377915, + 3470491036, + 2693910283, + 3642056355, + 3138596744, + 1364962596, + 2073328063, + 1983633131, + 926494387, + 3423689081, + 2150032023, + 4096667949, + 1749200295, + 3328846651, + 309677260, + 2016342300, + 1779581495, + 3079819751, + 111262694, + 1274766160, + 443224088, + 298511866, + 1025883608, + 3806446537, + 1145181785, + 168956806, + 3641502830, + 3584813610, + 1689216846, + 3666258015, + 3200248200, + 1692713982, + 2646376535, + 4042768518, + 1618508792, + 1610833997, + 3523052358, + 4130873264, + 2001055236, + 3610705100, + 2202168115, + 4028541809, + 2961195399, + 1006657119, + 2006996926, + 3186142756, + 1430667929, + 3210227297, + 1314452623, + 4074634658, + 4101304120, + 2273951170, + 1399257539, + 3367210612, + 3027628629, + 1190975929, + 2062231137, + 2333990788, + 2221543033, + 2438960610, + 1181637006, + 548689776, + 2362791313, + 3372408396, + 3104550113, + 3145860560, + 296247880, + 1970579870, + 3078560182, + 3769228297, + 1714227617, + 3291629107, + 3898220290, + 166772364, + 1251581989, + 493813264, + 448347421, + 195405023, + 2709975567, + 677966185, + 3703036547, + 1463355134, + 2715995803, + 1338867538, + 1343315457, + 2802222074, + 2684532164, + 233230375, + 2599980071, + 2000651841, + 3277868038, + 1638401717, + 4028070440, + 3237316320, + 6314154, + 819756386, + 300326615, + 590932579, + 1405279636, + 3267499572, + 3150704214, + 2428286686, + 3959192993, + 3461946742, + 1862657033, + 1266418056, + 963775037, + 2089974820, + 2263052895, + 1917689273, + 448879540, + 3550394620, + 3981727096, + 150775221, + 3627908307, + 1303187396, + 508620638, + 2975983352, + 2726630617, + 1817252668, + 1876281319, + 1457606340, + 908771278, + 3720792119, + 3617206836, + 2455994898, + 1729034894, + 1080033504 + ]), + new Uint32Array([ + 976866871, + 3556439503, + 2881648439, + 1522871579, + 1555064734, + 1336096578, + 3548522304, + 2579274686, + 3574697629, + 3205460757, + 3593280638, + 3338716283, + 3079412587, + 564236357, + 2993598910, + 1781952180, + 1464380207, + 3163844217, + 3332601554, + 1699332808, + 1393555694, + 1183702653, + 3581086237, + 1288719814, + 691649499, + 2847557200, + 2895455976, + 3193889540, + 2717570544, + 1781354906, + 1676643554, + 2592534050, + 3230253752, + 1126444790, + 2770207658, + 2633158820, + 2210423226, + 2615765581, + 2414155088, + 3127139286, + 673620729, + 2805611233, + 1269405062, + 4015350505, + 3341807571, + 4149409754, + 1057255273, + 2012875353, + 2162469141, + 2276492801, + 2601117357, + 993977747, + 3918593370, + 2654263191, + 753973209, + 36408145, + 2530585658, + 25011837, + 3520020182, + 2088578344, + 530523599, + 2918365339, + 1524020338, + 1518925132, + 3760827505, + 3759777254, + 1202760957, + 3985898139, + 3906192525, + 674977740, + 4174734889, + 2031300136, + 2019492241, + 3983892565, + 4153806404, + 3822280332, + 352677332, + 2297720250, + 60907813, + 90501309, + 3286998549, + 1016092578, + 2535922412, + 2839152426, + 457141659, + 509813237, + 4120667899, + 652014361, + 1966332200, + 2975202805, + 55981186, + 2327461051, + 676427537, + 3255491064, + 2882294119, + 3433927263, + 1307055953, + 942726286, + 933058658, + 2468411793, + 3933900994, + 4215176142, + 1361170020, + 2001714738, + 2830558078, + 3274259782, + 1222529897, + 1679025792, + 2729314320, + 3714953764, + 1770335741, + 151462246, + 3013232138, + 1682292957, + 1483529935, + 471910574, + 1539241949, + 458788160, + 3436315007, + 1807016891, + 3718408830, + 978976581, + 1043663428, + 3165965781, + 1927990952, + 4200891579, + 2372276910, + 3208408903, + 3533431907, + 1412390302, + 2931980059, + 4132332400, + 1947078029, + 3881505623, + 4168226417, + 2941484381, + 1077988104, + 1320477388, + 886195818, + 18198404, + 3786409e3, + 2509781533, + 112762804, + 3463356488, + 1866414978, + 891333506, + 18488651, + 661792760, + 1628790961, + 3885187036, + 3141171499, + 876946877, + 2693282273, + 1372485963, + 791857591, + 2686433993, + 3759982718, + 3167212022, + 3472953795, + 2716379847, + 445679433, + 3561995674, + 3504004811, + 3574258232, + 54117162, + 3331405415, + 2381918588, + 3769707343, + 4154350007, + 1140177722, + 4074052095, + 668550556, + 3214352940, + 367459370, + 261225585, + 2610173221, + 4209349473, + 3468074219, + 3265815641, + 314222801, + 3066103646, + 3808782860, + 282218597, + 3406013506, + 3773591054, + 379116347, + 1285071038, + 846784868, + 2669647154, + 3771962079, + 3550491691, + 2305946142, + 453669953, + 1268987020, + 3317592352, + 3279303384, + 3744833421, + 2610507566, + 3859509063, + 266596637, + 3847019092, + 517658769, + 3462560207, + 3443424879, + 370717030, + 4247526661, + 2224018117, + 4143653529, + 4112773975, + 2788324899, + 2477274417, + 1456262402, + 2901442914, + 1517677493, + 1846949527, + 2295493580, + 3734397586, + 2176403920, + 1280348187, + 1908823572, + 3871786941, + 846861322, + 1172426758, + 3287448474, + 3383383037, + 1655181056, + 3139813346, + 901632758, + 1897031941, + 2986607138, + 3066810236, + 3447102507, + 1393639104, + 373351379, + 950779232, + 625454576, + 3124240540, + 4148612726, + 2007998917, + 544563296, + 2244738638, + 2330496472, + 2058025392, + 1291430526, + 424198748, + 50039436, + 29584100, + 3605783033, + 2429876329, + 2791104160, + 1057563949, + 3255363231, + 3075367218, + 3463963227, + 1469046755, + 985887462 + ]) + ]; + this.P = new Uint32Array([ + 608135816, + 2242054355, + 320440878, + 57701188, + 2752067618, + 698298832, + 137296536, + 3964562569, + 1160258022, + 953160567, + 3193202383, + 887688300, + 3232508343, + 3380367581, + 1065670069, + 3041331479, + 2450970073, + 2306472731 + ]); + }; + function F(S, x8, i) { + return (S[0][x8[i + 3]] + S[1][x8[i + 2]] ^ S[2][x8[i + 1]]) + S[3][x8[i]]; + } + Blowfish.prototype.encipher = function(x, x8) { + if (x8 === void 0) { + x8 = new Uint8Array(x.buffer); + if (x.byteOffset !== 0) + x8 = x8.subarray(x.byteOffset); + } + x[0] ^= this.P[0]; + for (var i = 1; i < 16; i += 2) { + x[1] ^= F(this.S, x8, 0) ^ this.P[i]; + x[0] ^= F(this.S, x8, 4) ^ this.P[i + 1]; + } + var t = x[0]; + x[0] = x[1] ^ this.P[17]; + x[1] = t; + }; + Blowfish.prototype.decipher = function(x) { + var x8 = new Uint8Array(x.buffer); + if (x.byteOffset !== 0) + x8 = x8.subarray(x.byteOffset); + x[0] ^= this.P[17]; + for (var i = 16; i > 0; i -= 2) { + x[1] ^= F(this.S, x8, 0) ^ this.P[i]; + x[0] ^= F(this.S, x8, 4) ^ this.P[i - 1]; + } + var t = x[0]; + x[0] = x[1] ^ this.P[0]; + x[1] = t; + }; + function stream2word(data, databytes) { + var i, temp = 0; + for (i = 0; i < 4; i++, BLF_J++) { + if (BLF_J >= databytes) BLF_J = 0; + temp = temp << 8 | data[BLF_J]; + } + return temp; + } + Blowfish.prototype.expand0state = function(key, keybytes) { + var d = new Uint32Array(2), i, k; + var d8 = new Uint8Array(d.buffer); + for (i = 0, BLF_J = 0; i < 18; i++) { + this.P[i] ^= stream2word(key, keybytes); + } + BLF_J = 0; + for (i = 0; i < 18; i += 2) { + this.encipher(d, d8); + this.P[i] = d[0]; + this.P[i + 1] = d[1]; + } + for (i = 0; i < 4; i++) { + for (k = 0; k < 256; k += 2) { + this.encipher(d, d8); + this.S[i][k] = d[0]; + this.S[i][k + 1] = d[1]; + } + } + }; + Blowfish.prototype.expandstate = function(data, databytes, key, keybytes) { + var d = new Uint32Array(2), i, k; + for (i = 0, BLF_J = 0; i < 18; i++) { + this.P[i] ^= stream2word(key, keybytes); + } + for (i = 0, BLF_J = 0; i < 18; i += 2) { + d[0] ^= stream2word(data, databytes); + d[1] ^= stream2word(data, databytes); + this.encipher(d); + this.P[i] = d[0]; + this.P[i + 1] = d[1]; + } + for (i = 0; i < 4; i++) { + for (k = 0; k < 256; k += 2) { + d[0] ^= stream2word(data, databytes); + d[1] ^= stream2word(data, databytes); + this.encipher(d); + this.S[i][k] = d[0]; + this.S[i][k + 1] = d[1]; + } + } + BLF_J = 0; + }; + Blowfish.prototype.enc = function(data, blocks) { + for (var i = 0; i < blocks; i++) { + this.encipher(data.subarray(i * 2)); + } + }; + Blowfish.prototype.dec = function(data, blocks) { + for (var i = 0; i < blocks; i++) { + this.decipher(data.subarray(i * 2)); + } + }; + var BCRYPT_BLOCKS = 8; + var BCRYPT_HASHSIZE = 32; + function bcrypt_hash(sha2pass, sha2salt, out) { + var state = new Blowfish(), cdata = new Uint32Array(BCRYPT_BLOCKS), i, ciphertext = new Uint8Array([ + 79, + 120, + 121, + 99, + 104, + 114, + 111, + 109, + 97, + 116, + 105, + 99, + 66, + 108, + 111, + 119, + 102, + 105, + 115, + 104, + 83, + 119, + 97, + 116, + 68, + 121, + 110, + 97, + 109, + 105, + 116, + 101 + ]); + state.expandstate(sha2salt, 64, sha2pass, 64); + for (i = 0; i < 64; i++) { + state.expand0state(sha2salt, 64); + state.expand0state(sha2pass, 64); + } + for (i = 0; i < BCRYPT_BLOCKS; i++) + cdata[i] = stream2word(ciphertext, ciphertext.byteLength); + for (i = 0; i < 64; i++) + state.enc(cdata, cdata.byteLength / 8); + for (i = 0; i < BCRYPT_BLOCKS; i++) { + out[4 * i + 3] = cdata[i] >>> 24; + out[4 * i + 2] = cdata[i] >>> 16; + out[4 * i + 1] = cdata[i] >>> 8; + out[4 * i + 0] = cdata[i]; + } + } + function bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) { + var sha2pass = new Uint8Array(64), sha2salt = new Uint8Array(64), out = new Uint8Array(BCRYPT_HASHSIZE), tmpout = new Uint8Array(BCRYPT_HASHSIZE), countsalt = new Uint8Array(saltlen + 4), i, j, amt, stride, dest, count, origkeylen = keylen; + if (rounds < 1) + return -1; + if (passlen === 0 || saltlen === 0 || keylen === 0 || keylen > out.byteLength * out.byteLength || saltlen > 1 << 20) + return -1; + stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength); + amt = Math.floor((keylen + stride - 1) / stride); + for (i = 0; i < saltlen; i++) + countsalt[i] = salt[i]; + crypto_hash_sha512(sha2pass, pass, passlen); + for (count = 1; keylen > 0; count++) { + countsalt[saltlen + 0] = count >>> 24; + countsalt[saltlen + 1] = count >>> 16; + countsalt[saltlen + 2] = count >>> 8; + countsalt[saltlen + 3] = count; + crypto_hash_sha512(sha2salt, countsalt, saltlen + 4); + bcrypt_hash(sha2pass, sha2salt, tmpout); + for (i = out.byteLength; i--; ) + out[i] = tmpout[i]; + for (i = 1; i < rounds; i++) { + crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength); + bcrypt_hash(sha2pass, sha2salt, tmpout); + for (j = 0; j < out.byteLength; j++) + out[j] ^= tmpout[j]; + } + amt = Math.min(amt, keylen); + for (i = 0; i < amt; i++) { + dest = i * stride + (count - 1); + if (dest >= origkeylen) + break; + key[dest] = out[i]; + } + keylen -= i; + } + return 0; + } + module2.exports = { + BLOCKS: BCRYPT_BLOCKS, + HASHSIZE: BCRYPT_HASHSIZE, + hash: bcrypt_hash, + pbkdf: bcrypt_pbkdf + }; + } +}); + +// node_modules/cpu-features/build/Release/cpufeatures.node +var require_cpufeatures = __commonJS({ + "node_modules/cpu-features/build/Release/cpufeatures.node"() { + } +}); + +// node_modules/cpu-features/lib/index.js +var require_lib3 = __commonJS({ + "node_modules/cpu-features/lib/index.js"(exports2, module2) { + "use strict"; + var binding = require_cpufeatures(); + module2.exports = binding.getCPUInfo; + } +}); + +// node_modules/ssh2/lib/protocol/constants.js +var require_constants6 = __commonJS({ + "node_modules/ssh2/lib/protocol/constants.js"(exports2, module2) { + "use strict"; + var crypto = require("crypto"); + var cpuInfo; + try { + cpuInfo = require_lib3()(); + } catch { + } + var { bindingAvailable, CIPHER_INFO, MAC_INFO } = require_crypto(); + var eddsaSupported = (() => { + if (typeof crypto.sign === "function" && typeof crypto.verify === "function") { + const key = "-----BEGIN PRIVATE KEY-----\r\nMC4CAQAwBQYDK2VwBCIEIHKj+sVa9WcD/q2DJUJaf43Kptc8xYuUQA4bOFj9vC8T\r\n-----END PRIVATE KEY-----"; + const data = Buffer.from("a"); + let sig; + let verified; + try { + sig = crypto.sign(null, data, key); + verified = crypto.verify(null, data, key, sig); + } catch { + } + return Buffer.isBuffer(sig) && sig.length === 64 && verified === true; + } + return false; + })(); + var curve25519Supported = typeof crypto.diffieHellman === "function" && typeof crypto.generateKeyPairSync === "function" && typeof crypto.createPublicKey === "function"; + var DEFAULT_KEX = [ + // https://tools.ietf.org/html/rfc5656#section-10.1 + "ecdh-sha2-nistp256", + "ecdh-sha2-nistp384", + "ecdh-sha2-nistp521", + // https://tools.ietf.org/html/rfc4419#section-4 + "diffie-hellman-group-exchange-sha256", + // https://tools.ietf.org/html/rfc8268 + "diffie-hellman-group14-sha256", + "diffie-hellman-group15-sha512", + "diffie-hellman-group16-sha512", + "diffie-hellman-group17-sha512", + "diffie-hellman-group18-sha512" + ]; + if (curve25519Supported) { + DEFAULT_KEX.unshift("curve25519-sha256"); + DEFAULT_KEX.unshift("curve25519-sha256@libssh.org"); + } + var SUPPORTED_KEX = DEFAULT_KEX.concat([ + // https://tools.ietf.org/html/rfc4419#section-4 + "diffie-hellman-group-exchange-sha1", + "diffie-hellman-group14-sha1", + // REQUIRED + "diffie-hellman-group1-sha1" + // REQUIRED + ]); + var DEFAULT_SERVER_HOST_KEY = [ + "ecdsa-sha2-nistp256", + "ecdsa-sha2-nistp384", + "ecdsa-sha2-nistp521", + "rsa-sha2-512", + // RFC 8332 + "rsa-sha2-256", + // RFC 8332 + "ssh-rsa" + ]; + if (eddsaSupported) + DEFAULT_SERVER_HOST_KEY.unshift("ssh-ed25519"); + var SUPPORTED_SERVER_HOST_KEY = DEFAULT_SERVER_HOST_KEY.concat([ + "ssh-dss" + ]); + var canUseCipher = (() => { + const ciphers = crypto.getCiphers(); + return (name) => ciphers.includes(CIPHER_INFO[name].sslName); + })(); + var DEFAULT_CIPHER = [ + // http://tools.ietf.org/html/rfc5647 + "aes128-gcm@openssh.com", + "aes256-gcm@openssh.com", + // http://tools.ietf.org/html/rfc4344#section-4 + "aes128-ctr", + "aes192-ctr", + "aes256-ctr" + ]; + if (cpuInfo && cpuInfo.flags && !cpuInfo.flags.aes) { + if (bindingAvailable) + DEFAULT_CIPHER.unshift("chacha20-poly1305@openssh.com"); + else + DEFAULT_CIPHER.push("chacha20-poly1305@openssh.com"); + } else if (bindingAvailable && cpuInfo && cpuInfo.arch === "x86") { + DEFAULT_CIPHER.splice(4, 0, "chacha20-poly1305@openssh.com"); + } else { + DEFAULT_CIPHER.push("chacha20-poly1305@openssh.com"); + } + DEFAULT_CIPHER = DEFAULT_CIPHER.filter(canUseCipher); + var SUPPORTED_CIPHER = DEFAULT_CIPHER.concat([ + "aes256-cbc", + "aes192-cbc", + "aes128-cbc", + "blowfish-cbc", + "3des-cbc", + "aes128-gcm", + "aes256-gcm", + // http://tools.ietf.org/html/rfc4345#section-4: + "arcfour256", + "arcfour128", + "cast128-cbc", + "arcfour" + ].filter(canUseCipher)); + var canUseMAC = (() => { + const hashes = crypto.getHashes(); + return (name) => hashes.includes(MAC_INFO[name].sslName); + })(); + var DEFAULT_MAC = [ + "hmac-sha2-256-etm@openssh.com", + "hmac-sha2-512-etm@openssh.com", + "hmac-sha1-etm@openssh.com", + "hmac-sha2-256", + "hmac-sha2-512", + "hmac-sha1" + ].filter(canUseMAC); + var SUPPORTED_MAC = DEFAULT_MAC.concat([ + "hmac-md5", + "hmac-sha2-256-96", + // first 96 bits of HMAC-SHA256 + "hmac-sha2-512-96", + // first 96 bits of HMAC-SHA512 + "hmac-ripemd160", + "hmac-sha1-96", + // first 96 bits of HMAC-SHA1 + "hmac-md5-96" + // first 96 bits of HMAC-MD5 + ].filter(canUseMAC)); + var DEFAULT_COMPRESSION = [ + "none", + "zlib@openssh.com", + // ZLIB (LZ77) compression, except + // compression/decompression does not start until after + // successful user authentication + "zlib" + // ZLIB (LZ77) compression + ]; + var SUPPORTED_COMPRESSION = DEFAULT_COMPRESSION.concat([]); + var COMPAT = { + BAD_DHGEX: 1 << 0, + OLD_EXIT: 1 << 1, + DYN_RPORT_BUG: 1 << 2, + BUG_DHGEX_LARGE: 1 << 3, + IMPLY_RSA_SHA2_SIGALGS: 1 << 4 + }; + module2.exports = { + MESSAGE: { + // Transport layer protocol -- generic (1-19) + DISCONNECT: 1, + IGNORE: 2, + UNIMPLEMENTED: 3, + DEBUG: 4, + SERVICE_REQUEST: 5, + SERVICE_ACCEPT: 6, + EXT_INFO: 7, + // RFC 8308 + // Transport layer protocol -- algorithm negotiation (20-29) + KEXINIT: 20, + NEWKEYS: 21, + // Transport layer protocol -- key exchange method-specific (30-49) + KEXDH_INIT: 30, + KEXDH_REPLY: 31, + KEXDH_GEX_GROUP: 31, + KEXDH_GEX_INIT: 32, + KEXDH_GEX_REPLY: 33, + KEXDH_GEX_REQUEST: 34, + KEXECDH_INIT: 30, + KEXECDH_REPLY: 31, + // User auth protocol -- generic (50-59) + USERAUTH_REQUEST: 50, + USERAUTH_FAILURE: 51, + USERAUTH_SUCCESS: 52, + USERAUTH_BANNER: 53, + // User auth protocol -- user auth method-specific (60-79) + USERAUTH_PASSWD_CHANGEREQ: 60, + USERAUTH_PK_OK: 60, + USERAUTH_INFO_REQUEST: 60, + USERAUTH_INFO_RESPONSE: 61, + // Connection protocol -- generic (80-89) + GLOBAL_REQUEST: 80, + REQUEST_SUCCESS: 81, + REQUEST_FAILURE: 82, + // Connection protocol -- channel-related (90-127) + CHANNEL_OPEN: 90, + CHANNEL_OPEN_CONFIRMATION: 91, + CHANNEL_OPEN_FAILURE: 92, + CHANNEL_WINDOW_ADJUST: 93, + CHANNEL_DATA: 94, + CHANNEL_EXTENDED_DATA: 95, + CHANNEL_EOF: 96, + CHANNEL_CLOSE: 97, + CHANNEL_REQUEST: 98, + CHANNEL_SUCCESS: 99, + CHANNEL_FAILURE: 100 + // Reserved for client protocols (128-191) + // Local extensions (192-155) + }, + DISCONNECT_REASON: { + HOST_NOT_ALLOWED_TO_CONNECT: 1, + PROTOCOL_ERROR: 2, + KEY_EXCHANGE_FAILED: 3, + RESERVED: 4, + MAC_ERROR: 5, + COMPRESSION_ERROR: 6, + SERVICE_NOT_AVAILABLE: 7, + PROTOCOL_VERSION_NOT_SUPPORTED: 8, + HOST_KEY_NOT_VERIFIABLE: 9, + CONNECTION_LOST: 10, + BY_APPLICATION: 11, + TOO_MANY_CONNECTIONS: 12, + AUTH_CANCELED_BY_USER: 13, + NO_MORE_AUTH_METHODS_AVAILABLE: 14, + ILLEGAL_USER_NAME: 15 + }, + DISCONNECT_REASON_STR: void 0, + CHANNEL_OPEN_FAILURE: { + ADMINISTRATIVELY_PROHIBITED: 1, + CONNECT_FAILED: 2, + UNKNOWN_CHANNEL_TYPE: 3, + RESOURCE_SHORTAGE: 4 + }, + TERMINAL_MODE: { + TTY_OP_END: 0, + // Indicates end of options. + VINTR: 1, + // Interrupt character; 255 if none. Similarly for the + // other characters. Not all of these characters are + // supported on all systems. + VQUIT: 2, + // The quit character (sends SIGQUIT signal on POSIX + // systems). + VERASE: 3, + // Erase the character to left of the cursor. + VKILL: 4, + // Kill the current input line. + VEOF: 5, + // End-of-file character (sends EOF from the + // terminal). + VEOL: 6, + // End-of-line character in addition to carriage + // return and/or linefeed. + VEOL2: 7, + // Additional end-of-line character. + VSTART: 8, + // Continues paused output (normally control-Q). + VSTOP: 9, + // Pauses output (normally control-S). + VSUSP: 10, + // Suspends the current program. + VDSUSP: 11, + // Another suspend character. + VREPRINT: 12, + // Reprints the current input line. + VWERASE: 13, + // Erases a word left of cursor. + VLNEXT: 14, + // Enter the next character typed literally, even if + // it is a special character + VFLUSH: 15, + // Character to flush output. + VSWTCH: 16, + // Switch to a different shell layer. + VSTATUS: 17, + // Prints system status line (load, command, pid, + // etc). + VDISCARD: 18, + // Toggles the flushing of terminal output. + IGNPAR: 30, + // The ignore parity flag. The parameter SHOULD be 0 + // if this flag is FALSE, and 1 if it is TRUE. + PARMRK: 31, + // Mark parity and framing errors. + INPCK: 32, + // Enable checking of parity errors. + ISTRIP: 33, + // Strip 8th bit off characters. + INLCR: 34, + // Map NL into CR on input. + IGNCR: 35, + // Ignore CR on input. + ICRNL: 36, + // Map CR to NL on input. + IUCLC: 37, + // Translate uppercase characters to lowercase. + IXON: 38, + // Enable output flow control. + IXANY: 39, + // Any char will restart after stop. + IXOFF: 40, + // Enable input flow control. + IMAXBEL: 41, + // Ring bell on input queue full. + ISIG: 50, + // Enable signals INTR, QUIT, [D]SUSP. + ICANON: 51, + // Canonicalize input lines. + XCASE: 52, + // Enable input and output of uppercase characters by + // preceding their lowercase equivalents with "\". + ECHO: 53, + // Enable echoing. + ECHOE: 54, + // Visually erase chars. + ECHOK: 55, + // Kill character discards current line. + ECHONL: 56, + // Echo NL even if ECHO is off. + NOFLSH: 57, + // Don't flush after interrupt. + TOSTOP: 58, + // Stop background jobs from output. + IEXTEN: 59, + // Enable extensions. + ECHOCTL: 60, + // Echo control characters as ^(Char). + ECHOKE: 61, + // Visual erase for line kill. + PENDIN: 62, + // Retype pending input. + OPOST: 70, + // Enable output processing. + OLCUC: 71, + // Convert lowercase to uppercase. + ONLCR: 72, + // Map NL to CR-NL. + OCRNL: 73, + // Translate carriage return to newline (output). + ONOCR: 74, + // Translate newline to carriage return-newline + // (output). + ONLRET: 75, + // Newline performs a carriage return (output). + CS7: 90, + // 7 bit mode. + CS8: 91, + // 8 bit mode. + PARENB: 92, + // Parity enable. + PARODD: 93, + // Odd parity, else even. + TTY_OP_ISPEED: 128, + // Specifies the input baud rate in bits per second. + TTY_OP_OSPEED: 129 + // Specifies the output baud rate in bits per second. + }, + CHANNEL_EXTENDED_DATATYPE: { + STDERR: 1 + }, + SIGNALS: [ + "ABRT", + "ALRM", + "FPE", + "HUP", + "ILL", + "INT", + "QUIT", + "SEGV", + "TERM", + "USR1", + "USR2", + "KILL", + "PIPE" + ].reduce((cur, val) => ({ ...cur, [val]: 1 }), {}), + COMPAT, + COMPAT_CHECKS: [ + ["Cisco-1.25", COMPAT.BAD_DHGEX], + [/^Cisco-1[.]/, COMPAT.BUG_DHGEX_LARGE], + [/^[0-9.]+$/, COMPAT.OLD_EXIT], + // old SSH.com implementations + [/^OpenSSH_5[.][0-9]+/, COMPAT.DYN_RPORT_BUG], + [/^OpenSSH_7[.]4/, COMPAT.IMPLY_RSA_SHA2_SIGALGS] + ], + // KEX proposal-related + DEFAULT_KEX, + SUPPORTED_KEX, + DEFAULT_SERVER_HOST_KEY, + SUPPORTED_SERVER_HOST_KEY, + DEFAULT_CIPHER, + SUPPORTED_CIPHER, + DEFAULT_MAC, + SUPPORTED_MAC, + DEFAULT_COMPRESSION, + SUPPORTED_COMPRESSION, + curve25519Supported, + eddsaSupported + }; + module2.exports.DISCONNECT_REASON_BY_VALUE = Array.from(Object.entries(module2.exports.DISCONNECT_REASON)).reduce((obj, [key, value]) => ({ ...obj, [value]: key }), {}); + } +}); + +// node_modules/ssh2/lib/protocol/utils.js +var require_utils3 = __commonJS({ + "node_modules/ssh2/lib/protocol/utils.js"(exports2, module2) { + "use strict"; + var Ber = require_lib2().Ber; + var DISCONNECT_REASON; + var FastBuffer = Buffer[Symbol.species]; + var TypedArrayFill = Object.getPrototypeOf(Uint8Array.prototype).fill; + function readUInt32BE(buf, offset) { + return buf[offset++] * 16777216 + buf[offset++] * 65536 + buf[offset++] * 256 + buf[offset]; + } + function bufferCopy(src, dest, srcStart, srcEnd, destStart) { + if (!destStart) + destStart = 0; + if (srcEnd > src.length) + srcEnd = src.length; + let nb = srcEnd - srcStart; + const destLeft = dest.length - destStart; + if (nb > destLeft) + nb = destLeft; + dest.set( + new Uint8Array(src.buffer, src.byteOffset + srcStart, nb), + destStart + ); + return nb; + } + function bufferSlice(buf, start, end) { + if (end === void 0) + end = buf.length; + return new FastBuffer(buf.buffer, buf.byteOffset + start, end - start); + } + function makeBufferParser() { + let pos = 0; + let buffer; + const self2 = { + init: (buf, start) => { + buffer = buf; + pos = typeof start === "number" ? start : 0; + }, + pos: () => pos, + length: () => buffer ? buffer.length : 0, + avail: () => buffer && pos < buffer.length ? buffer.length - pos : 0, + clear: () => { + buffer = void 0; + }, + readUInt32BE: () => { + if (!buffer || pos + 3 >= buffer.length) + return; + return buffer[pos++] * 16777216 + buffer[pos++] * 65536 + buffer[pos++] * 256 + buffer[pos++]; + }, + readUInt64BE: (behavior) => { + if (!buffer || pos + 7 >= buffer.length) + return; + switch (behavior) { + case "always": + return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`); + case "maybe": + if (buffer[pos] > 31) + return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`); + // FALLTHROUGH + default: + return buffer[pos++] * 72057594037927940 + buffer[pos++] * 281474976710656 + buffer[pos++] * 1099511627776 + buffer[pos++] * 4294967296 + buffer[pos++] * 16777216 + buffer[pos++] * 65536 + buffer[pos++] * 256 + buffer[pos++]; + } + }, + skip: (n) => { + if (buffer && n > 0) + pos += n; + }, + skipString: () => { + const len = self2.readUInt32BE(); + if (len === void 0) + return; + pos += len; + return pos <= buffer.length ? len : void 0; + }, + readByte: () => { + if (buffer && pos < buffer.length) + return buffer[pos++]; + }, + readBool: () => { + if (buffer && pos < buffer.length) + return !!buffer[pos++]; + }, + readList: () => { + const list = self2.readString(true); + if (list === void 0) + return; + return list ? list.split(",") : []; + }, + readString: (dest, maxLen) => { + if (typeof dest === "number") { + maxLen = dest; + dest = void 0; + } + const len = self2.readUInt32BE(); + if (len === void 0) + return; + if (buffer.length - pos < len || typeof maxLen === "number" && len > maxLen) { + return; + } + if (dest) { + if (Buffer.isBuffer(dest)) + return bufferCopy(buffer, dest, pos, pos += len); + return buffer.utf8Slice(pos, pos += len); + } + return bufferSlice(buffer, pos, pos += len); + }, + readRaw: (len) => { + if (!buffer) + return; + if (typeof len !== "number") + return bufferSlice(buffer, pos, pos += buffer.length - pos); + if (buffer.length - pos >= len) + return bufferSlice(buffer, pos, pos += len); + } + }; + return self2; + } + function makeError(msg, level, fatal) { + const err = new Error(msg); + if (typeof level === "boolean") { + fatal = level; + err.level = "protocol"; + } else { + err.level = level || "protocol"; + } + err.fatal = !!fatal; + return err; + } + function writeUInt32BE(buf, value, offset) { + buf[offset++] = value >>> 24; + buf[offset++] = value >>> 16; + buf[offset++] = value >>> 8; + buf[offset++] = value; + return offset; + } + var utilBufferParser = makeBufferParser(); + module2.exports = { + bufferCopy, + bufferSlice, + FastBuffer, + bufferFill: (buf, value, start, end) => { + return TypedArrayFill.call(buf, value, start, end); + }, + makeError, + doFatalError: (protocol, msg, level, reason) => { + let err; + if (DISCONNECT_REASON === void 0) + ({ DISCONNECT_REASON } = require_constants6()); + if (msg instanceof Error) { + err = msg; + if (typeof level !== "number") + reason = DISCONNECT_REASON.PROTOCOL_ERROR; + else + reason = level; + } else { + err = makeError(msg, level, true); + } + if (typeof reason !== "number") + reason = DISCONNECT_REASON.PROTOCOL_ERROR; + protocol.disconnect(reason); + protocol._destruct(); + protocol._onError(err); + return Infinity; + }, + readUInt32BE, + writeUInt32BE, + writeUInt32LE: (buf, value, offset) => { + buf[offset++] = value; + buf[offset++] = value >>> 8; + buf[offset++] = value >>> 16; + buf[offset++] = value >>> 24; + return offset; + }, + makeBufferParser, + bufferParser: makeBufferParser(), + readString: (buffer, start, dest, maxLen) => { + if (typeof dest === "number") { + maxLen = dest; + dest = void 0; + } + if (start === void 0) + start = 0; + const left = buffer.length - start; + if (start < 0 || start >= buffer.length || left < 4) + return; + const len = readUInt32BE(buffer, start); + if (left < 4 + len || typeof maxLen === "number" && len > maxLen) + return; + start += 4; + const end = start + len; + buffer._pos = end; + if (dest) { + if (Buffer.isBuffer(dest)) + return bufferCopy(buffer, dest, start, end); + return buffer.utf8Slice(start, end); + } + return bufferSlice(buffer, start, end); + }, + sigSSHToASN1: (sig, type) => { + switch (type) { + case "ssh-dss": { + if (sig.length > 40) + return sig; + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + let r = sig.slice(0, 20); + let s = sig.slice(20); + if (r[0] & 128) { + const rNew = Buffer.allocUnsafe(21); + rNew[0] = 0; + r.copy(rNew, 1); + r = rNew; + } else if (r[0] === 0 && !(r[1] & 128)) { + r = r.slice(1); + } + if (s[0] & 128) { + const sNew = Buffer.allocUnsafe(21); + sNew[0] = 0; + s.copy(sNew, 1); + s = sNew; + } else if (s[0] === 0 && !(s[1] & 128)) { + s = s.slice(1); + } + asnWriter.writeBuffer(r, Ber.Integer); + asnWriter.writeBuffer(s, Ber.Integer); + asnWriter.endSequence(); + return asnWriter.buffer; + } + case "ecdsa-sha2-nistp256": + case "ecdsa-sha2-nistp384": + case "ecdsa-sha2-nistp521": { + utilBufferParser.init(sig, 0); + const r = utilBufferParser.readString(); + const s = utilBufferParser.readString(); + utilBufferParser.clear(); + if (r === void 0 || s === void 0) + return; + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + asnWriter.writeBuffer(r, Ber.Integer); + asnWriter.writeBuffer(s, Ber.Integer); + asnWriter.endSequence(); + return asnWriter.buffer; + } + default: + return sig; + } + }, + convertSignature: (signature, keyType) => { + switch (keyType) { + case "ssh-dss": { + if (signature.length <= 40) + return signature; + const asnReader = new Ber.Reader(signature); + asnReader.readSequence(); + let r = asnReader.readString(Ber.Integer, true); + let s = asnReader.readString(Ber.Integer, true); + let rOffset = 0; + let sOffset = 0; + if (r.length < 20) { + const rNew = Buffer.allocUnsafe(20); + rNew.set(r, 1); + r = rNew; + r[0] = 0; + } + if (s.length < 20) { + const sNew = Buffer.allocUnsafe(20); + sNew.set(s, 1); + s = sNew; + s[0] = 0; + } + if (r.length > 20 && r[0] === 0) + rOffset = 1; + if (s.length > 20 && s[0] === 0) + sOffset = 1; + const newSig = Buffer.allocUnsafe(r.length - rOffset + (s.length - sOffset)); + bufferCopy(r, newSig, rOffset, r.length, 0); + bufferCopy(s, newSig, sOffset, s.length, r.length - rOffset); + return newSig; + } + case "ecdsa-sha2-nistp256": + case "ecdsa-sha2-nistp384": + case "ecdsa-sha2-nistp521": { + if (signature[0] === 0) + return signature; + const asnReader = new Ber.Reader(signature); + asnReader.readSequence(); + const r = asnReader.readString(Ber.Integer, true); + const s = asnReader.readString(Ber.Integer, true); + if (r === null || s === null) + return; + const newSig = Buffer.allocUnsafe(4 + r.length + 4 + s.length); + writeUInt32BE(newSig, r.length, 0); + newSig.set(r, 4); + writeUInt32BE(newSig, s.length, 4 + r.length); + newSig.set(s, 4 + 4 + r.length); + return newSig; + } + } + return signature; + }, + sendPacket: (proto, packet, bypass) => { + if (!bypass && proto._kexinit !== void 0) { + if (proto._queue === void 0) + proto._queue = []; + proto._queue.push(packet); + proto._debug && proto._debug("Outbound: ... packet queued"); + return false; + } + proto._cipher.encrypt(packet); + return true; + } + }; + } +}); + +// node_modules/ssh2/lib/protocol/crypto/build/Release/sshcrypto.node +var require_sshcrypto = __commonJS({ + "node_modules/ssh2/lib/protocol/crypto/build/Release/sshcrypto.node"() { + } +}); + +// node_modules/ssh2/lib/protocol/crypto/poly1305.js +var require_poly1305 = __commonJS({ + "node_modules/ssh2/lib/protocol/crypto/poly1305.js"(exports2, module2) { + var createPoly1305 = (function() { + var _scriptDir = typeof document !== "undefined" && document.currentScript ? document.currentScript.src : void 0; + if (typeof __filename !== "undefined") _scriptDir = _scriptDir || __filename; + return (function(createPoly13052) { + createPoly13052 = createPoly13052 || {}; + var b; + b || (b = typeof createPoly13052 !== "undefined" ? createPoly13052 : {}); + var q, r; + b.ready = new Promise(function(a, c) { + q = a; + r = c; + }); + var u = {}, w; + for (w in b) b.hasOwnProperty(w) && (u[w] = b[w]); + var x = "object" === typeof window, y = "function" === typeof importScripts, z = "object" === typeof process && "object" === typeof process.versions && "string" === typeof process.versions.node, B = "", C, D, E, F, G; + if (z) B = y ? require("path").dirname(B) + "/" : __dirname + "/", C = function(a, c) { + var d = H(a); + if (d) return c ? d : d.toString(); + F || (F = require("fs")); + G || (G = require("path")); + a = G.normalize(a); + return F.readFileSync(a, c ? null : "utf8"); + }, E = function(a) { + a = C(a, true); + a.buffer || (a = new Uint8Array(a)); + assert(a.buffer); + return a; + }, D = function(a, c, d) { + var e = H(a); + e && c(e); + F || (F = require("fs")); + G || (G = require("path")); + a = G.normalize(a); + F.readFile(a, function(f, l) { + f ? d(f) : c(l.buffer); + }); + }, 1 < process.argv.length && process.argv[1].replace(/\\/g, "/"), process.argv.slice(2), b.inspect = function() { + return "[Emscripten Module object]"; + }; + else if (x || y) y ? B = self.location.href : "undefined" !== typeof document && document.currentScript && (B = document.currentScript.src), _scriptDir && (B = _scriptDir), 0 !== B.indexOf("blob:") ? B = B.substr(0, B.lastIndexOf("/") + 1) : B = "", C = function(a) { + try { + var c = new XMLHttpRequest(); + c.open("GET", a, false); + c.send(null); + return c.responseText; + } catch (f) { + if (a = H(a)) { + c = []; + for (var d = 0; d < a.length; d++) { + var e = a[d]; + 255 < e && (ba && assert(false, "Character code " + e + " (" + String.fromCharCode(e) + ") at offset " + d + " not in 0x00-0xFF."), e &= 255); + c.push(String.fromCharCode(e)); + } + return c.join(""); + } + throw f; + } + }, y && (E = function(a) { + try { + var c = new XMLHttpRequest(); + c.open("GET", a, false); + c.responseType = "arraybuffer"; + c.send(null); + return new Uint8Array(c.response); + } catch (d) { + if (a = H(a)) return a; + throw d; + } + }), D = function(a, c, d) { + var e = new XMLHttpRequest(); + e.open("GET", a, true); + e.responseType = "arraybuffer"; + e.onload = function() { + if (200 == e.status || 0 == e.status && e.response) c(e.response); + else { + var f = H(a); + f ? c(f.buffer) : d(); + } + }; + e.onerror = d; + e.send(null); + }; + b.print || console.log.bind(console); + var I = b.printErr || console.warn.bind(console); + for (w in u) u.hasOwnProperty(w) && (b[w] = u[w]); + u = null; + var J; + b.wasmBinary && (J = b.wasmBinary); + var noExitRuntime = b.noExitRuntime || true; + "object" !== typeof WebAssembly && K("no native wasm support detected"); + var L, M = false; + function assert(a, c) { + a || K("Assertion failed: " + c); + } + function N(a) { + var c = b["_" + a]; + assert(c, "Cannot call unknown function " + a + ", make sure it is exported"); + return c; + } + function ca(a, c, d, e) { + var f = { string: function(g) { + var p = 0; + if (null !== g && void 0 !== g && 0 !== g) { + var n = (g.length << 2) + 1; + p = O(n); + var k = p, h = P; + if (0 < n) { + n = k + n - 1; + for (var v = 0; v < g.length; ++v) { + var m = g.charCodeAt(v); + if (55296 <= m && 57343 >= m) { + var oa = g.charCodeAt(++v); + m = 65536 + ((m & 1023) << 10) | oa & 1023; + } + if (127 >= m) { + if (k >= n) break; + h[k++] = m; + } else { + if (2047 >= m) { + if (k + 1 >= n) break; + h[k++] = 192 | m >> 6; + } else { + if (65535 >= m) { + if (k + 2 >= n) break; + h[k++] = 224 | m >> 12; + } else { + if (k + 3 >= n) break; + h[k++] = 240 | m >> 18; + h[k++] = 128 | m >> 12 & 63; + } + h[k++] = 128 | m >> 6 & 63; + } + h[k++] = 128 | m & 63; + } + } + h[k] = 0; + } + } + return p; + }, array: function(g) { + var p = O(g.length); + Q.set(g, p); + return p; + } }, l = N(a), A = []; + a = 0; + if (e) for (var t = 0; t < e.length; t++) { + var aa = f[d[t]]; + aa ? (0 === a && (a = da()), A[t] = aa(e[t])) : A[t] = e[t]; + } + d = l.apply(null, A); + d = (function(g) { + if ("string" === c) if (g) { + for (var p = P, n = g + NaN, k = g; p[k] && !(k >= n); ) ++k; + if (16 < k - g && p.subarray && ea) g = ea.decode(p.subarray(g, k)); + else { + for (n = ""; g < k; ) { + var h = p[g++]; + if (h & 128) { + var v = p[g++] & 63; + if (192 == (h & 224)) n += String.fromCharCode((h & 31) << 6 | v); + else { + var m = p[g++] & 63; + h = 224 == (h & 240) ? (h & 15) << 12 | v << 6 | m : (h & 7) << 18 | v << 12 | m << 6 | p[g++] & 63; + 65536 > h ? n += String.fromCharCode(h) : (h -= 65536, n += String.fromCharCode(55296 | h >> 10, 56320 | h & 1023)); + } + } else n += String.fromCharCode(h); + } + g = n; + } + } else g = ""; + else g = "boolean" === c ? !!g : g; + return g; + })(d); + 0 !== a && fa(a); + return d; + } + var ea = "undefined" !== typeof TextDecoder ? new TextDecoder("utf8") : void 0, ha, Q, P; + function ia() { + var a = L.buffer; + ha = a; + b.HEAP8 = Q = new Int8Array(a); + b.HEAP16 = new Int16Array(a); + b.HEAP32 = new Int32Array(a); + b.HEAPU8 = P = new Uint8Array(a); + b.HEAPU16 = new Uint16Array(a); + b.HEAPU32 = new Uint32Array(a); + b.HEAPF32 = new Float32Array(a); + b.HEAPF64 = new Float64Array(a); + } + var R, ja = [], ka = [], la = []; + function ma() { + var a = b.preRun.shift(); + ja.unshift(a); + } + var S = 0, T = null, U = null; + b.preloadedImages = {}; + b.preloadedAudios = {}; + function K(a) { + if (b.onAbort) b.onAbort(a); + I(a); + M = true; + a = new WebAssembly.RuntimeError("abort(" + a + "). Build with -s ASSERTIONS=1 for more info."); + r(a); + throw a; + } + var V = "data:application/octet-stream;base64,", W; + W = "data:application/octet-stream;base64,AGFzbQEAAAABIAZgAX8Bf2ADf39/AGABfwBgAABgAAF/YAZ/f39/f38AAgcBAWEBYQAAAwsKAAEDAQAAAgQFAgQFAXABAQEFBwEBgAKAgAIGCQF/AUGAjMACCwclCQFiAgABYwADAWQACQFlAAgBZgAHAWcABgFoAAUBaQAKAWoBAAqGTQpPAQJ/QYAIKAIAIgEgAEEDakF8cSICaiEAAkAgAkEAIAAgAU0bDQAgAD8AQRB0SwRAIAAQAEUNAQtBgAggADYCACABDwtBhAhBMDYCAEF/C4wFAg5+Cn8gACgCJCEUIAAoAiAhFSAAKAIcIREgACgCGCESIAAoAhQhEyACQRBPBEAgAC0ATEVBGHQhFyAAKAIEIhZBBWytIQ8gACgCCCIYQQVsrSENIAAoAgwiGUEFbK0hCyAAKAIQIhpBBWytIQkgADUCACEIIBqtIRAgGa0hDiAYrSEMIBatIQoDQCASIAEtAAMiEiABLQAEQQh0ciABLQAFQRB0ciABLQAGIhZBGHRyQQJ2Qf///x9xaq0iAyAOfiABLwAAIAEtAAJBEHRyIBNqIBJBGHRBgICAGHFqrSIEIBB+fCARIAEtAAdBCHQgFnIgAS0ACEEQdHIgAS0ACSIRQRh0ckEEdkH///8fcWqtIgUgDH58IAEtAApBCHQgEXIgAS0AC0EQdHIgAS0ADEEYdHJBBnYgFWqtIgYgCn58IBQgF2ogAS8ADSABLQAPQRB0cmqtIgcgCH58IAMgDH4gBCAOfnwgBSAKfnwgBiAIfnwgByAJfnwgAyAKfiAEIAx+fCAFIAh+fCAGIAl+fCAHIAt+fCADIAh+IAQgCn58IAUgCX58IAYgC358IAcgDX58IAMgCX4gBCAIfnwgBSALfnwgBiANfnwgByAPfnwiA0IaiEL/////D4N8IgRCGohC/////w+DfCIFQhqIQv////8Pg3wiBkIaiEL/////D4N8IgdCGoinQQVsIAOnQf///x9xaiITQRp2IASnQf///x9xaiESIAWnQf///x9xIREgBqdB////H3EhFSAHp0H///8fcSEUIBNB////H3EhEyABQRBqIQEgAkEQayICQQ9LDQALCyAAIBQ2AiQgACAVNgIgIAAgETYCHCAAIBI2AhggACATNgIUCwMAAQu2BAEGfwJAIAAoAjgiBARAIABBPGohBQJAIAJBECAEayIDIAIgA0kbIgZFDQAgBkEDcSEHAkAgBkEBa0EDSQRAQQAhAwwBCyAGQXxxIQhBACEDA0AgBSADIARqaiABIANqLQAAOgAAIAUgA0EBciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0ECciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0EDciIEIAAoAjhqaiABIARqLQAAOgAAIANBBGohAyAAKAI4IQQgCEEEayIIDQALCyAHRQ0AA0AgBSADIARqaiABIANqLQAAOgAAIANBAWohAyAAKAI4IQQgB0EBayIHDQALCyAAIAQgBmoiAzYCOCADQRBJDQEgACAFQRAQAiAAQQA2AjggAiAGayECIAEgBmohAQsgAkEQTwRAIAAgASACQXBxIgMQAiACQQ9xIQIgASADaiEBCyACRQ0AIAJBA3EhBCAAQTxqIQVBACEDIAJBAWtBA08EQCACQXxxIQcDQCAFIAAoAjggA2pqIAEgA2otAAA6AAAgBSADQQFyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQJyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQNyIgYgACgCOGpqIAEgBmotAAA6AAAgA0EEaiEDIAdBBGsiBw0ACwsgBARAA0AgBSAAKAI4IANqaiABIANqLQAAOgAAIANBAWohAyAEQQFrIgQNAAsLIAAgACgCOCACajYCOAsLoS0BDH8jAEEQayIMJAACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAEH0AU0EQEGICCgCACIFQRAgAEELakF4cSAAQQtJGyIIQQN2IgJ2IgFBA3EEQCABQX9zQQFxIAJqIgNBA3QiAUG4CGooAgAiBEEIaiEAAkAgBCgCCCICIAFBsAhqIgFGBEBBiAggBUF+IAN3cTYCAAwBCyACIAE2AgwgASACNgIICyAEIANBA3QiAUEDcjYCBCABIARqIgEgASgCBEEBcjYCBAwNCyAIQZAIKAIAIgpNDQEgAQRAAkBBAiACdCIAQQAgAGtyIAEgAnRxIgBBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2aiIDQQN0IgBBuAhqKAIAIgQoAggiASAAQbAIaiIARgRAQYgIIAVBfiADd3EiBTYCAAwBCyABIAA2AgwgACABNgIICyAEQQhqIQAgBCAIQQNyNgIEIAQgCGoiAiADQQN0IgEgCGsiA0EBcjYCBCABIARqIAM2AgAgCgRAIApBA3YiAUEDdEGwCGohB0GcCCgCACEEAn8gBUEBIAF0IgFxRQRAQYgIIAEgBXI2AgAgBwwBCyAHKAIICyEBIAcgBDYCCCABIAQ2AgwgBCAHNgIMIAQgATYCCAtBnAggAjYCAEGQCCADNgIADA0LQYwIKAIAIgZFDQEgBkEAIAZrcUEBayIAIABBDHZBEHEiAnYiAUEFdkEIcSIAIAJyIAEgAHYiAUECdkEEcSIAciABIAB2IgFBAXZBAnEiAHIgASAAdiIBQQF2QQFxIgByIAEgAHZqQQJ0QbgKaigCACIBKAIEQXhxIAhrIQMgASECA0ACQCACKAIQIgBFBEAgAigCFCIARQ0BCyAAKAIEQXhxIAhrIgIgAyACIANJIgIbIQMgACABIAIbIQEgACECDAELCyABIAhqIgkgAU0NAiABKAIYIQsgASABKAIMIgRHBEAgASgCCCIAQZgIKAIASRogACAENgIMIAQgADYCCAwMCyABQRRqIgIoAgAiAEUEQCABKAIQIgBFDQQgAUEQaiECCwNAIAIhByAAIgRBFGoiAigCACIADQAgBEEQaiECIAQoAhAiAA0ACyAHQQA2AgAMCwtBfyEIIABBv39LDQAgAEELaiIAQXhxIQhBjAgoAgAiCUUNAEEAIAhrIQMCQAJAAkACf0EAIAhBgAJJDQAaQR8gCEH///8HSw0AGiAAQQh2IgAgAEGA/j9qQRB2QQhxIgJ0IgAgAEGA4B9qQRB2QQRxIgF0IgAgAEGAgA9qQRB2QQJxIgB0QQ92IAEgAnIgAHJrIgBBAXQgCCAAQRVqdkEBcXJBHGoLIgVBAnRBuApqKAIAIgJFBEBBACEADAELQQAhACAIQQBBGSAFQQF2ayAFQR9GG3QhAQNAAkAgAigCBEF4cSAIayIHIANPDQAgAiEEIAciAw0AQQAhAyACIQAMAwsgACACKAIUIgcgByACIAFBHXZBBHFqKAIQIgJGGyAAIAcbIQAgAUEBdCEBIAINAAsLIAAgBHJFBEBBACEEQQIgBXQiAEEAIABrciAJcSIARQ0DIABBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2akECdEG4CmooAgAhAAsgAEUNAQsDQCAAKAIEQXhxIAhrIgEgA0khAiABIAMgAhshAyAAIAQgAhshBCAAKAIQIgEEfyABBSAAKAIUCyIADQALCyAERQ0AIANBkAgoAgAgCGtPDQAgBCAIaiIGIARNDQEgBCgCGCEFIAQgBCgCDCIBRwRAIAQoAggiAEGYCCgCAEkaIAAgATYCDCABIAA2AggMCgsgBEEUaiICKAIAIgBFBEAgBCgCECIARQ0EIARBEGohAgsDQCACIQcgACIBQRRqIgIoAgAiAA0AIAFBEGohAiABKAIQIgANAAsgB0EANgIADAkLIAhBkAgoAgAiAk0EQEGcCCgCACEDAkAgAiAIayIBQRBPBEBBkAggATYCAEGcCCADIAhqIgA2AgAgACABQQFyNgIEIAIgA2ogATYCACADIAhBA3I2AgQMAQtBnAhBADYCAEGQCEEANgIAIAMgAkEDcjYCBCACIANqIgAgACgCBEEBcjYCBAsgA0EIaiEADAsLIAhBlAgoAgAiBkkEQEGUCCAGIAhrIgE2AgBBoAhBoAgoAgAiAiAIaiIANgIAIAAgAUEBcjYCBCACIAhBA3I2AgQgAkEIaiEADAsLQQAhACAIQS9qIgkCf0HgCygCAARAQegLKAIADAELQewLQn83AgBB5AtCgKCAgICABDcCAEHgCyAMQQxqQXBxQdiq1aoFczYCAEH0C0EANgIAQcQLQQA2AgBBgCALIgFqIgVBACABayIHcSICIAhNDQpBwAsoAgAiBARAQbgLKAIAIgMgAmoiASADTQ0LIAEgBEsNCwtBxAstAABBBHENBQJAAkBBoAgoAgAiAwRAQcgLIQADQCADIAAoAgAiAU8EQCABIAAoAgRqIANLDQMLIAAoAggiAA0ACwtBABABIgFBf0YNBiACIQVB5AsoAgAiA0EBayIAIAFxBEAgAiABayAAIAFqQQAgA2txaiEFCyAFIAhNDQYgBUH+////B0sNBkHACygCACIEBEBBuAsoAgAiAyAFaiIAIANNDQcgACAESw0HCyAFEAEiACABRw0BDAgLIAUgBmsgB3EiBUH+////B0sNBSAFEAEiASAAKAIAIAAoAgRqRg0EIAEhAAsCQCAAQX9GDQAgCEEwaiAFTQ0AQegLKAIAIgEgCSAFa2pBACABa3EiAUH+////B0sEQCAAIQEMCAsgARABQX9HBEAgASAFaiEFIAAhAQwIC0EAIAVrEAEaDAULIAAiAUF/Rw0GDAQLAAtBACEEDAcLQQAhAQwFCyABQX9HDQILQcQLQcQLKAIAQQRyNgIACyACQf7///8HSw0BIAIQASEBQQAQASEAIAFBf0YNASAAQX9GDQEgACABTQ0BIAAgAWsiBSAIQShqTQ0BC0G4C0G4CygCACAFaiIANgIAQbwLKAIAIABJBEBBvAsgADYCAAsCQAJAAkBBoAgoAgAiBwRAQcgLIQADQCABIAAoAgAiAyAAKAIEIgJqRg0CIAAoAggiAA0ACwwCC0GYCCgCACIAQQAgACABTRtFBEBBmAggATYCAAtBACEAQcwLIAU2AgBByAsgATYCAEGoCEF/NgIAQawIQeALKAIANgIAQdQLQQA2AgADQCAAQQN0IgNBuAhqIANBsAhqIgI2AgAgA0G8CGogAjYCACAAQQFqIgBBIEcNAAtBlAggBUEoayIDQXggAWtBB3FBACABQQhqQQdxGyIAayICNgIAQaAIIAAgAWoiADYCACAAIAJBAXI2AgQgASADakEoNgIEQaQIQfALKAIANgIADAILIAAtAAxBCHENACADIAdLDQAgASAHTQ0AIAAgAiAFajYCBEGgCCAHQXggB2tBB3FBACAHQQhqQQdxGyIAaiICNgIAQZQIQZQIKAIAIAVqIgEgAGsiADYCACACIABBAXI2AgQgASAHakEoNgIEQaQIQfALKAIANgIADAELQZgIKAIAIAFLBEBBmAggATYCAAsgASAFaiECQcgLIQACQAJAAkACQAJAAkADQCACIAAoAgBHBEAgACgCCCIADQEMAgsLIAAtAAxBCHFFDQELQcgLIQADQCAHIAAoAgAiAk8EQCACIAAoAgRqIgQgB0sNAwsgACgCCCEADAALAAsgACABNgIAIAAgACgCBCAFajYCBCABQXggAWtBB3FBACABQQhqQQdxG2oiCSAIQQNyNgIEIAJBeCACa0EHcUEAIAJBCGpBB3EbaiIFIAggCWoiBmshAiAFIAdGBEBBoAggBjYCAEGUCEGUCCgCACACaiIANgIAIAYgAEEBcjYCBAwDCyAFQZwIKAIARgRAQZwIIAY2AgBBkAhBkAgoAgAgAmoiADYCACAGIABBAXI2AgQgACAGaiAANgIADAMLIAUoAgQiAEEDcUEBRgRAIABBeHEhBwJAIABB/wFNBEAgBSgCCCIDIABBA3YiAEEDdEGwCGpGGiADIAUoAgwiAUYEQEGICEGICCgCAEF+IAB3cTYCAAwCCyADIAE2AgwgASADNgIIDAELIAUoAhghCAJAIAUgBSgCDCIBRwRAIAUoAggiACABNgIMIAEgADYCCAwBCwJAIAVBFGoiACgCACIDDQAgBUEQaiIAKAIAIgMNAEEAIQEMAQsDQCAAIQQgAyIBQRRqIgAoAgAiAw0AIAFBEGohACABKAIQIgMNAAsgBEEANgIACyAIRQ0AAkAgBSAFKAIcIgNBAnRBuApqIgAoAgBGBEAgACABNgIAIAENAUGMCEGMCCgCAEF+IAN3cTYCAAwCCyAIQRBBFCAIKAIQIAVGG2ogATYCACABRQ0BCyABIAg2AhggBSgCECIABEAgASAANgIQIAAgATYCGAsgBSgCFCIARQ0AIAEgADYCFCAAIAE2AhgLIAUgB2ohBSACIAdqIQILIAUgBSgCBEF+cTYCBCAGIAJBAXI2AgQgAiAGaiACNgIAIAJB/wFNBEAgAkEDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwDC0EfIQAgAkH///8HTQRAIAJBCHYiACAAQYD+P2pBEHZBCHEiA3QiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASADciAAcmsiAEEBdCACIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQQCQEGMCCgCACIDQQEgAHQiAXFFBEBBjAggASADcjYCACAEIAY2AgAgBiAENgIYDAELIAJBAEEZIABBAXZrIABBH0YbdCEAIAQoAgAhAQNAIAEiAygCBEF4cSACRg0DIABBHXYhASAAQQF0IQAgAyABQQRxaiIEKAIQIgENAAsgBCAGNgIQIAYgAzYCGAsgBiAGNgIMIAYgBjYCCAwCC0GUCCAFQShrIgNBeCABa0EHcUEAIAFBCGpBB3EbIgBrIgI2AgBBoAggACABaiIANgIAIAAgAkEBcjYCBCABIANqQSg2AgRBpAhB8AsoAgA2AgAgByAEQScgBGtBB3FBACAEQSdrQQdxG2pBL2siACAAIAdBEGpJGyICQRs2AgQgAkHQCykCADcCECACQcgLKQIANwIIQdALIAJBCGo2AgBBzAsgBTYCAEHICyABNgIAQdQLQQA2AgAgAkEYaiEAA0AgAEEHNgIEIABBCGohASAAQQRqIQAgASAESQ0ACyACIAdGDQMgAiACKAIEQX5xNgIEIAcgAiAHayIEQQFyNgIEIAIgBDYCACAEQf8BTQRAIARBA3YiAEEDdEGwCGohAgJ/QYgIKAIAIgFBASAAdCIAcUUEQEGICCAAIAFyNgIAIAIMAQsgAigCCAshACACIAc2AgggACAHNgIMIAcgAjYCDCAHIAA2AggMBAtBHyEAIAdCADcCECAEQf///wdNBEAgBEEIdiIAIABBgP4/akEQdkEIcSICdCIAIABBgOAfakEQdkEEcSIBdCIAIABBgIAPakEQdkECcSIAdEEPdiABIAJyIAByayIAQQF0IAQgAEEVanZBAXFyQRxqIQALIAcgADYCHCAAQQJ0QbgKaiEDAkBBjAgoAgAiAkEBIAB0IgFxRQRAQYwIIAEgAnI2AgAgAyAHNgIAIAcgAzYCGAwBCyAEQQBBGSAAQQF2ayAAQR9GG3QhACADKAIAIQEDQCABIgIoAgRBeHEgBEYNBCAAQR12IQEgAEEBdCEAIAIgAUEEcWoiAygCECIBDQALIAMgBzYCECAHIAI2AhgLIAcgBzYCDCAHIAc2AggMAwsgAygCCCIAIAY2AgwgAyAGNgIIIAZBADYCGCAGIAM2AgwgBiAANgIICyAJQQhqIQAMBQsgAigCCCIAIAc2AgwgAiAHNgIIIAdBADYCGCAHIAI2AgwgByAANgIIC0GUCCgCACIAIAhNDQBBlAggACAIayIBNgIAQaAIQaAIKAIAIgIgCGoiADYCACAAIAFBAXI2AgQgAiAIQQNyNgIEIAJBCGohAAwDC0GECEEwNgIAQQAhAAwCCwJAIAVFDQACQCAEKAIcIgJBAnRBuApqIgAoAgAgBEYEQCAAIAE2AgAgAQ0BQYwIIAlBfiACd3EiCTYCAAwCCyAFQRBBFCAFKAIQIARGG2ogATYCACABRQ0BCyABIAU2AhggBCgCECIABEAgASAANgIQIAAgATYCGAsgBCgCFCIARQ0AIAEgADYCFCAAIAE2AhgLAkAgA0EPTQRAIAQgAyAIaiIAQQNyNgIEIAAgBGoiACAAKAIEQQFyNgIEDAELIAQgCEEDcjYCBCAGIANBAXI2AgQgAyAGaiADNgIAIANB/wFNBEAgA0EDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwBC0EfIQAgA0H///8HTQRAIANBCHYiACAAQYD+P2pBEHZBCHEiAnQiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASACciAAcmsiAEEBdCADIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQICQAJAIAlBASAAdCIBcUUEQEGMCCABIAlyNgIAIAIgBjYCACAGIAI2AhgMAQsgA0EAQRkgAEEBdmsgAEEfRht0IQAgAigCACEIA0AgCCIBKAIEQXhxIANGDQIgAEEddiECIABBAXQhACABIAJBBHFqIgIoAhAiCA0ACyACIAY2AhAgBiABNgIYCyAGIAY2AgwgBiAGNgIIDAELIAEoAggiACAGNgIMIAEgBjYCCCAGQQA2AhggBiABNgIMIAYgADYCCAsgBEEIaiEADAELAkAgC0UNAAJAIAEoAhwiAkECdEG4CmoiACgCACABRgRAIAAgBDYCACAEDQFBjAggBkF+IAJ3cTYCAAwCCyALQRBBFCALKAIQIAFGG2ogBDYCACAERQ0BCyAEIAs2AhggASgCECIABEAgBCAANgIQIAAgBDYCGAsgASgCFCIARQ0AIAQgADYCFCAAIAQ2AhgLAkAgA0EPTQRAIAEgAyAIaiIAQQNyNgIEIAAgAWoiACAAKAIEQQFyNgIEDAELIAEgCEEDcjYCBCAJIANBAXI2AgQgAyAJaiADNgIAIAoEQCAKQQN2IgBBA3RBsAhqIQRBnAgoAgAhAgJ/QQEgAHQiACAFcUUEQEGICCAAIAVyNgIAIAQMAQsgBCgCCAshACAEIAI2AgggACACNgIMIAIgBDYCDCACIAA2AggLQZwIIAk2AgBBkAggAzYCAAsgAUEIaiEACyAMQRBqJAAgAAsQACMAIABrQXBxIgAkACAACwYAIAAkAAsEACMAC4AJAgh/BH4jAEGQAWsiBiQAIAYgBS0AA0EYdEGAgIAYcSAFLwAAIAUtAAJBEHRycjYCACAGIAUoAANBAnZBg/7/H3E2AgQgBiAFKAAGQQR2Qf+B/x9xNgIIIAYgBSgACUEGdkH//8AfcTYCDCAFLwANIQggBS0ADyEJIAZCADcCFCAGQgA3AhwgBkEANgIkIAYgCCAJQRB0QYCAPHFyNgIQIAYgBSgAEDYCKCAGIAUoABQ2AiwgBiAFKAAYNgIwIAUoABwhBSAGQQA6AEwgBkEANgI4IAYgBTYCNCAGIAEgAhAEIAQEQCAGIAMgBBAECyAGKAI4IgEEQCAGQTxqIgIgAWpBAToAACABQQFqQQ9NBEAgASAGakE9aiEEAkBBDyABayIDRQ0AIAMgBGoiAUEBa0EAOgAAIARBADoAACADQQNJDQAgAUECa0EAOgAAIARBADoAASABQQNrQQA6AAAgBEEAOgACIANBB0kNACABQQRrQQA6AAAgBEEAOgADIANBCUkNACAEQQAgBGtBA3EiAWoiBEEANgIAIAQgAyABa0F8cSIBaiIDQQRrQQA2AgAgAUEJSQ0AIARBADYCCCAEQQA2AgQgA0EIa0EANgIAIANBDGtBADYCACABQRlJDQAgBEEANgIYIARBADYCFCAEQQA2AhAgBEEANgIMIANBEGtBADYCACADQRRrQQA2AgAgA0EYa0EANgIAIANBHGtBADYCACABIARBBHFBGHIiAWsiA0EgSQ0AIAEgBGohAQNAIAFCADcDGCABQgA3AxAgAUIANwMIIAFCADcDACABQSBqIQEgA0EgayIDQR9LDQALCwsgBkEBOgBMIAYgAkEQEAILIAY1AjQhECAGNQIwIREgBjUCLCEOIAAgBjUCKCAGKAIkIAYoAiAgBigCHCAGKAIYIgNBGnZqIgJBGnZqIgFBGnZqIgtBgICAYHIgAUH///8fcSINIAJB////H3EiCCAGKAIUIAtBGnZBBWxqIgFB////H3EiCUEFaiIFQRp2IANB////H3EgAUEadmoiA2oiAUEadmoiAkEadmoiBEEadmoiDEEfdSIHIANxIAEgDEEfdkEBayIDQf///x9xIgpxciIBQRp0IAUgCnEgByAJcXJyrXwiDzwAACAAIA9CGIg8AAMgACAPQhCIPAACIAAgD0IIiDwAASAAIA4gByAIcSACIApxciICQRR0IAFBBnZyrXwgD0IgiHwiDjwABCAAIA5CGIg8AAcgACAOQhCIPAAGIAAgDkIIiDwABSAAIBEgByANcSAEIApxciIBQQ50IAJBDHZyrXwgDkIgiHwiDjwACCAAIA5CGIg8AAsgACAOQhCIPAAKIAAgDkIIiDwACSAAIBAgAyAMcSAHIAtxckEIdCABQRJ2cq18IA5CIIh8Ig48AAwgACAOQhiIPAAPIAAgDkIQiDwADiAAIA5CCIg8AA0gBkIANwIwIAZCADcCKCAGQgA3AiAgBkIANwIYIAZCADcCECAGQgA3AgggBkIANwIAIAZBkAFqJAALpwwBB38CQCAARQ0AIABBCGsiAyAAQQRrKAIAIgFBeHEiAGohBQJAIAFBAXENACABQQNxRQ0BIAMgAygCACIBayIDQZgIKAIASQ0BIAAgAWohACADQZwIKAIARwRAIAFB/wFNBEAgAygCCCICIAFBA3YiBEEDdEGwCGpGGiACIAMoAgwiAUYEQEGICEGICCgCAEF+IAR3cTYCAAwDCyACIAE2AgwgASACNgIIDAILIAMoAhghBgJAIAMgAygCDCIBRwRAIAMoAggiAiABNgIMIAEgAjYCCAwBCwJAIANBFGoiAigCACIEDQAgA0EQaiICKAIAIgQNAEEAIQEMAQsDQCACIQcgBCIBQRRqIgIoAgAiBA0AIAFBEGohAiABKAIQIgQNAAsgB0EANgIACyAGRQ0BAkAgAyADKAIcIgJBAnRBuApqIgQoAgBGBEAgBCABNgIAIAENAUGMCEGMCCgCAEF+IAJ3cTYCAAwDCyAGQRBBFCAGKAIQIANGG2ogATYCACABRQ0CCyABIAY2AhggAygCECICBEAgASACNgIQIAIgATYCGAsgAygCFCICRQ0BIAEgAjYCFCACIAE2AhgMAQsgBSgCBCIBQQNxQQNHDQBBkAggADYCACAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAA8LIAMgBU8NACAFKAIEIgFBAXFFDQACQCABQQJxRQRAIAVBoAgoAgBGBEBBoAggAzYCAEGUCEGUCCgCACAAaiIANgIAIAMgAEEBcjYCBCADQZwIKAIARw0DQZAIQQA2AgBBnAhBADYCAA8LIAVBnAgoAgBGBEBBnAggAzYCAEGQCEGQCCgCACAAaiIANgIAIAMgAEEBcjYCBCAAIANqIAA2AgAPCyABQXhxIABqIQACQCABQf8BTQRAIAUoAggiAiABQQN2IgRBA3RBsAhqRhogAiAFKAIMIgFGBEBBiAhBiAgoAgBBfiAEd3E2AgAMAgsgAiABNgIMIAEgAjYCCAwBCyAFKAIYIQYCQCAFIAUoAgwiAUcEQCAFKAIIIgJBmAgoAgBJGiACIAE2AgwgASACNgIIDAELAkAgBUEUaiICKAIAIgQNACAFQRBqIgIoAgAiBA0AQQAhAQwBCwNAIAIhByAEIgFBFGoiAigCACIEDQAgAUEQaiECIAEoAhAiBA0ACyAHQQA2AgALIAZFDQACQCAFIAUoAhwiAkECdEG4CmoiBCgCAEYEQCAEIAE2AgAgAQ0BQYwIQYwIKAIAQX4gAndxNgIADAILIAZBEEEUIAYoAhAgBUYbaiABNgIAIAFFDQELIAEgBjYCGCAFKAIQIgIEQCABIAI2AhAgAiABNgIYCyAFKAIUIgJFDQAgASACNgIUIAIgATYCGAsgAyAAQQFyNgIEIAAgA2ogADYCACADQZwIKAIARw0BQZAIIAA2AgAPCyAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAAsgAEH/AU0EQCAAQQN2IgFBA3RBsAhqIQACf0GICCgCACICQQEgAXQiAXFFBEBBiAggASACcjYCACAADAELIAAoAggLIQIgACADNgIIIAIgAzYCDCADIAA2AgwgAyACNgIIDwtBHyECIANCADcCECAAQf///wdNBEAgAEEIdiIBIAFBgP4/akEQdkEIcSIBdCICIAJBgOAfakEQdkEEcSICdCIEIARBgIAPakEQdkECcSIEdEEPdiABIAJyIARyayIBQQF0IAAgAUEVanZBAXFyQRxqIQILIAMgAjYCHCACQQJ0QbgKaiEBAkACQAJAQYwIKAIAIgRBASACdCIHcUUEQEGMCCAEIAdyNgIAIAEgAzYCACADIAE2AhgMAQsgAEEAQRkgAkEBdmsgAkEfRht0IQIgASgCACEBA0AgASIEKAIEQXhxIABGDQIgAkEddiEBIAJBAXQhAiAEIAFBBHFqIgdBEGooAgAiAQ0ACyAHIAM2AhAgAyAENgIYCyADIAM2AgwgAyADNgIIDAELIAQoAggiACADNgIMIAQgAzYCCCADQQA2AhggAyAENgIMIAMgADYCCAtBqAhBqAgoAgBBAWsiAEF/IAAbNgIACwsLCQEAQYEICwIGUA=="; + if (!W.startsWith(V)) { + var na = W; + W = b.locateFile ? b.locateFile(na, B) : B + na; + } + function pa() { + var a = W; + try { + if (a == W && J) return new Uint8Array(J); + var c = H(a); + if (c) return c; + if (E) return E(a); + throw "both async and sync fetching of the wasm failed"; + } catch (d) { + K(d); + } + } + function qa() { + if (!J && (x || y)) { + if ("function" === typeof fetch && !W.startsWith("file://")) return fetch(W, { credentials: "same-origin" }).then(function(a) { + if (!a.ok) throw "failed to load wasm binary file at '" + W + "'"; + return a.arrayBuffer(); + }).catch(function() { + return pa(); + }); + if (D) return new Promise(function(a, c) { + D(W, function(d) { + a(new Uint8Array(d)); + }, c); + }); + } + return Promise.resolve().then(function() { + return pa(); + }); + } + function X(a) { + for (; 0 < a.length; ) { + var c = a.shift(); + if ("function" == typeof c) c(b); + else { + var d = c.m; + "number" === typeof d ? void 0 === c.l ? R.get(d)() : R.get(d)(c.l) : d(void 0 === c.l ? null : c.l); + } + } + } + var ba = false, ra = "function" === typeof atob ? atob : function(a) { + var c = "", d = 0; + a = a.replace(/[^A-Za-z0-9\+\/=]/g, ""); + do { + var e = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a.charAt(d++)); + var f = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a.charAt(d++)); + var l = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a.charAt(d++)); + var A = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a.charAt(d++)); + e = e << 2 | f >> 4; + f = (f & 15) << 4 | l >> 2; + var t = (l & 3) << 6 | A; + c += String.fromCharCode(e); + 64 !== l && (c += String.fromCharCode(f)); + 64 !== A && (c += String.fromCharCode(t)); + } while (d < a.length); + return c; + }; + function H(a) { + if (a.startsWith(V)) { + a = a.slice(V.length); + if ("boolean" === typeof z && z) { + var c = Buffer.from(a, "base64"); + c = new Uint8Array(c.buffer, c.byteOffset, c.byteLength); + } else try { + var d = ra(a), e = new Uint8Array(d.length); + for (a = 0; a < d.length; ++a) e[a] = d.charCodeAt(a); + c = e; + } catch (f) { + throw Error("Converting base64 string to bytes failed."); + } + return c; + } + } + var sa = { a: function(a) { + var c = P.length; + a >>>= 0; + if (2147483648 < a) return false; + for (var d = 1; 4 >= d; d *= 2) { + var e = c * (1 + 0.2 / d); + e = Math.min(e, a + 100663296); + e = Math.max(a, e); + 0 < e % 65536 && (e += 65536 - e % 65536); + a: { + try { + L.grow(Math.min(2147483648, e) - ha.byteLength + 65535 >>> 16); + ia(); + var f = 1; + break a; + } catch (l) { + } + f = void 0; + } + if (f) return true; + } + return false; + } }; + (function() { + function a(f) { + b.asm = f.exports; + L = b.asm.b; + ia(); + R = b.asm.j; + ka.unshift(b.asm.c); + S--; + b.monitorRunDependencies && b.monitorRunDependencies(S); + 0 == S && (null !== T && (clearInterval(T), T = null), U && (f = U, U = null, f())); + } + function c(f) { + a(f.instance); + } + function d(f) { + return qa().then(function(l) { + return WebAssembly.instantiate(l, e); + }).then(f, function(l) { + I("failed to asynchronously prepare wasm: " + l); + K(l); + }); + } + var e = { a: sa }; + S++; + b.monitorRunDependencies && b.monitorRunDependencies(S); + if (b.instantiateWasm) try { + return b.instantiateWasm( + e, + a + ); + } catch (f) { + return I("Module.instantiateWasm callback failed with error: " + f), false; + } + (function() { + return J || "function" !== typeof WebAssembly.instantiateStreaming || W.startsWith(V) || W.startsWith("file://") || "function" !== typeof fetch ? d(c) : fetch(W, { credentials: "same-origin" }).then(function(f) { + return WebAssembly.instantiateStreaming(f, e).then(c, function(l) { + I("wasm streaming compile failed: " + l); + I("falling back to ArrayBuffer instantiation"); + return d(c); + }); + }); + })().catch(r); + return {}; + })(); + b.___wasm_call_ctors = function() { + return (b.___wasm_call_ctors = b.asm.c).apply(null, arguments); + }; + b._poly1305_auth = function() { + return (b._poly1305_auth = b.asm.d).apply(null, arguments); + }; + var da = b.stackSave = function() { + return (da = b.stackSave = b.asm.e).apply(null, arguments); + }, fa = b.stackRestore = function() { + return (fa = b.stackRestore = b.asm.f).apply(null, arguments); + }, O = b.stackAlloc = function() { + return (O = b.stackAlloc = b.asm.g).apply(null, arguments); + }; + b._malloc = function() { + return (b._malloc = b.asm.h).apply(null, arguments); + }; + b._free = function() { + return (b._free = b.asm.i).apply(null, arguments); + }; + b.cwrap = function(a, c, d, e) { + d = d || []; + var f = d.every(function(l) { + return "number" === l; + }); + return "string" !== c && f && !e ? N(a) : function() { + return ca(a, c, d, arguments); + }; + }; + var Y; + U = function ta() { + Y || Z(); + Y || (U = ta); + }; + function Z() { + function a() { + if (!Y && (Y = true, b.calledRun = true, !M)) { + X(ka); + q(b); + if (b.onRuntimeInitialized) b.onRuntimeInitialized(); + if (b.postRun) for ("function" == typeof b.postRun && (b.postRun = [b.postRun]); b.postRun.length; ) { + var c = b.postRun.shift(); + la.unshift(c); + } + X(la); + } + } + if (!(0 < S)) { + if (b.preRun) for ("function" == typeof b.preRun && (b.preRun = [b.preRun]); b.preRun.length; ) ma(); + X(ja); + 0 < S || (b.setStatus ? (b.setStatus("Running..."), setTimeout(function() { + setTimeout(function() { + b.setStatus(""); + }, 1); + a(); + }, 1)) : a()); + } + } + b.run = Z; + if (b.preInit) for ("function" == typeof b.preInit && (b.preInit = [b.preInit]); 0 < b.preInit.length; ) b.preInit.pop()(); + Z(); + return createPoly13052.ready; + }); + })(); + if (typeof exports2 === "object" && typeof module2 === "object") + module2.exports = createPoly1305; + else if (typeof define === "function" && define["amd"]) + define([], function() { + return createPoly1305; + }); + else if (typeof exports2 === "object") + exports2["createPoly1305"] = createPoly1305; + } +}); + +// node_modules/ssh2/lib/protocol/crypto.js +var require_crypto = __commonJS({ + "node_modules/ssh2/lib/protocol/crypto.js"(exports2, module2) { + "use strict"; + var { + createCipheriv, + createDecipheriv, + createHmac, + randomFillSync, + timingSafeEqual + } = require("crypto"); + var { readUInt32BE, writeUInt32BE } = require_utils3(); + var FastBuffer = Buffer[Symbol.species]; + var MAX_SEQNO = 2 ** 32 - 1; + var EMPTY_BUFFER = Buffer.alloc(0); + var BUF_INT = Buffer.alloc(4); + var DISCARD_CACHE = /* @__PURE__ */ new Map(); + var MAX_PACKET_SIZE = 35e3; + var binding; + var AESGCMCipher; + var ChaChaPolyCipher; + var GenericCipher; + var AESGCMDecipher; + var ChaChaPolyDecipher; + var GenericDecipher; + try { + binding = require_sshcrypto(); + ({ + AESGCMCipher, + ChaChaPolyCipher, + GenericCipher, + AESGCMDecipher, + ChaChaPolyDecipher, + GenericDecipher + } = binding); + } catch { + } + var CIPHER_STREAM = 1 << 0; + var CIPHER_INFO = (() => { + function info2(sslName, blockLen, keyLen, ivLen, authLen, discardLen, flags) { + return { + sslName, + blockLen, + keyLen, + ivLen: ivLen !== 0 || flags & CIPHER_STREAM ? ivLen : blockLen, + authLen, + discardLen, + stream: !!(flags & CIPHER_STREAM) + }; + } + return { + "chacha20-poly1305@openssh.com": info2("chacha20", 8, 64, 0, 16, 0, CIPHER_STREAM), + "aes128-gcm": info2("aes-128-gcm", 16, 16, 12, 16, 0, CIPHER_STREAM), + "aes256-gcm": info2("aes-256-gcm", 16, 32, 12, 16, 0, CIPHER_STREAM), + "aes128-gcm@openssh.com": info2("aes-128-gcm", 16, 16, 12, 16, 0, CIPHER_STREAM), + "aes256-gcm@openssh.com": info2("aes-256-gcm", 16, 32, 12, 16, 0, CIPHER_STREAM), + "aes128-cbc": info2("aes-128-cbc", 16, 16, 0, 0, 0, 0), + "aes192-cbc": info2("aes-192-cbc", 16, 24, 0, 0, 0, 0), + "aes256-cbc": info2("aes-256-cbc", 16, 32, 0, 0, 0, 0), + "rijndael-cbc@lysator.liu.se": info2("aes-256-cbc", 16, 32, 0, 0, 0, 0), + "3des-cbc": info2("des-ede3-cbc", 8, 24, 0, 0, 0, 0), + "blowfish-cbc": info2("bf-cbc", 8, 16, 0, 0, 0, 0), + "idea-cbc": info2("idea-cbc", 8, 16, 0, 0, 0, 0), + "cast128-cbc": info2("cast-cbc", 8, 16, 0, 0, 0, 0), + "aes128-ctr": info2("aes-128-ctr", 16, 16, 16, 0, 0, CIPHER_STREAM), + "aes192-ctr": info2("aes-192-ctr", 16, 24, 16, 0, 0, CIPHER_STREAM), + "aes256-ctr": info2("aes-256-ctr", 16, 32, 16, 0, 0, CIPHER_STREAM), + "3des-ctr": info2("des-ede3", 8, 24, 8, 0, 0, CIPHER_STREAM), + "blowfish-ctr": info2("bf-ecb", 8, 16, 8, 0, 0, CIPHER_STREAM), + "cast128-ctr": info2("cast5-ecb", 8, 16, 8, 0, 0, CIPHER_STREAM), + /* The "arcfour128" algorithm is the RC4 cipher, as described in + [SCHNEIER], using a 128-bit key. The first 1536 bytes of keystream + generated by the cipher MUST be discarded, and the first byte of the + first encrypted packet MUST be encrypted using the 1537th byte of + keystream. + + -- http://tools.ietf.org/html/rfc4345#section-4 */ + "arcfour": info2("rc4", 8, 16, 0, 0, 1536, CIPHER_STREAM), + "arcfour128": info2("rc4", 8, 16, 0, 0, 1536, CIPHER_STREAM), + "arcfour256": info2("rc4", 8, 32, 0, 0, 1536, CIPHER_STREAM), + "arcfour512": info2("rc4", 8, 64, 0, 0, 1536, CIPHER_STREAM) + }; + })(); + var MAC_INFO = (() => { + function info2(sslName, len, actualLen, isETM) { + return { + sslName, + len, + actualLen, + isETM + }; + } + return { + "hmac-md5": info2("md5", 16, 16, false), + "hmac-md5-96": info2("md5", 16, 12, false), + "hmac-ripemd160": info2("ripemd160", 20, 20, false), + "hmac-sha1": info2("sha1", 20, 20, false), + "hmac-sha1-etm@openssh.com": info2("sha1", 20, 20, true), + "hmac-sha1-96": info2("sha1", 20, 12, false), + "hmac-sha2-256": info2("sha256", 32, 32, false), + "hmac-sha2-256-etm@openssh.com": info2("sha256", 32, 32, true), + "hmac-sha2-256-96": info2("sha256", 32, 12, false), + "hmac-sha2-512": info2("sha512", 64, 64, false), + "hmac-sha2-512-etm@openssh.com": info2("sha512", 64, 64, true), + "hmac-sha2-512-96": info2("sha512", 64, 12, false) + }; + })(); + var NullCipher = class { + constructor(seqno, onWrite) { + this.outSeqno = seqno; + this._onWrite = onWrite; + this._dead = false; + } + free() { + this._dead = true; + } + allocPacket(payloadLen) { + let pktLen = 4 + 1 + payloadLen; + let padLen = 8 - (pktLen & 8 - 1); + if (padLen < 4) + padLen += 8; + pktLen += padLen; + const packet = Buffer.allocUnsafe(pktLen); + writeUInt32BE(packet, pktLen - 4, 0); + packet[4] = padLen; + randomFillSync(packet, 5 + payloadLen, padLen); + return packet; + } + encrypt(packet) { + if (this._dead) + return; + this._onWrite(packet); + this.outSeqno = this.outSeqno + 1 >>> 0; + } + }; + var POLY1305_ZEROS = Buffer.alloc(32); + var POLY1305_OUT_COMPUTE = Buffer.alloc(16); + var POLY1305_WASM_MODULE; + var POLY1305_RESULT_MALLOC; + var poly1305_auth; + var ChaChaPolyCipherNative = class { + constructor(config) { + const enc = config.outbound; + this.outSeqno = enc.seqno; + this._onWrite = enc.onWrite; + this._encKeyMain = enc.cipherKey.slice(0, 32); + this._encKeyPktLen = enc.cipherKey.slice(32); + this._dead = false; + } + free() { + this._dead = true; + } + allocPacket(payloadLen) { + let pktLen = 4 + 1 + payloadLen; + let padLen = 8 - (pktLen - 4 & 8 - 1); + if (padLen < 4) + padLen += 8; + pktLen += padLen; + const packet = Buffer.allocUnsafe(pktLen); + writeUInt32BE(packet, pktLen - 4, 0); + packet[4] = padLen; + randomFillSync(packet, 5 + payloadLen, padLen); + return packet; + } + encrypt(packet) { + if (this._dead) + return; + POLY1305_OUT_COMPUTE[0] = 0; + writeUInt32BE(POLY1305_OUT_COMPUTE, this.outSeqno, 12); + const polyKey = createCipheriv("chacha20", this._encKeyMain, POLY1305_OUT_COMPUTE).update(POLY1305_ZEROS); + const pktLenEnc = createCipheriv("chacha20", this._encKeyPktLen, POLY1305_OUT_COMPUTE).update(packet.slice(0, 4)); + this._onWrite(pktLenEnc); + POLY1305_OUT_COMPUTE[0] = 1; + const payloadEnc = createCipheriv("chacha20", this._encKeyMain, POLY1305_OUT_COMPUTE).update(packet.slice(4)); + this._onWrite(payloadEnc); + poly1305_auth( + POLY1305_RESULT_MALLOC, + pktLenEnc, + pktLenEnc.length, + payloadEnc, + payloadEnc.length, + polyKey + ); + const mac = Buffer.allocUnsafe(16); + mac.set( + new Uint8Array( + POLY1305_WASM_MODULE.HEAPU8.buffer, + POLY1305_RESULT_MALLOC, + 16 + ), + 0 + ); + this._onWrite(mac); + this.outSeqno = this.outSeqno + 1 >>> 0; + } + }; + var ChaChaPolyCipherBinding = class { + constructor(config) { + const enc = config.outbound; + this.outSeqno = enc.seqno; + this._onWrite = enc.onWrite; + this._instance = new ChaChaPolyCipher(enc.cipherKey); + this._dead = false; + } + free() { + this._dead = true; + this._instance.free(); + } + allocPacket(payloadLen) { + let pktLen = 4 + 1 + payloadLen; + let padLen = 8 - (pktLen - 4 & 8 - 1); + if (padLen < 4) + padLen += 8; + pktLen += padLen; + const packet = Buffer.allocUnsafe( + pktLen + 16 + /* MAC */ + ); + writeUInt32BE(packet, pktLen - 4, 0); + packet[4] = padLen; + randomFillSync(packet, 5 + payloadLen, padLen); + return packet; + } + encrypt(packet) { + if (this._dead) + return; + this._instance.encrypt(packet, this.outSeqno); + this._onWrite(packet); + this.outSeqno = this.outSeqno + 1 >>> 0; + } + }; + var AESGCMCipherNative = class { + constructor(config) { + const enc = config.outbound; + this.outSeqno = enc.seqno; + this._onWrite = enc.onWrite; + this._encSSLName = enc.cipherInfo.sslName; + this._encKey = enc.cipherKey; + this._encIV = enc.cipherIV; + this._dead = false; + } + free() { + this._dead = true; + } + allocPacket(payloadLen) { + let pktLen = 4 + 1 + payloadLen; + let padLen = 16 - (pktLen - 4 & 16 - 1); + if (padLen < 4) + padLen += 16; + pktLen += padLen; + const packet = Buffer.allocUnsafe(pktLen); + writeUInt32BE(packet, pktLen - 4, 0); + packet[4] = padLen; + randomFillSync(packet, 5 + payloadLen, padLen); + return packet; + } + encrypt(packet) { + if (this._dead) + return; + const cipher = createCipheriv(this._encSSLName, this._encKey, this._encIV); + cipher.setAutoPadding(false); + const lenData = packet.slice(0, 4); + cipher.setAAD(lenData); + this._onWrite(lenData); + const encrypted = cipher.update(packet.slice(4)); + this._onWrite(encrypted); + const final = cipher.final(); + if (final.length) + this._onWrite(final); + const tag = cipher.getAuthTag(); + this._onWrite(tag); + ivIncrement(this._encIV); + this.outSeqno = this.outSeqno + 1 >>> 0; + } + }; + var AESGCMCipherBinding = class { + constructor(config) { + const enc = config.outbound; + this.outSeqno = enc.seqno; + this._onWrite = enc.onWrite; + this._instance = new AESGCMCipher( + enc.cipherInfo.sslName, + enc.cipherKey, + enc.cipherIV + ); + this._dead = false; + } + free() { + this._dead = true; + this._instance.free(); + } + allocPacket(payloadLen) { + let pktLen = 4 + 1 + payloadLen; + let padLen = 16 - (pktLen - 4 & 16 - 1); + if (padLen < 4) + padLen += 16; + pktLen += padLen; + const packet = Buffer.allocUnsafe( + pktLen + 16 + /* authTag */ + ); + writeUInt32BE(packet, pktLen - 4, 0); + packet[4] = padLen; + randomFillSync(packet, 5 + payloadLen, padLen); + return packet; + } + encrypt(packet) { + if (this._dead) + return; + this._instance.encrypt(packet); + this._onWrite(packet); + this.outSeqno = this.outSeqno + 1 >>> 0; + } + }; + var GenericCipherNative = class { + constructor(config) { + const enc = config.outbound; + this.outSeqno = enc.seqno; + this._onWrite = enc.onWrite; + this._encBlockLen = enc.cipherInfo.blockLen; + this._cipherInstance = createCipheriv( + enc.cipherInfo.sslName, + enc.cipherKey, + enc.cipherIV + ); + this._macSSLName = enc.macInfo.sslName; + this._macKey = enc.macKey; + this._macActualLen = enc.macInfo.actualLen; + this._macETM = enc.macInfo.isETM; + this._aadLen = this._macETM ? 4 : 0; + this._dead = false; + const discardLen = enc.cipherInfo.discardLen; + if (discardLen) { + let discard = DISCARD_CACHE.get(discardLen); + if (discard === void 0) { + discard = Buffer.alloc(discardLen); + DISCARD_CACHE.set(discardLen, discard); + } + this._cipherInstance.update(discard); + } + } + free() { + this._dead = true; + } + allocPacket(payloadLen) { + const blockLen = this._encBlockLen; + let pktLen = 4 + 1 + payloadLen; + let padLen = blockLen - (pktLen - this._aadLen & blockLen - 1); + if (padLen < 4) + padLen += blockLen; + pktLen += padLen; + const packet = Buffer.allocUnsafe(pktLen); + writeUInt32BE(packet, pktLen - 4, 0); + packet[4] = padLen; + randomFillSync(packet, 5 + payloadLen, padLen); + return packet; + } + encrypt(packet) { + if (this._dead) + return; + let mac; + if (this._macETM) { + const lenBytes = new Uint8Array(packet.buffer, packet.byteOffset, 4); + const encrypted = this._cipherInstance.update( + new Uint8Array( + packet.buffer, + packet.byteOffset + 4, + packet.length - 4 + ) + ); + this._onWrite(lenBytes); + this._onWrite(encrypted); + mac = createHmac(this._macSSLName, this._macKey); + writeUInt32BE(BUF_INT, this.outSeqno, 0); + mac.update(BUF_INT); + mac.update(lenBytes); + mac.update(encrypted); + } else { + const encrypted = this._cipherInstance.update(packet); + this._onWrite(encrypted); + mac = createHmac(this._macSSLName, this._macKey); + writeUInt32BE(BUF_INT, this.outSeqno, 0); + mac.update(BUF_INT); + mac.update(packet); + } + let digest = mac.digest(); + if (digest.length > this._macActualLen) + digest = digest.slice(0, this._macActualLen); + this._onWrite(digest); + this.outSeqno = this.outSeqno + 1 >>> 0; + } + }; + var GenericCipherBinding = class { + constructor(config) { + const enc = config.outbound; + this.outSeqno = enc.seqno; + this._onWrite = enc.onWrite; + this._encBlockLen = enc.cipherInfo.blockLen; + this._macLen = enc.macInfo.len; + this._macActualLen = enc.macInfo.actualLen; + this._aadLen = enc.macInfo.isETM ? 4 : 0; + this._instance = new GenericCipher( + enc.cipherInfo.sslName, + enc.cipherKey, + enc.cipherIV, + enc.macInfo.sslName, + enc.macKey, + enc.macInfo.isETM + ); + this._dead = false; + } + free() { + this._dead = true; + this._instance.free(); + } + allocPacket(payloadLen) { + const blockLen = this._encBlockLen; + let pktLen = 4 + 1 + payloadLen; + let padLen = blockLen - (pktLen - this._aadLen & blockLen - 1); + if (padLen < 4) + padLen += blockLen; + pktLen += padLen; + const packet = Buffer.allocUnsafe(pktLen + this._macLen); + writeUInt32BE(packet, pktLen - 4, 0); + packet[4] = padLen; + randomFillSync(packet, 5 + payloadLen, padLen); + return packet; + } + encrypt(packet) { + if (this._dead) + return; + this._instance.encrypt(packet, this.outSeqno); + if (this._macActualLen < this._macLen) { + packet = new FastBuffer( + packet.buffer, + packet.byteOffset, + packet.length - (this._macLen - this._macActualLen) + ); + } + this._onWrite(packet); + this.outSeqno = this.outSeqno + 1 >>> 0; + } + }; + var NullDecipher = class { + constructor(seqno, onPayload) { + this.inSeqno = seqno; + this._onPayload = onPayload; + this._len = 0; + this._lenBytes = 0; + this._packet = null; + this._packetPos = 0; + } + free() { + } + decrypt(data, p, dataLen) { + while (p < dataLen) { + if (this._lenBytes < 4) { + let nb = Math.min(4 - this._lenBytes, dataLen - p); + this._lenBytes += nb; + while (nb--) + this._len = (this._len << 8) + data[p++]; + if (this._lenBytes < 4) + return; + if (this._len > MAX_PACKET_SIZE || this._len < 8 || (4 + this._len & 7) !== 0) { + throw new Error("Bad packet length"); + } + if (p >= dataLen) + return; + } + if (this._packetPos < this._len) { + const nb = Math.min(this._len - this._packetPos, dataLen - p); + let chunk; + if (p !== 0 || nb !== dataLen) + chunk = new Uint8Array(data.buffer, data.byteOffset + p, nb); + else + chunk = data; + if (nb === this._len) { + this._packet = chunk; + } else { + if (!this._packet) + this._packet = Buffer.allocUnsafe(this._len); + this._packet.set(chunk, this._packetPos); + } + p += nb; + this._packetPos += nb; + if (this._packetPos < this._len) + return; + } + const payload = !this._packet ? EMPTY_BUFFER : new FastBuffer( + this._packet.buffer, + this._packet.byteOffset + 1, + this._packet.length - this._packet[0] - 1 + ); + this.inSeqno = this.inSeqno + 1 >>> 0; + this._len = 0; + this._lenBytes = 0; + this._packet = null; + this._packetPos = 0; + { + const ret = this._onPayload(payload); + if (ret !== void 0) + return ret === false ? p : ret; + } + } + } + }; + var ChaChaPolyDecipherNative = class { + constructor(config) { + const dec = config.inbound; + this.inSeqno = dec.seqno; + this._onPayload = dec.onPayload; + this._decKeyMain = dec.decipherKey.slice(0, 32); + this._decKeyPktLen = dec.decipherKey.slice(32); + this._len = 0; + this._lenBuf = Buffer.alloc(4); + this._lenPos = 0; + this._packet = null; + this._pktLen = 0; + this._mac = Buffer.allocUnsafe(16); + this._calcMac = Buffer.allocUnsafe(16); + this._macPos = 0; + } + free() { + } + decrypt(data, p, dataLen) { + while (p < dataLen) { + if (this._lenPos < 4) { + let nb = Math.min(4 - this._lenPos, dataLen - p); + while (nb--) + this._lenBuf[this._lenPos++] = data[p++]; + if (this._lenPos < 4) + return; + POLY1305_OUT_COMPUTE[0] = 0; + writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12); + const decLenBytes = createDecipheriv("chacha20", this._decKeyPktLen, POLY1305_OUT_COMPUTE).update(this._lenBuf); + this._len = readUInt32BE(decLenBytes, 0); + if (this._len > MAX_PACKET_SIZE || this._len < 8 || (this._len & 7) !== 0) { + throw new Error("Bad packet length"); + } + } + if (this._pktLen < this._len) { + if (p >= dataLen) + return; + const nb = Math.min(this._len - this._pktLen, dataLen - p); + let encrypted; + if (p !== 0 || nb !== dataLen) + encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); + else + encrypted = data; + if (nb === this._len) { + this._packet = encrypted; + } else { + if (!this._packet) + this._packet = Buffer.allocUnsafe(this._len); + this._packet.set(encrypted, this._pktLen); + } + p += nb; + this._pktLen += nb; + if (this._pktLen < this._len || p >= dataLen) + return; + } + { + const nb = Math.min(16 - this._macPos, dataLen - p); + if (p !== 0 || nb !== dataLen) { + this._mac.set( + new Uint8Array(data.buffer, data.byteOffset + p, nb), + this._macPos + ); + } else { + this._mac.set(data, this._macPos); + } + p += nb; + this._macPos += nb; + if (this._macPos < 16) + return; + } + POLY1305_OUT_COMPUTE[0] = 0; + writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12); + const polyKey = createCipheriv("chacha20", this._decKeyMain, POLY1305_OUT_COMPUTE).update(POLY1305_ZEROS); + poly1305_auth( + POLY1305_RESULT_MALLOC, + this._lenBuf, + 4, + this._packet, + this._packet.length, + polyKey + ); + this._calcMac.set( + new Uint8Array( + POLY1305_WASM_MODULE.HEAPU8.buffer, + POLY1305_RESULT_MALLOC, + 16 + ), + 0 + ); + if (!timingSafeEqual(this._calcMac, this._mac)) + throw new Error("Invalid MAC"); + POLY1305_OUT_COMPUTE[0] = 1; + const packet = createDecipheriv("chacha20", this._decKeyMain, POLY1305_OUT_COMPUTE).update(this._packet); + const payload = new FastBuffer( + packet.buffer, + packet.byteOffset + 1, + packet.length - packet[0] - 1 + ); + this.inSeqno = this.inSeqno + 1 >>> 0; + this._len = 0; + this._lenPos = 0; + this._packet = null; + this._pktLen = 0; + this._macPos = 0; + { + const ret = this._onPayload(payload); + if (ret !== void 0) + return ret === false ? p : ret; + } + } + } + }; + var ChaChaPolyDecipherBinding = class { + constructor(config) { + const dec = config.inbound; + this.inSeqno = dec.seqno; + this._onPayload = dec.onPayload; + this._instance = new ChaChaPolyDecipher(dec.decipherKey); + this._len = 0; + this._lenBuf = Buffer.alloc(4); + this._lenPos = 0; + this._packet = null; + this._pktLen = 0; + this._mac = Buffer.allocUnsafe(16); + this._macPos = 0; + } + free() { + this._instance.free(); + } + decrypt(data, p, dataLen) { + while (p < dataLen) { + if (this._lenPos < 4) { + let nb = Math.min(4 - this._lenPos, dataLen - p); + while (nb--) + this._lenBuf[this._lenPos++] = data[p++]; + if (this._lenPos < 4) + return; + this._len = this._instance.decryptLen(this._lenBuf, this.inSeqno); + if (this._len > MAX_PACKET_SIZE || this._len < 8 || (this._len & 7) !== 0) { + throw new Error("Bad packet length"); + } + if (p >= dataLen) + return; + } + if (this._pktLen < this._len) { + const nb = Math.min(this._len - this._pktLen, dataLen - p); + let encrypted; + if (p !== 0 || nb !== dataLen) + encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); + else + encrypted = data; + if (nb === this._len) { + this._packet = encrypted; + } else { + if (!this._packet) + this._packet = Buffer.allocUnsafe(this._len); + this._packet.set(encrypted, this._pktLen); + } + p += nb; + this._pktLen += nb; + if (this._pktLen < this._len || p >= dataLen) + return; + } + { + const nb = Math.min(16 - this._macPos, dataLen - p); + if (p !== 0 || nb !== dataLen) { + this._mac.set( + new Uint8Array(data.buffer, data.byteOffset + p, nb), + this._macPos + ); + } else { + this._mac.set(data, this._macPos); + } + p += nb; + this._macPos += nb; + if (this._macPos < 16) + return; + } + this._instance.decrypt(this._packet, this._mac, this.inSeqno); + const payload = new FastBuffer( + this._packet.buffer, + this._packet.byteOffset + 1, + this._packet.length - this._packet[0] - 1 + ); + this.inSeqno = this.inSeqno + 1 >>> 0; + this._len = 0; + this._lenPos = 0; + this._packet = null; + this._pktLen = 0; + this._macPos = 0; + { + const ret = this._onPayload(payload); + if (ret !== void 0) + return ret === false ? p : ret; + } + } + } + }; + var AESGCMDecipherNative = class { + constructor(config) { + const dec = config.inbound; + this.inSeqno = dec.seqno; + this._onPayload = dec.onPayload; + this._decipherInstance = null; + this._decipherSSLName = dec.decipherInfo.sslName; + this._decipherKey = dec.decipherKey; + this._decipherIV = dec.decipherIV; + this._len = 0; + this._lenBytes = 0; + this._packet = null; + this._packetPos = 0; + this._pktLen = 0; + this._tag = Buffer.allocUnsafe(16); + this._tagPos = 0; + } + free() { + } + decrypt(data, p, dataLen) { + while (p < dataLen) { + if (this._lenBytes < 4) { + let nb = Math.min(4 - this._lenBytes, dataLen - p); + this._lenBytes += nb; + while (nb--) + this._len = (this._len << 8) + data[p++]; + if (this._lenBytes < 4) + return; + if (this._len + 20 > MAX_PACKET_SIZE || this._len < 16 || (this._len & 15) !== 0) { + throw new Error("Bad packet length"); + } + this._decipherInstance = createDecipheriv( + this._decipherSSLName, + this._decipherKey, + this._decipherIV + ); + this._decipherInstance.setAutoPadding(false); + this._decipherInstance.setAAD(intToBytes(this._len)); + } + if (this._pktLen < this._len) { + if (p >= dataLen) + return; + const nb = Math.min(this._len - this._pktLen, dataLen - p); + let decrypted; + if (p !== 0 || nb !== dataLen) { + decrypted = this._decipherInstance.update( + new Uint8Array(data.buffer, data.byteOffset + p, nb) + ); + } else { + decrypted = this._decipherInstance.update(data); + } + if (decrypted.length) { + if (nb === this._len) { + this._packet = decrypted; + } else { + if (!this._packet) + this._packet = Buffer.allocUnsafe(this._len); + this._packet.set(decrypted, this._packetPos); + } + this._packetPos += decrypted.length; + } + p += nb; + this._pktLen += nb; + if (this._pktLen < this._len || p >= dataLen) + return; + } + { + const nb = Math.min(16 - this._tagPos, dataLen - p); + if (p !== 0 || nb !== dataLen) { + this._tag.set( + new Uint8Array(data.buffer, data.byteOffset + p, nb), + this._tagPos + ); + } else { + this._tag.set(data, this._tagPos); + } + p += nb; + this._tagPos += nb; + if (this._tagPos < 16) + return; + } + { + this._decipherInstance.setAuthTag(this._tag); + const decrypted = this._decipherInstance.final(); + if (decrypted.length) { + if (this._packet) + this._packet.set(decrypted, this._packetPos); + else + this._packet = decrypted; + } + } + const payload = !this._packet ? EMPTY_BUFFER : new FastBuffer( + this._packet.buffer, + this._packet.byteOffset + 1, + this._packet.length - this._packet[0] - 1 + ); + this.inSeqno = this.inSeqno + 1 >>> 0; + ivIncrement(this._decipherIV); + this._len = 0; + this._lenBytes = 0; + this._packet = null; + this._packetPos = 0; + this._pktLen = 0; + this._tagPos = 0; + { + const ret = this._onPayload(payload); + if (ret !== void 0) + return ret === false ? p : ret; + } + } + } + }; + var AESGCMDecipherBinding = class { + constructor(config) { + const dec = config.inbound; + this.inSeqno = dec.seqno; + this._onPayload = dec.onPayload; + this._instance = new AESGCMDecipher( + dec.decipherInfo.sslName, + dec.decipherKey, + dec.decipherIV + ); + this._len = 0; + this._lenBytes = 0; + this._packet = null; + this._pktLen = 0; + this._tag = Buffer.allocUnsafe(16); + this._tagPos = 0; + } + free() { + } + decrypt(data, p, dataLen) { + while (p < dataLen) { + if (this._lenBytes < 4) { + let nb = Math.min(4 - this._lenBytes, dataLen - p); + this._lenBytes += nb; + while (nb--) + this._len = (this._len << 8) + data[p++]; + if (this._lenBytes < 4) + return; + if (this._len + 20 > MAX_PACKET_SIZE || this._len < 16 || (this._len & 15) !== 0) { + throw new Error(`Bad packet length: ${this._len}`); + } + } + if (this._pktLen < this._len) { + if (p >= dataLen) + return; + const nb = Math.min(this._len - this._pktLen, dataLen - p); + let encrypted; + if (p !== 0 || nb !== dataLen) + encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); + else + encrypted = data; + if (nb === this._len) { + this._packet = encrypted; + } else { + if (!this._packet) + this._packet = Buffer.allocUnsafe(this._len); + this._packet.set(encrypted, this._pktLen); + } + p += nb; + this._pktLen += nb; + if (this._pktLen < this._len || p >= dataLen) + return; + } + { + const nb = Math.min(16 - this._tagPos, dataLen - p); + if (p !== 0 || nb !== dataLen) { + this._tag.set( + new Uint8Array(data.buffer, data.byteOffset + p, nb), + this._tagPos + ); + } else { + this._tag.set(data, this._tagPos); + } + p += nb; + this._tagPos += nb; + if (this._tagPos < 16) + return; + } + this._instance.decrypt(this._packet, this._len, this._tag); + const payload = new FastBuffer( + this._packet.buffer, + this._packet.byteOffset + 1, + this._packet.length - this._packet[0] - 1 + ); + this.inSeqno = this.inSeqno + 1 >>> 0; + this._len = 0; + this._lenBytes = 0; + this._packet = null; + this._pktLen = 0; + this._tagPos = 0; + { + const ret = this._onPayload(payload); + if (ret !== void 0) + return ret === false ? p : ret; + } + } + } + }; + var GenericDecipherNative = class { + constructor(config) { + const dec = config.inbound; + this.inSeqno = dec.seqno; + this._onPayload = dec.onPayload; + this._decipherInstance = createDecipheriv( + dec.decipherInfo.sslName, + dec.decipherKey, + dec.decipherIV + ); + this._decipherInstance.setAutoPadding(false); + this._block = Buffer.allocUnsafe( + dec.macInfo.isETM ? 4 : dec.decipherInfo.blockLen + ); + this._blockSize = dec.decipherInfo.blockLen; + this._blockPos = 0; + this._len = 0; + this._packet = null; + this._packetPos = 0; + this._pktLen = 0; + this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen); + this._macPos = 0; + this._macSSLName = dec.macInfo.sslName; + this._macKey = dec.macKey; + this._macActualLen = dec.macInfo.actualLen; + this._macETM = dec.macInfo.isETM; + this._macInstance = null; + const discardLen = dec.decipherInfo.discardLen; + if (discardLen) { + let discard = DISCARD_CACHE.get(discardLen); + if (discard === void 0) { + discard = Buffer.alloc(discardLen); + DISCARD_CACHE.set(discardLen, discard); + } + this._decipherInstance.update(discard); + } + } + free() { + } + decrypt(data, p, dataLen) { + while (p < dataLen) { + if (this._blockPos < this._block.length) { + const nb = Math.min(this._block.length - this._blockPos, dataLen - p); + if (p !== 0 || nb !== dataLen || nb < data.length) { + this._block.set( + new Uint8Array(data.buffer, data.byteOffset + p, nb), + this._blockPos + ); + } else { + this._block.set(data, this._blockPos); + } + p += nb; + this._blockPos += nb; + if (this._blockPos < this._block.length) + return; + let decrypted; + let need; + if (this._macETM) { + this._len = need = readUInt32BE(this._block, 0); + } else { + decrypted = this._decipherInstance.update(this._block); + this._len = readUInt32BE(decrypted, 0); + need = 4 + this._len - this._blockSize; + } + if (this._len > MAX_PACKET_SIZE || this._len < 5 || (need & this._blockSize - 1) !== 0) { + throw new Error("Bad packet length"); + } + this._macInstance = createHmac(this._macSSLName, this._macKey); + writeUInt32BE(BUF_INT, this.inSeqno, 0); + this._macInstance.update(BUF_INT); + if (this._macETM) { + this._macInstance.update(this._block); + } else { + this._macInstance.update(new Uint8Array( + decrypted.buffer, + decrypted.byteOffset, + 4 + )); + this._pktLen = decrypted.length - 4; + this._packetPos = this._pktLen; + this._packet = Buffer.allocUnsafe(this._len); + this._packet.set( + new Uint8Array( + decrypted.buffer, + decrypted.byteOffset + 4, + this._packetPos + ), + 0 + ); + } + if (p >= dataLen) + return; + } + if (this._pktLen < this._len) { + const nb = Math.min(this._len - this._pktLen, dataLen - p); + let encrypted; + if (p !== 0 || nb !== dataLen) + encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); + else + encrypted = data; + if (this._macETM) + this._macInstance.update(encrypted); + const decrypted = this._decipherInstance.update(encrypted); + if (decrypted.length) { + if (nb === this._len) { + this._packet = decrypted; + } else { + if (!this._packet) + this._packet = Buffer.allocUnsafe(this._len); + this._packet.set(decrypted, this._packetPos); + } + this._packetPos += decrypted.length; + } + p += nb; + this._pktLen += nb; + if (this._pktLen < this._len || p >= dataLen) + return; + } + { + const nb = Math.min(this._macActualLen - this._macPos, dataLen - p); + if (p !== 0 || nb !== dataLen) { + this._mac.set( + new Uint8Array(data.buffer, data.byteOffset + p, nb), + this._macPos + ); + } else { + this._mac.set(data, this._macPos); + } + p += nb; + this._macPos += nb; + if (this._macPos < this._macActualLen) + return; + } + if (!this._macETM) + this._macInstance.update(this._packet); + let calculated = this._macInstance.digest(); + if (this._macActualLen < calculated.length) { + calculated = new Uint8Array( + calculated.buffer, + calculated.byteOffset, + this._macActualLen + ); + } + if (!timingSafeEquals(calculated, this._mac)) + throw new Error("Invalid MAC"); + const payload = new FastBuffer( + this._packet.buffer, + this._packet.byteOffset + 1, + this._packet.length - this._packet[0] - 1 + ); + this.inSeqno = this.inSeqno + 1 >>> 0; + this._blockPos = 0; + this._len = 0; + this._packet = null; + this._packetPos = 0; + this._pktLen = 0; + this._macPos = 0; + this._macInstance = null; + { + const ret = this._onPayload(payload); + if (ret !== void 0) + return ret === false ? p : ret; + } + } + } + }; + var GenericDecipherBinding = class { + constructor(config) { + const dec = config.inbound; + this.inSeqno = dec.seqno; + this._onPayload = dec.onPayload; + this._instance = new GenericDecipher( + dec.decipherInfo.sslName, + dec.decipherKey, + dec.decipherIV, + dec.macInfo.sslName, + dec.macKey, + dec.macInfo.isETM, + dec.macInfo.actualLen + ); + this._block = Buffer.allocUnsafe( + dec.macInfo.isETM || dec.decipherInfo.stream ? 4 : dec.decipherInfo.blockLen + ); + this._blockPos = 0; + this._len = 0; + this._packet = null; + this._pktLen = 0; + this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen); + this._macPos = 0; + this._macActualLen = dec.macInfo.actualLen; + this._macETM = dec.macInfo.isETM; + } + free() { + this._instance.free(); + } + decrypt(data, p, dataLen) { + while (p < dataLen) { + if (this._blockPos < this._block.length) { + const nb = Math.min(this._block.length - this._blockPos, dataLen - p); + if (p !== 0 || nb !== dataLen || nb < data.length) { + this._block.set( + new Uint8Array(data.buffer, data.byteOffset + p, nb), + this._blockPos + ); + } else { + this._block.set(data, this._blockPos); + } + p += nb; + this._blockPos += nb; + if (this._blockPos < this._block.length) + return; + let need; + if (this._macETM) { + this._len = need = readUInt32BE(this._block, 0); + } else { + this._instance.decryptBlock(this._block); + this._len = readUInt32BE(this._block, 0); + need = 4 + this._len - this._block.length; + } + if (this._len > MAX_PACKET_SIZE || this._len < 5 || (need & this._block.length - 1) !== 0) { + throw new Error("Bad packet length"); + } + if (!this._macETM) { + this._pktLen = this._block.length - 4; + if (this._pktLen) { + this._packet = Buffer.allocUnsafe(this._len); + this._packet.set( + new Uint8Array( + this._block.buffer, + this._block.byteOffset + 4, + this._pktLen + ), + 0 + ); + } + } + if (p >= dataLen) + return; + } + if (this._pktLen < this._len) { + const nb = Math.min(this._len - this._pktLen, dataLen - p); + let encrypted; + if (p !== 0 || nb !== dataLen) + encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); + else + encrypted = data; + if (nb === this._len) { + this._packet = encrypted; + } else { + if (!this._packet) + this._packet = Buffer.allocUnsafe(this._len); + this._packet.set(encrypted, this._pktLen); + } + p += nb; + this._pktLen += nb; + if (this._pktLen < this._len || p >= dataLen) + return; + } + { + const nb = Math.min(this._macActualLen - this._macPos, dataLen - p); + if (p !== 0 || nb !== dataLen) { + this._mac.set( + new Uint8Array(data.buffer, data.byteOffset + p, nb), + this._macPos + ); + } else { + this._mac.set(data, this._macPos); + } + p += nb; + this._macPos += nb; + if (this._macPos < this._macActualLen) + return; + } + this._instance.decrypt( + this._packet, + this.inSeqno, + this._block, + this._mac + ); + const payload = new FastBuffer( + this._packet.buffer, + this._packet.byteOffset + 1, + this._packet.length - this._packet[0] - 1 + ); + this.inSeqno = this.inSeqno + 1 >>> 0; + this._blockPos = 0; + this._len = 0; + this._packet = null; + this._pktLen = 0; + this._macPos = 0; + this._macInstance = null; + { + const ret = this._onPayload(payload); + if (ret !== void 0) + return ret === false ? p : ret; + } + } + } + }; + function ivIncrement(iv) { + ++iv[11] >>> 8 && ++iv[10] >>> 8 && ++iv[9] >>> 8 && ++iv[8] >>> 8 && ++iv[7] >>> 8 && ++iv[6] >>> 8 && ++iv[5] >>> 8 && ++iv[4] >>> 8; + } + var intToBytes = (() => { + const ret = Buffer.alloc(4); + return (n) => { + ret[0] = n >>> 24; + ret[1] = n >>> 16; + ret[2] = n >>> 8; + ret[3] = n; + return ret; + }; + })(); + function timingSafeEquals(a, b) { + if (a.length !== b.length) { + timingSafeEqual(a, a); + return false; + } + return timingSafeEqual(a, b); + } + function createCipher(config) { + if (typeof config !== "object" || config === null) + throw new Error("Invalid config"); + if (typeof config.outbound !== "object" || config.outbound === null) + throw new Error("Invalid outbound"); + const outbound = config.outbound; + if (typeof outbound.onWrite !== "function") + throw new Error("Invalid outbound.onWrite"); + if (typeof outbound.cipherInfo !== "object" || outbound.cipherInfo === null) + throw new Error("Invalid outbound.cipherInfo"); + if (!Buffer.isBuffer(outbound.cipherKey) || outbound.cipherKey.length !== outbound.cipherInfo.keyLen) { + throw new Error("Invalid outbound.cipherKey"); + } + if (outbound.cipherInfo.ivLen && (!Buffer.isBuffer(outbound.cipherIV) || outbound.cipherIV.length !== outbound.cipherInfo.ivLen)) { + throw new Error("Invalid outbound.cipherIV"); + } + if (typeof outbound.seqno !== "number" || outbound.seqno < 0 || outbound.seqno > MAX_SEQNO) { + throw new Error("Invalid outbound.seqno"); + } + const forceNative = !!outbound.forceNative; + switch (outbound.cipherInfo.sslName) { + case "aes-128-gcm": + case "aes-256-gcm": + return AESGCMCipher && !forceNative ? new AESGCMCipherBinding(config) : new AESGCMCipherNative(config); + case "chacha20": + return ChaChaPolyCipher && !forceNative ? new ChaChaPolyCipherBinding(config) : new ChaChaPolyCipherNative(config); + default: { + if (typeof outbound.macInfo !== "object" || outbound.macInfo === null) + throw new Error("Invalid outbound.macInfo"); + if (!Buffer.isBuffer(outbound.macKey) || outbound.macKey.length !== outbound.macInfo.len) { + throw new Error("Invalid outbound.macKey"); + } + return GenericCipher && !forceNative ? new GenericCipherBinding(config) : new GenericCipherNative(config); + } + } + } + function createDecipher(config) { + if (typeof config !== "object" || config === null) + throw new Error("Invalid config"); + if (typeof config.inbound !== "object" || config.inbound === null) + throw new Error("Invalid inbound"); + const inbound = config.inbound; + if (typeof inbound.onPayload !== "function") + throw new Error("Invalid inbound.onPayload"); + if (typeof inbound.decipherInfo !== "object" || inbound.decipherInfo === null) { + throw new Error("Invalid inbound.decipherInfo"); + } + if (!Buffer.isBuffer(inbound.decipherKey) || inbound.decipherKey.length !== inbound.decipherInfo.keyLen) { + throw new Error("Invalid inbound.decipherKey"); + } + if (inbound.decipherInfo.ivLen && (!Buffer.isBuffer(inbound.decipherIV) || inbound.decipherIV.length !== inbound.decipherInfo.ivLen)) { + throw new Error("Invalid inbound.decipherIV"); + } + if (typeof inbound.seqno !== "number" || inbound.seqno < 0 || inbound.seqno > MAX_SEQNO) { + throw new Error("Invalid inbound.seqno"); + } + const forceNative = !!inbound.forceNative; + switch (inbound.decipherInfo.sslName) { + case "aes-128-gcm": + case "aes-256-gcm": + return AESGCMDecipher && !forceNative ? new AESGCMDecipherBinding(config) : new AESGCMDecipherNative(config); + case "chacha20": + return ChaChaPolyDecipher && !forceNative ? new ChaChaPolyDecipherBinding(config) : new ChaChaPolyDecipherNative(config); + default: { + if (typeof inbound.macInfo !== "object" || inbound.macInfo === null) + throw new Error("Invalid inbound.macInfo"); + if (!Buffer.isBuffer(inbound.macKey) || inbound.macKey.length !== inbound.macInfo.len) { + throw new Error("Invalid inbound.macKey"); + } + return GenericDecipher && !forceNative ? new GenericDecipherBinding(config) : new GenericDecipherNative(config); + } + } + } + module2.exports = { + CIPHER_INFO, + MAC_INFO, + bindingAvailable: !!binding, + init: (() => { + return new Promise(async (resolve, reject) => { + try { + POLY1305_WASM_MODULE = await require_poly1305()(); + POLY1305_RESULT_MALLOC = POLY1305_WASM_MODULE._malloc(16); + poly1305_auth = POLY1305_WASM_MODULE.cwrap( + "poly1305_auth", + null, + ["number", "array", "number", "array", "number", "array"] + ); + } catch (ex) { + return reject(ex); + } + resolve(); + }); + })(), + NullCipher, + createCipher, + NullDecipher, + createDecipher + }; + } +}); + +// node_modules/ssh2/lib/protocol/keyParser.js +var require_keyParser = __commonJS({ + "node_modules/ssh2/lib/protocol/keyParser.js"(exports2, module2) { + "use strict"; + var { + createDecipheriv, + createECDH, + createHash, + createHmac, + createSign, + createVerify, + getCiphers, + sign: sign_, + verify: verify_ + } = require("crypto"); + var supportedOpenSSLCiphers = getCiphers(); + var { Ber } = require_lib2(); + var bcrypt_pbkdf = require_bcrypt_pbkdf().pbkdf; + var { CIPHER_INFO } = require_crypto(); + var { eddsaSupported, SUPPORTED_CIPHER } = require_constants6(); + var { + bufferSlice, + makeBufferParser, + readString, + readUInt32BE, + writeUInt32BE + } = require_utils3(); + var SYM_HASH_ALGO = /* @__PURE__ */ Symbol("Hash Algorithm"); + var SYM_PRIV_PEM = /* @__PURE__ */ Symbol("Private key PEM"); + var SYM_PUB_PEM = /* @__PURE__ */ Symbol("Public key PEM"); + var SYM_PUB_SSH = /* @__PURE__ */ Symbol("Public key SSH"); + var SYM_DECRYPTED = /* @__PURE__ */ Symbol("Decrypted Key"); + var CIPHER_INFO_OPENSSL = /* @__PURE__ */ Object.create(null); + { + const keys = Object.keys(CIPHER_INFO); + for (let i = 0; i < keys.length; ++i) { + const cipherName = CIPHER_INFO[keys[i]].sslName; + if (!cipherName || CIPHER_INFO_OPENSSL[cipherName]) + continue; + CIPHER_INFO_OPENSSL[cipherName] = CIPHER_INFO[keys[i]]; + } + } + var binaryKeyParser = makeBufferParser(); + function makePEM(type, data) { + data = data.base64Slice(0, data.length); + let formatted = data.replace(/.{64}/g, "$&\n"); + if (data.length & 63) + formatted += "\n"; + return `-----BEGIN ${type} KEY----- +${formatted}-----END ${type} KEY-----`; + } + function combineBuffers(buf1, buf2) { + const result = Buffer.allocUnsafe(buf1.length + buf2.length); + result.set(buf1, 0); + result.set(buf2, buf1.length); + return result; + } + function skipFields(buf, nfields) { + const bufLen = buf.length; + let pos = buf._pos || 0; + for (let i = 0; i < nfields; ++i) { + const left = bufLen - pos; + if (pos >= bufLen || left < 4) + return false; + const len = readUInt32BE(buf, pos); + if (left < 4 + len) + return false; + pos += 4 + len; + } + buf._pos = pos; + return true; + } + function genOpenSSLRSAPub(n, e) { + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + asnWriter.startSequence(); + asnWriter.writeOID("1.2.840.113549.1.1.1"); + asnWriter.writeNull(); + asnWriter.endSequence(); + asnWriter.startSequence(Ber.BitString); + asnWriter.writeByte(0); + asnWriter.startSequence(); + asnWriter.writeBuffer(n, Ber.Integer); + asnWriter.writeBuffer(e, Ber.Integer); + asnWriter.endSequence(); + asnWriter.endSequence(); + asnWriter.endSequence(); + return makePEM("PUBLIC", asnWriter.buffer); + } + function genOpenSSHRSAPub(n, e) { + const publicKey = Buffer.allocUnsafe(4 + 7 + 4 + e.length + 4 + n.length); + writeUInt32BE(publicKey, 7, 0); + publicKey.utf8Write("ssh-rsa", 4, 7); + let i = 4 + 7; + writeUInt32BE(publicKey, e.length, i); + publicKey.set(e, i += 4); + writeUInt32BE(publicKey, n.length, i += e.length); + publicKey.set(n, i + 4); + return publicKey; + } + var genOpenSSLRSAPriv = /* @__PURE__ */ (() => { + function genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp) { + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + asnWriter.writeInt(0, Ber.Integer); + asnWriter.writeBuffer(n, Ber.Integer); + asnWriter.writeBuffer(e, Ber.Integer); + asnWriter.writeBuffer(d, Ber.Integer); + asnWriter.writeBuffer(p, Ber.Integer); + asnWriter.writeBuffer(q, Ber.Integer); + asnWriter.writeBuffer(dmp1, Ber.Integer); + asnWriter.writeBuffer(dmq1, Ber.Integer); + asnWriter.writeBuffer(iqmp, Ber.Integer); + asnWriter.endSequence(); + return asnWriter.buffer; + } + function bigIntFromBuffer(buf) { + return BigInt(`0x${buf.hexSlice(0, buf.length)}`); + } + function bigIntToBuffer(bn) { + let hex = bn.toString(16); + if ((hex.length & 1) !== 0) { + hex = `0${hex}`; + } else { + const sigbit = hex.charCodeAt(0); + if (sigbit === 56 || sigbit === 57 || sigbit >= 97 && sigbit <= 102) { + hex = `00${hex}`; + } + } + return Buffer.from(hex, "hex"); + } + return function genOpenSSLRSAPriv2(n, e, d, iqmp, p, q) { + const bn_d = bigIntFromBuffer(d); + const dmp1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(p) - 1n)); + const dmq1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(q) - 1n)); + return makePEM( + "RSA PRIVATE", + genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp) + ); + }; + })(); + function genOpenSSLDSAPub(p, q, g, y) { + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + asnWriter.startSequence(); + asnWriter.writeOID("1.2.840.10040.4.1"); + asnWriter.startSequence(); + asnWriter.writeBuffer(p, Ber.Integer); + asnWriter.writeBuffer(q, Ber.Integer); + asnWriter.writeBuffer(g, Ber.Integer); + asnWriter.endSequence(); + asnWriter.endSequence(); + asnWriter.startSequence(Ber.BitString); + asnWriter.writeByte(0); + asnWriter.writeBuffer(y, Ber.Integer); + asnWriter.endSequence(); + asnWriter.endSequence(); + return makePEM("PUBLIC", asnWriter.buffer); + } + function genOpenSSHDSAPub(p, q, g, y) { + const publicKey = Buffer.allocUnsafe( + 4 + 7 + 4 + p.length + 4 + q.length + 4 + g.length + 4 + y.length + ); + writeUInt32BE(publicKey, 7, 0); + publicKey.utf8Write("ssh-dss", 4, 7); + let i = 4 + 7; + writeUInt32BE(publicKey, p.length, i); + publicKey.set(p, i += 4); + writeUInt32BE(publicKey, q.length, i += p.length); + publicKey.set(q, i += 4); + writeUInt32BE(publicKey, g.length, i += q.length); + publicKey.set(g, i += 4); + writeUInt32BE(publicKey, y.length, i += g.length); + publicKey.set(y, i + 4); + return publicKey; + } + function genOpenSSLDSAPriv(p, q, g, y, x) { + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + asnWriter.writeInt(0, Ber.Integer); + asnWriter.writeBuffer(p, Ber.Integer); + asnWriter.writeBuffer(q, Ber.Integer); + asnWriter.writeBuffer(g, Ber.Integer); + asnWriter.writeBuffer(y, Ber.Integer); + asnWriter.writeBuffer(x, Ber.Integer); + asnWriter.endSequence(); + return makePEM("DSA PRIVATE", asnWriter.buffer); + } + function genOpenSSLEdPub(pub) { + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + asnWriter.startSequence(); + asnWriter.writeOID("1.3.101.112"); + asnWriter.endSequence(); + asnWriter.startSequence(Ber.BitString); + asnWriter.writeByte(0); + asnWriter._ensure(pub.length); + asnWriter._buf.set(pub, asnWriter._offset); + asnWriter._offset += pub.length; + asnWriter.endSequence(); + asnWriter.endSequence(); + return makePEM("PUBLIC", asnWriter.buffer); + } + function genOpenSSHEdPub(pub) { + const publicKey = Buffer.allocUnsafe(4 + 11 + 4 + pub.length); + writeUInt32BE(publicKey, 11, 0); + publicKey.utf8Write("ssh-ed25519", 4, 11); + writeUInt32BE(publicKey, pub.length, 15); + publicKey.set(pub, 19); + return publicKey; + } + function genOpenSSLEdPriv(priv) { + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + asnWriter.writeInt(0, Ber.Integer); + asnWriter.startSequence(); + asnWriter.writeOID("1.3.101.112"); + asnWriter.endSequence(); + asnWriter.startSequence(Ber.OctetString); + asnWriter.writeBuffer(priv, Ber.OctetString); + asnWriter.endSequence(); + asnWriter.endSequence(); + return makePEM("PRIVATE", asnWriter.buffer); + } + function genOpenSSLECDSAPub(oid, Q) { + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + asnWriter.startSequence(); + asnWriter.writeOID("1.2.840.10045.2.1"); + asnWriter.writeOID(oid); + asnWriter.endSequence(); + asnWriter.startSequence(Ber.BitString); + asnWriter.writeByte(0); + asnWriter._ensure(Q.length); + asnWriter._buf.set(Q, asnWriter._offset); + asnWriter._offset += Q.length; + asnWriter.endSequence(); + asnWriter.endSequence(); + return makePEM("PUBLIC", asnWriter.buffer); + } + function genOpenSSHECDSAPub(oid, Q) { + let curveName; + switch (oid) { + case "1.2.840.10045.3.1.7": + curveName = "nistp256"; + break; + case "1.3.132.0.34": + curveName = "nistp384"; + break; + case "1.3.132.0.35": + curveName = "nistp521"; + break; + default: + return; + } + const publicKey = Buffer.allocUnsafe(4 + 19 + 4 + 8 + 4 + Q.length); + writeUInt32BE(publicKey, 19, 0); + publicKey.utf8Write(`ecdsa-sha2-${curveName}`, 4, 19); + writeUInt32BE(publicKey, 8, 23); + publicKey.utf8Write(curveName, 27, 8); + writeUInt32BE(publicKey, Q.length, 35); + publicKey.set(Q, 39); + return publicKey; + } + function genOpenSSLECDSAPriv(oid, pub, priv) { + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + asnWriter.writeInt(1, Ber.Integer); + asnWriter.writeBuffer(priv, Ber.OctetString); + asnWriter.startSequence(160); + asnWriter.writeOID(oid); + asnWriter.endSequence(); + asnWriter.startSequence(161); + asnWriter.startSequence(Ber.BitString); + asnWriter.writeByte(0); + asnWriter._ensure(pub.length); + asnWriter._buf.set(pub, asnWriter._offset); + asnWriter._offset += pub.length; + asnWriter.endSequence(); + asnWriter.endSequence(); + asnWriter.endSequence(); + return makePEM("EC PRIVATE", asnWriter.buffer); + } + function genOpenSSLECDSAPubFromPriv(curveName, priv) { + const tempECDH = createECDH(curveName); + tempECDH.setPrivateKey(priv); + return tempECDH.getPublicKey(); + } + var BaseKey = { + sign: (() => { + if (typeof sign_ === "function") { + return function sign(data, algo) { + const pem = this[SYM_PRIV_PEM]; + if (pem === null) + return new Error("No private key available"); + if (!algo || typeof algo !== "string") + algo = this[SYM_HASH_ALGO]; + try { + return sign_(algo, data, pem); + } catch (ex) { + return ex; + } + }; + } + return function sign(data, algo) { + const pem = this[SYM_PRIV_PEM]; + if (pem === null) + return new Error("No private key available"); + if (!algo || typeof algo !== "string") + algo = this[SYM_HASH_ALGO]; + const signature = createSign(algo); + signature.update(data); + try { + return signature.sign(pem); + } catch (ex) { + return ex; + } + }; + })(), + verify: (() => { + if (typeof verify_ === "function") { + return function verify(data, signature, algo) { + const pem = this[SYM_PUB_PEM]; + if (pem === null) + return new Error("No public key available"); + if (!algo || typeof algo !== "string") + algo = this[SYM_HASH_ALGO]; + try { + return verify_(algo, data, pem, signature); + } catch (ex) { + return ex; + } + }; + } + return function verify(data, signature, algo) { + const pem = this[SYM_PUB_PEM]; + if (pem === null) + return new Error("No public key available"); + if (!algo || typeof algo !== "string") + algo = this[SYM_HASH_ALGO]; + const verifier = createVerify(algo); + verifier.update(data); + try { + return verifier.verify(pem, signature); + } catch (ex) { + return ex; + } + }; + })(), + isPrivateKey: function isPrivateKey() { + return this[SYM_PRIV_PEM] !== null; + }, + getPrivatePEM: function getPrivatePEM() { + return this[SYM_PRIV_PEM]; + }, + getPublicPEM: function getPublicPEM() { + return this[SYM_PUB_PEM]; + }, + getPublicSSH: function getPublicSSH() { + return this[SYM_PUB_SSH]; + }, + equals: function equals(key) { + const parsed = parseKey(key); + if (parsed instanceof Error) + return false; + return this.type === parsed.type && this[SYM_PRIV_PEM] === parsed[SYM_PRIV_PEM] && this[SYM_PUB_PEM] === parsed[SYM_PUB_PEM] && this[SYM_PUB_SSH].equals(parsed[SYM_PUB_SSH]); + } + }; + function OpenSSH_Private(type, comment, privPEM, pubPEM, pubSSH, algo, decrypted) { + this.type = type; + this.comment = comment; + this[SYM_PRIV_PEM] = privPEM; + this[SYM_PUB_PEM] = pubPEM; + this[SYM_PUB_SSH] = pubSSH; + this[SYM_HASH_ALGO] = algo; + this[SYM_DECRYPTED] = decrypted; + } + OpenSSH_Private.prototype = BaseKey; + { + let parseOpenSSHPrivKeys = function(data, nkeys, decrypted) { + const keys = []; + if (data.length < 8) + return new Error("Malformed OpenSSH private key"); + const check1 = readUInt32BE(data, 0); + const check2 = readUInt32BE(data, 4); + if (check1 !== check2) { + if (decrypted) { + return new Error( + "OpenSSH key integrity check failed -- bad passphrase?" + ); + } + return new Error("OpenSSH key integrity check failed"); + } + data._pos = 8; + let i; + let oid; + for (i = 0; i < nkeys; ++i) { + let algo; + let privPEM; + let pubPEM; + let pubSSH; + const type = readString(data, data._pos, true); + if (type === void 0) + return new Error("Malformed OpenSSH private key"); + switch (type) { + case "ssh-rsa": { + const n = readString(data, data._pos); + if (n === void 0) + return new Error("Malformed OpenSSH private key"); + const e = readString(data, data._pos); + if (e === void 0) + return new Error("Malformed OpenSSH private key"); + const d = readString(data, data._pos); + if (d === void 0) + return new Error("Malformed OpenSSH private key"); + const iqmp = readString(data, data._pos); + if (iqmp === void 0) + return new Error("Malformed OpenSSH private key"); + const p = readString(data, data._pos); + if (p === void 0) + return new Error("Malformed OpenSSH private key"); + const q = readString(data, data._pos); + if (q === void 0) + return new Error("Malformed OpenSSH private key"); + pubPEM = genOpenSSLRSAPub(n, e); + pubSSH = genOpenSSHRSAPub(n, e); + privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q); + algo = "sha1"; + break; + } + case "ssh-dss": { + const p = readString(data, data._pos); + if (p === void 0) + return new Error("Malformed OpenSSH private key"); + const q = readString(data, data._pos); + if (q === void 0) + return new Error("Malformed OpenSSH private key"); + const g = readString(data, data._pos); + if (g === void 0) + return new Error("Malformed OpenSSH private key"); + const y = readString(data, data._pos); + if (y === void 0) + return new Error("Malformed OpenSSH private key"); + const x = readString(data, data._pos); + if (x === void 0) + return new Error("Malformed OpenSSH private key"); + pubPEM = genOpenSSLDSAPub(p, q, g, y); + pubSSH = genOpenSSHDSAPub(p, q, g, y); + privPEM = genOpenSSLDSAPriv(p, q, g, y, x); + algo = "sha1"; + break; + } + case "ssh-ed25519": { + if (!eddsaSupported) + return new Error(`Unsupported OpenSSH private key type: ${type}`); + const edpub = readString(data, data._pos); + if (edpub === void 0 || edpub.length !== 32) + return new Error("Malformed OpenSSH private key"); + const edpriv = readString(data, data._pos); + if (edpriv === void 0 || edpriv.length !== 64) + return new Error("Malformed OpenSSH private key"); + pubPEM = genOpenSSLEdPub(edpub); + pubSSH = genOpenSSHEdPub(edpub); + privPEM = genOpenSSLEdPriv(bufferSlice(edpriv, 0, 32)); + algo = null; + break; + } + case "ecdsa-sha2-nistp256": + algo = "sha256"; + oid = "1.2.840.10045.3.1.7"; + // FALLTHROUGH + case "ecdsa-sha2-nistp384": + if (algo === void 0) { + algo = "sha384"; + oid = "1.3.132.0.34"; + } + // FALLTHROUGH + case "ecdsa-sha2-nistp521": { + if (algo === void 0) { + algo = "sha512"; + oid = "1.3.132.0.35"; + } + if (!skipFields(data, 1)) + return new Error("Malformed OpenSSH private key"); + const ecpub = readString(data, data._pos); + if (ecpub === void 0) + return new Error("Malformed OpenSSH private key"); + const ecpriv = readString(data, data._pos); + if (ecpriv === void 0) + return new Error("Malformed OpenSSH private key"); + pubPEM = genOpenSSLECDSAPub(oid, ecpub); + pubSSH = genOpenSSHECDSAPub(oid, ecpub); + privPEM = genOpenSSLECDSAPriv(oid, ecpub, ecpriv); + break; + } + default: + return new Error(`Unsupported OpenSSH private key type: ${type}`); + } + const privComment = readString(data, data._pos, true); + if (privComment === void 0) + return new Error("Malformed OpenSSH private key"); + keys.push( + new OpenSSH_Private( + type, + privComment, + privPEM, + pubPEM, + pubSSH, + algo, + decrypted + ) + ); + } + let cnt = 0; + for (i = data._pos; i < data.length; ++i) { + if (data[i] !== ++cnt % 255) + return new Error("Malformed OpenSSH private key"); + } + return keys; + }; + const regexp = /^-----BEGIN OPENSSH PRIVATE KEY-----(?:\r\n|\n)([\s\S]+)(?:\r\n|\n)-----END OPENSSH PRIVATE KEY-----$/; + OpenSSH_Private.parse = (str, passphrase) => { + const m = regexp.exec(str); + if (m === null) + return null; + let ret; + const data = Buffer.from(m[1], "base64"); + if (data.length < 31) + return new Error("Malformed OpenSSH private key"); + const magic = data.utf8Slice(0, 15); + if (magic !== "openssh-key-v1\0") + return new Error(`Unsupported OpenSSH key magic: ${magic}`); + const cipherName = readString(data, 15, true); + if (cipherName === void 0) + return new Error("Malformed OpenSSH private key"); + if (cipherName !== "none" && SUPPORTED_CIPHER.indexOf(cipherName) === -1) + return new Error(`Unsupported cipher for OpenSSH key: ${cipherName}`); + const kdfName = readString(data, data._pos, true); + if (kdfName === void 0) + return new Error("Malformed OpenSSH private key"); + if (kdfName !== "none") { + if (cipherName === "none") + return new Error("Malformed OpenSSH private key"); + if (kdfName !== "bcrypt") + return new Error(`Unsupported kdf name for OpenSSH key: ${kdfName}`); + if (!passphrase) { + return new Error( + "Encrypted private OpenSSH key detected, but no passphrase given" + ); + } + } else if (cipherName !== "none") { + return new Error("Malformed OpenSSH private key"); + } + let encInfo; + let cipherKey; + let cipherIV; + if (cipherName !== "none") + encInfo = CIPHER_INFO[cipherName]; + const kdfOptions = readString(data, data._pos); + if (kdfOptions === void 0) + return new Error("Malformed OpenSSH private key"); + if (kdfOptions.length) { + switch (kdfName) { + case "none": + return new Error("Malformed OpenSSH private key"); + case "bcrypt": { + const salt = readString(kdfOptions, 0); + if (salt === void 0 || kdfOptions._pos + 4 > kdfOptions.length) + return new Error("Malformed OpenSSH private key"); + const rounds = readUInt32BE(kdfOptions, kdfOptions._pos); + const gen = Buffer.allocUnsafe(encInfo.keyLen + encInfo.ivLen); + const r = bcrypt_pbkdf( + passphrase, + passphrase.length, + salt, + salt.length, + gen, + gen.length, + rounds + ); + if (r !== 0) + return new Error("Failed to generate information to decrypt key"); + cipherKey = bufferSlice(gen, 0, encInfo.keyLen); + cipherIV = bufferSlice(gen, encInfo.keyLen, gen.length); + break; + } + } + } else if (kdfName !== "none") { + return new Error("Malformed OpenSSH private key"); + } + if (data._pos + 3 >= data.length) + return new Error("Malformed OpenSSH private key"); + const keyCount = readUInt32BE(data, data._pos); + data._pos += 4; + if (keyCount > 0) { + for (let i = 0; i < keyCount; ++i) { + const pubData = readString(data, data._pos); + if (pubData === void 0) + return new Error("Malformed OpenSSH private key"); + const type = readString(pubData, 0, true); + if (type === void 0) + return new Error("Malformed OpenSSH private key"); + } + let privBlob = readString(data, data._pos); + if (privBlob === void 0) + return new Error("Malformed OpenSSH private key"); + if (cipherKey !== void 0) { + if (privBlob.length < encInfo.blockLen || privBlob.length % encInfo.blockLen !== 0) { + return new Error("Malformed OpenSSH private key"); + } + try { + const options = { authTagLength: encInfo.authLen }; + const decipher = createDecipheriv( + encInfo.sslName, + cipherKey, + cipherIV, + options + ); + decipher.setAutoPadding(false); + if (encInfo.authLen > 0) { + if (data.length - data._pos < encInfo.authLen) + return new Error("Malformed OpenSSH private key"); + decipher.setAuthTag( + bufferSlice(data, data._pos, data._pos += encInfo.authLen) + ); + } + privBlob = combineBuffers( + decipher.update(privBlob), + decipher.final() + ); + } catch (ex) { + return ex; + } + } + if (data._pos !== data.length) + return new Error("Malformed OpenSSH private key"); + ret = parseOpenSSHPrivKeys(privBlob, keyCount, cipherKey !== void 0); + } else { + ret = []; + } + if (ret instanceof Error) + return ret; + return ret[0]; + }; + } + function OpenSSH_Old_Private(type, comment, privPEM, pubPEM, pubSSH, algo, decrypted) { + this.type = type; + this.comment = comment; + this[SYM_PRIV_PEM] = privPEM; + this[SYM_PUB_PEM] = pubPEM; + this[SYM_PUB_SSH] = pubSSH; + this[SYM_HASH_ALGO] = algo; + this[SYM_DECRYPTED] = decrypted; + } + OpenSSH_Old_Private.prototype = BaseKey; + { + const regexp = /^-----BEGIN (RSA|DSA|EC) PRIVATE KEY-----(?:\r\n|\n)((?:[^:]+:\s*[\S].*(?:\r\n|\n))*)([\s\S]+)(?:\r\n|\n)-----END (RSA|DSA|EC) PRIVATE KEY-----$/; + OpenSSH_Old_Private.parse = (str, passphrase) => { + const m = regexp.exec(str); + if (m === null) + return null; + let privBlob = Buffer.from(m[3], "base64"); + let headers = m[2]; + let decrypted = false; + if (headers !== void 0) { + headers = headers.split(/\r\n|\n/g); + for (let i = 0; i < headers.length; ++i) { + const header = headers[i]; + let sepIdx = header.indexOf(":"); + if (header.slice(0, sepIdx) === "DEK-Info") { + const val = header.slice(sepIdx + 2); + sepIdx = val.indexOf(","); + if (sepIdx === -1) + continue; + const cipherName = val.slice(0, sepIdx).toLowerCase(); + if (supportedOpenSSLCiphers.indexOf(cipherName) === -1) { + return new Error( + `Cipher (${cipherName}) not supported for encrypted OpenSSH private key` + ); + } + const encInfo = CIPHER_INFO_OPENSSL[cipherName]; + if (!encInfo) { + return new Error( + `Cipher (${cipherName}) not supported for encrypted OpenSSH private key` + ); + } + const cipherIV = Buffer.from(val.slice(sepIdx + 1), "hex"); + if (cipherIV.length !== encInfo.ivLen) + return new Error("Malformed encrypted OpenSSH private key"); + if (!passphrase) { + return new Error( + "Encrypted OpenSSH private key detected, but no passphrase given" + ); + } + const ivSlice = bufferSlice(cipherIV, 0, 8); + let cipherKey = createHash("md5").update(passphrase).update(ivSlice).digest(); + while (cipherKey.length < encInfo.keyLen) { + cipherKey = combineBuffers( + cipherKey, + createHash("md5").update(cipherKey).update(passphrase).update(ivSlice).digest() + ); + } + if (cipherKey.length > encInfo.keyLen) + cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen); + try { + const decipher = createDecipheriv(cipherName, cipherKey, cipherIV); + decipher.setAutoPadding(false); + privBlob = combineBuffers( + decipher.update(privBlob), + decipher.final() + ); + decrypted = true; + } catch (ex) { + return ex; + } + } + } + } + let type; + let privPEM; + let pubPEM; + let pubSSH; + let algo; + let reader; + let errMsg = "Malformed OpenSSH private key"; + if (decrypted) + errMsg += ". Bad passphrase?"; + switch (m[1]) { + case "RSA": + type = "ssh-rsa"; + privPEM = makePEM("RSA PRIVATE", privBlob); + try { + reader = new Ber.Reader(privBlob); + reader.readSequence(); + reader.readInt(); + const n = reader.readString(Ber.Integer, true); + if (n === null) + return new Error(errMsg); + const e = reader.readString(Ber.Integer, true); + if (e === null) + return new Error(errMsg); + pubPEM = genOpenSSLRSAPub(n, e); + pubSSH = genOpenSSHRSAPub(n, e); + } catch { + return new Error(errMsg); + } + algo = "sha1"; + break; + case "DSA": + type = "ssh-dss"; + privPEM = makePEM("DSA PRIVATE", privBlob); + try { + reader = new Ber.Reader(privBlob); + reader.readSequence(); + reader.readInt(); + const p = reader.readString(Ber.Integer, true); + if (p === null) + return new Error(errMsg); + const q = reader.readString(Ber.Integer, true); + if (q === null) + return new Error(errMsg); + const g = reader.readString(Ber.Integer, true); + if (g === null) + return new Error(errMsg); + const y = reader.readString(Ber.Integer, true); + if (y === null) + return new Error(errMsg); + pubPEM = genOpenSSLDSAPub(p, q, g, y); + pubSSH = genOpenSSHDSAPub(p, q, g, y); + } catch { + return new Error(errMsg); + } + algo = "sha1"; + break; + case "EC": { + let ecSSLName; + let ecPriv; + let ecOID; + try { + reader = new Ber.Reader(privBlob); + reader.readSequence(); + reader.readInt(); + ecPriv = reader.readString(Ber.OctetString, true); + reader.readByte(); + const offset = reader.readLength(); + if (offset !== null) { + reader._offset = offset; + ecOID = reader.readOID(); + if (ecOID === null) + return new Error(errMsg); + switch (ecOID) { + case "1.2.840.10045.3.1.7": + ecSSLName = "prime256v1"; + type = "ecdsa-sha2-nistp256"; + algo = "sha256"; + break; + case "1.3.132.0.34": + ecSSLName = "secp384r1"; + type = "ecdsa-sha2-nistp384"; + algo = "sha384"; + break; + case "1.3.132.0.35": + ecSSLName = "secp521r1"; + type = "ecdsa-sha2-nistp521"; + algo = "sha512"; + break; + default: + return new Error(`Unsupported private key EC OID: ${ecOID}`); + } + } else { + return new Error(errMsg); + } + } catch { + return new Error(errMsg); + } + privPEM = makePEM("EC PRIVATE", privBlob); + const pubBlob = genOpenSSLECDSAPubFromPriv(ecSSLName, ecPriv); + pubPEM = genOpenSSLECDSAPub(ecOID, pubBlob); + pubSSH = genOpenSSHECDSAPub(ecOID, pubBlob); + break; + } + } + return new OpenSSH_Old_Private( + type, + "", + privPEM, + pubPEM, + pubSSH, + algo, + decrypted + ); + }; + } + function PPK_Private(type, comment, privPEM, pubPEM, pubSSH, algo, decrypted) { + this.type = type; + this.comment = comment; + this[SYM_PRIV_PEM] = privPEM; + this[SYM_PUB_PEM] = pubPEM; + this[SYM_PUB_SSH] = pubSSH; + this[SYM_HASH_ALGO] = algo; + this[SYM_DECRYPTED] = decrypted; + } + PPK_Private.prototype = BaseKey; + { + const EMPTY_PASSPHRASE = Buffer.alloc(0); + const PPK_IV = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + const PPK_PP1 = Buffer.from([0, 0, 0, 0]); + const PPK_PP2 = Buffer.from([0, 0, 0, 1]); + const regexp = /^PuTTY-User-Key-File-2: (ssh-(?:rsa|dss))\r?\nEncryption: (aes256-cbc|none)\r?\nComment: ([^\r\n]*)\r?\nPublic-Lines: \d+\r?\n([\s\S]+?)\r?\nPrivate-Lines: \d+\r?\n([\s\S]+?)\r?\nPrivate-MAC: ([^\r\n]+)/; + PPK_Private.parse = (str, passphrase) => { + const m = regexp.exec(str); + if (m === null) + return null; + const cipherName = m[2]; + const encrypted = cipherName !== "none"; + if (encrypted && !passphrase) { + return new Error( + "Encrypted PPK private key detected, but no passphrase given" + ); + } + let privBlob = Buffer.from(m[5], "base64"); + if (encrypted) { + const encInfo = CIPHER_INFO[cipherName]; + let cipherKey = combineBuffers( + createHash("sha1").update(PPK_PP1).update(passphrase).digest(), + createHash("sha1").update(PPK_PP2).update(passphrase).digest() + ); + if (cipherKey.length > encInfo.keyLen) + cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen); + try { + const decipher = createDecipheriv(encInfo.sslName, cipherKey, PPK_IV); + decipher.setAutoPadding(false); + privBlob = combineBuffers( + decipher.update(privBlob), + decipher.final() + ); + } catch (ex) { + return ex; + } + } + const type = m[1]; + const comment = m[3]; + const pubBlob = Buffer.from(m[4], "base64"); + const mac = m[6]; + const typeLen = type.length; + const cipherNameLen = cipherName.length; + const commentLen = Buffer.byteLength(comment); + const pubLen = pubBlob.length; + const privLen = privBlob.length; + const macData = Buffer.allocUnsafe(4 + typeLen + 4 + cipherNameLen + 4 + commentLen + 4 + pubLen + 4 + privLen); + let p = 0; + writeUInt32BE(macData, typeLen, p); + macData.utf8Write(type, p += 4, typeLen); + writeUInt32BE(macData, cipherNameLen, p += typeLen); + macData.utf8Write(cipherName, p += 4, cipherNameLen); + writeUInt32BE(macData, commentLen, p += cipherNameLen); + macData.utf8Write(comment, p += 4, commentLen); + writeUInt32BE(macData, pubLen, p += commentLen); + macData.set(pubBlob, p += 4); + writeUInt32BE(macData, privLen, p += pubLen); + macData.set(privBlob, p + 4); + if (!passphrase) + passphrase = EMPTY_PASSPHRASE; + const calcMAC = createHmac( + "sha1", + createHash("sha1").update("putty-private-key-file-mac-key").update(passphrase).digest() + ).update(macData).digest("hex"); + if (calcMAC !== mac) { + if (encrypted) { + return new Error( + "PPK private key integrity check failed -- bad passphrase?" + ); + } + return new Error("PPK private key integrity check failed"); + } + let pubPEM; + let pubSSH; + let privPEM; + pubBlob._pos = 0; + skipFields(pubBlob, 1); + switch (type) { + case "ssh-rsa": { + const e = readString(pubBlob, pubBlob._pos); + if (e === void 0) + return new Error("Malformed PPK public key"); + const n = readString(pubBlob, pubBlob._pos); + if (n === void 0) + return new Error("Malformed PPK public key"); + const d = readString(privBlob, 0); + if (d === void 0) + return new Error("Malformed PPK private key"); + const p2 = readString(privBlob, privBlob._pos); + if (p2 === void 0) + return new Error("Malformed PPK private key"); + const q = readString(privBlob, privBlob._pos); + if (q === void 0) + return new Error("Malformed PPK private key"); + const iqmp = readString(privBlob, privBlob._pos); + if (iqmp === void 0) + return new Error("Malformed PPK private key"); + pubPEM = genOpenSSLRSAPub(n, e); + pubSSH = genOpenSSHRSAPub(n, e); + privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p2, q); + break; + } + case "ssh-dss": { + const p2 = readString(pubBlob, pubBlob._pos); + if (p2 === void 0) + return new Error("Malformed PPK public key"); + const q = readString(pubBlob, pubBlob._pos); + if (q === void 0) + return new Error("Malformed PPK public key"); + const g = readString(pubBlob, pubBlob._pos); + if (g === void 0) + return new Error("Malformed PPK public key"); + const y = readString(pubBlob, pubBlob._pos); + if (y === void 0) + return new Error("Malformed PPK public key"); + const x = readString(privBlob, 0); + if (x === void 0) + return new Error("Malformed PPK private key"); + pubPEM = genOpenSSLDSAPub(p2, q, g, y); + pubSSH = genOpenSSHDSAPub(p2, q, g, y); + privPEM = genOpenSSLDSAPriv(p2, q, g, y, x); + break; + } + } + return new PPK_Private( + type, + comment, + privPEM, + pubPEM, + pubSSH, + "sha1", + encrypted + ); + }; + } + function OpenSSH_Public(type, comment, pubPEM, pubSSH, algo) { + this.type = type; + this.comment = comment; + this[SYM_PRIV_PEM] = null; + this[SYM_PUB_PEM] = pubPEM; + this[SYM_PUB_SSH] = pubSSH; + this[SYM_HASH_ALGO] = algo; + this[SYM_DECRYPTED] = false; + } + OpenSSH_Public.prototype = BaseKey; + { + let regexp; + if (eddsaSupported) + regexp = /^(((?:ssh-(?:rsa|dss|ed25519))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\s+([\S].*)?)$/; + else + regexp = /^(((?:ssh-(?:rsa|dss))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\s+([\S].*)?)$/; + OpenSSH_Public.parse = (str) => { + const m = regexp.exec(str); + if (m === null) + return null; + const fullType = m[1]; + const baseType = m[2]; + const data = Buffer.from(m[3], "base64"); + const comment = m[4] || ""; + const type = readString(data, data._pos, true); + if (type === void 0 || type.indexOf(baseType) !== 0) + return new Error("Malformed OpenSSH public key"); + return parseDER(data, baseType, comment, fullType); + }; + } + function RFC4716_Public(type, comment, pubPEM, pubSSH, algo) { + this.type = type; + this.comment = comment; + this[SYM_PRIV_PEM] = null; + this[SYM_PUB_PEM] = pubPEM; + this[SYM_PUB_SSH] = pubSSH; + this[SYM_HASH_ALGO] = algo; + this[SYM_DECRYPTED] = false; + } + RFC4716_Public.prototype = BaseKey; + { + const regexp = /^---- BEGIN SSH2 PUBLIC KEY ----(?:\r?\n)((?:.{0,72}\r?\n)+)---- END SSH2 PUBLIC KEY ----$/; + const RE_DATA = /^[A-Z0-9a-z/+=\r\n]+$/; + const RE_HEADER = /^([\x21-\x39\x3B-\x7E]{1,64}): ((?:[^\\]*\\\r?\n)*[^\r\n]+)\r?\n/gm; + const RE_HEADER_ENDS = /\\\r?\n/g; + RFC4716_Public.parse = (str) => { + let m = regexp.exec(str); + if (m === null) + return null; + const body = m[1]; + let dataStart = 0; + let comment = ""; + while (m = RE_HEADER.exec(body)) { + const headerName = m[1]; + const headerValue = m[2].replace(RE_HEADER_ENDS, ""); + if (headerValue.length > 1024) { + RE_HEADER.lastIndex = 0; + return new Error("Malformed RFC4716 public key"); + } + dataStart = RE_HEADER.lastIndex; + if (headerName.toLowerCase() === "comment") { + comment = headerValue; + if (comment.length > 1 && comment.charCodeAt(0) === 34 && comment.charCodeAt(comment.length - 1) === 34) { + comment = comment.slice(1, -1); + } + } + } + let data = body.slice(dataStart); + if (!RE_DATA.test(data)) + return new Error("Malformed RFC4716 public key"); + data = Buffer.from(data, "base64"); + const type = readString(data, 0, true); + if (type === void 0) + return new Error("Malformed RFC4716 public key"); + let pubPEM = null; + let pubSSH = null; + switch (type) { + case "ssh-rsa": { + const e = readString(data, data._pos); + if (e === void 0) + return new Error("Malformed RFC4716 public key"); + const n = readString(data, data._pos); + if (n === void 0) + return new Error("Malformed RFC4716 public key"); + pubPEM = genOpenSSLRSAPub(n, e); + pubSSH = genOpenSSHRSAPub(n, e); + break; + } + case "ssh-dss": { + const p = readString(data, data._pos); + if (p === void 0) + return new Error("Malformed RFC4716 public key"); + const q = readString(data, data._pos); + if (q === void 0) + return new Error("Malformed RFC4716 public key"); + const g = readString(data, data._pos); + if (g === void 0) + return new Error("Malformed RFC4716 public key"); + const y = readString(data, data._pos); + if (y === void 0) + return new Error("Malformed RFC4716 public key"); + pubPEM = genOpenSSLDSAPub(p, q, g, y); + pubSSH = genOpenSSHDSAPub(p, q, g, y); + break; + } + default: + return new Error("Malformed RFC4716 public key"); + } + return new RFC4716_Public(type, comment, pubPEM, pubSSH, "sha1"); + }; + } + function parseDER(data, baseType, comment, fullType) { + if (!isSupportedKeyType(baseType)) + return new Error(`Unsupported OpenSSH public key type: ${baseType}`); + let algo; + let oid; + let pubPEM = null; + let pubSSH = null; + switch (baseType) { + case "ssh-rsa": { + const e = readString(data, data._pos || 0); + if (e === void 0) + return new Error("Malformed OpenSSH public key"); + const n = readString(data, data._pos); + if (n === void 0) + return new Error("Malformed OpenSSH public key"); + pubPEM = genOpenSSLRSAPub(n, e); + pubSSH = genOpenSSHRSAPub(n, e); + algo = "sha1"; + break; + } + case "ssh-dss": { + const p = readString(data, data._pos || 0); + if (p === void 0) + return new Error("Malformed OpenSSH public key"); + const q = readString(data, data._pos); + if (q === void 0) + return new Error("Malformed OpenSSH public key"); + const g = readString(data, data._pos); + if (g === void 0) + return new Error("Malformed OpenSSH public key"); + const y = readString(data, data._pos); + if (y === void 0) + return new Error("Malformed OpenSSH public key"); + pubPEM = genOpenSSLDSAPub(p, q, g, y); + pubSSH = genOpenSSHDSAPub(p, q, g, y); + algo = "sha1"; + break; + } + case "ssh-ed25519": { + const edpub = readString(data, data._pos || 0); + if (edpub === void 0 || edpub.length !== 32) + return new Error("Malformed OpenSSH public key"); + pubPEM = genOpenSSLEdPub(edpub); + pubSSH = genOpenSSHEdPub(edpub); + algo = null; + break; + } + case "ecdsa-sha2-nistp256": + algo = "sha256"; + oid = "1.2.840.10045.3.1.7"; + // FALLTHROUGH + case "ecdsa-sha2-nistp384": + if (algo === void 0) { + algo = "sha384"; + oid = "1.3.132.0.34"; + } + // FALLTHROUGH + case "ecdsa-sha2-nistp521": { + if (algo === void 0) { + algo = "sha512"; + oid = "1.3.132.0.35"; + } + if (!skipFields(data, 1)) + return new Error("Malformed OpenSSH public key"); + const ecpub = readString(data, data._pos || 0); + if (ecpub === void 0) + return new Error("Malformed OpenSSH public key"); + pubPEM = genOpenSSLECDSAPub(oid, ecpub); + pubSSH = genOpenSSHECDSAPub(oid, ecpub); + break; + } + default: + return new Error(`Unsupported OpenSSH public key type: ${baseType}`); + } + return new OpenSSH_Public(fullType, comment, pubPEM, pubSSH, algo); + } + function isSupportedKeyType(type) { + switch (type) { + case "ssh-rsa": + case "ssh-dss": + case "ecdsa-sha2-nistp256": + case "ecdsa-sha2-nistp384": + case "ecdsa-sha2-nistp521": + return true; + case "ssh-ed25519": + if (eddsaSupported) + return true; + // FALLTHROUGH + default: + return false; + } + } + function isParsedKey(val) { + if (!val) + return false; + return typeof val[SYM_DECRYPTED] === "boolean"; + } + function parseKey(data, passphrase) { + if (isParsedKey(data)) + return data; + let origBuffer; + if (Buffer.isBuffer(data)) { + origBuffer = data; + data = data.utf8Slice(0, data.length).trim(); + } else if (typeof data === "string") { + data = data.trim(); + } else { + return new Error("Key data must be a Buffer or string"); + } + if (passphrase != void 0) { + if (typeof passphrase === "string") + passphrase = Buffer.from(passphrase); + else if (!Buffer.isBuffer(passphrase)) + return new Error("Passphrase must be a string or Buffer when supplied"); + } + let ret; + if ((ret = OpenSSH_Private.parse(data, passphrase)) !== null) + return ret; + if ((ret = OpenSSH_Old_Private.parse(data, passphrase)) !== null) + return ret; + if ((ret = PPK_Private.parse(data, passphrase)) !== null) + return ret; + if ((ret = OpenSSH_Public.parse(data)) !== null) + return ret; + if ((ret = RFC4716_Public.parse(data)) !== null) + return ret; + if (origBuffer) { + binaryKeyParser.init(origBuffer, 0); + const type = binaryKeyParser.readString(true); + if (type !== void 0) { + data = binaryKeyParser.readRaw(); + if (data !== void 0) { + ret = parseDER(data, type, "", type); + if (ret instanceof Error) + ret = null; + } + } + binaryKeyParser.clear(); + } + if (ret) + return ret; + return new Error("Unsupported key format"); + } + module2.exports = { + isParsedKey, + isSupportedKeyType, + parseDERKey: (data, type) => parseDER(data, type, "", type), + parseKey + }; + } +}); + +// node_modules/ssh2/lib/agent.js +var require_agent2 = __commonJS({ + "node_modules/ssh2/lib/agent.js"(exports2, module2) { + "use strict"; + var { Socket } = require("net"); + var { Duplex } = require("stream"); + var { resolve } = require("path"); + var { readFile } = require("fs"); + var { execFile, spawn } = require("child_process"); + var { isParsedKey, parseKey } = require_keyParser(); + var { + makeBufferParser, + readUInt32BE, + writeUInt32BE, + writeUInt32LE + } = require_utils3(); + function once(cb) { + let called = false; + return (...args) => { + if (called) + return; + called = true; + cb(...args); + }; + } + function concat(buf1, buf2) { + const combined = Buffer.allocUnsafe(buf1.length + buf2.length); + buf1.copy(combined, 0); + buf2.copy(combined, buf1.length); + return combined; + } + function noop3() { + } + var EMPTY_BUF = Buffer.alloc(0); + var binaryParser = makeBufferParser(); + var BaseAgent = class { + getIdentities(cb) { + cb(new Error("Missing getIdentities() implementation")); + } + sign(pubKey, data, options, cb) { + if (typeof options === "function") + cb = options; + cb(new Error("Missing sign() implementation")); + } + }; + var OpenSSHAgent = class extends BaseAgent { + constructor(socketPath) { + super(); + this.socketPath = socketPath; + } + getStream(cb) { + cb = once(cb); + const sock = new Socket(); + sock.on("connect", () => { + cb(null, sock); + }); + sock.on("close", onFail).on("end", onFail).on("error", onFail); + sock.connect(this.socketPath); + function onFail() { + try { + sock.destroy(); + } catch { + } + cb(new Error("Failed to connect to agent")); + } + } + getIdentities(cb) { + cb = once(cb); + this.getStream((err, stream2) => { + function onFail(err2) { + if (stream2) { + try { + stream2.destroy(); + } catch { + } + } + if (!err2) + err2 = new Error("Failed to retrieve identities from agent"); + cb(err2); + } + if (err) + return onFail(err); + const protocol = new AgentProtocol(true); + protocol.on("error", onFail); + protocol.pipe(stream2).pipe(protocol); + stream2.on("close", onFail).on("end", onFail).on("error", onFail); + protocol.getIdentities((err2, keys) => { + if (err2) + return onFail(err2); + try { + stream2.destroy(); + } catch { + } + cb(null, keys); + }); + }); + } + sign(pubKey, data, options, cb) { + if (typeof options === "function") { + cb = options; + options = void 0; + } else if (typeof options !== "object" || options === null) { + options = void 0; + } + cb = once(cb); + this.getStream((err, stream2) => { + function onFail(err2) { + if (stream2) { + try { + stream2.destroy(); + } catch { + } + } + if (!err2) + err2 = new Error("Failed to sign data with agent"); + cb(err2); + } + if (err) + return onFail(err); + const protocol = new AgentProtocol(true); + protocol.on("error", onFail); + protocol.pipe(stream2).pipe(protocol); + stream2.on("close", onFail).on("end", onFail).on("error", onFail); + protocol.sign(pubKey, data, options, (err2, sig) => { + if (err2) + return onFail(err2); + try { + stream2.destroy(); + } catch { + } + cb(null, sig); + }); + }); + } + }; + var PageantAgent = (() => { + const RET_ERR_BADARGS = 10; + const RET_ERR_UNAVAILABLE = 11; + const RET_ERR_NOMAP = 12; + const RET_ERR_BINSTDIN = 13; + const RET_ERR_BINSTDOUT = 14; + const RET_ERR_BADLEN = 15; + const EXEPATH = resolve(__dirname, "..", "util/pagent.exe"); + const ERROR = { + [RET_ERR_BADARGS]: new Error("Invalid pagent.exe arguments"), + [RET_ERR_UNAVAILABLE]: new Error("Pageant is not running"), + [RET_ERR_NOMAP]: new Error("pagent.exe could not create an mmap"), + [RET_ERR_BINSTDIN]: new Error("pagent.exe could not set mode for stdin"), + [RET_ERR_BINSTDOUT]: new Error("pagent.exe could not set mode for stdout"), + [RET_ERR_BADLEN]: new Error("pagent.exe did not get expected input payload") + }; + function destroy(stream2) { + stream2.buffer = null; + if (stream2.proc) { + stream2.proc.kill(); + stream2.proc = void 0; + } + } + class PageantSocket extends Duplex { + constructor() { + super(); + this.proc = void 0; + this.buffer = null; + } + _read(n) { + } + _write(data, encoding, cb) { + if (this.buffer === null) { + this.buffer = data; + } else { + const newBuffer = Buffer.allocUnsafe(this.buffer.length + data.length); + this.buffer.copy(newBuffer, 0); + data.copy(newBuffer, this.buffer.length); + this.buffer = newBuffer; + } + if (this.buffer.length < 4) + return cb(); + const len = readUInt32BE(this.buffer, 0); + if (this.buffer.length - 4 < len) + return cb(); + data = this.buffer.slice(0, 4 + len); + if (this.buffer.length > 4 + len) + return cb(new Error("Unexpected multiple agent requests")); + this.buffer = null; + let error2; + const proc = this.proc = spawn(EXEPATH, [data.length]); + proc.stdout.on("data", (data2) => { + this.push(data2); + }); + proc.on("error", (err) => { + error2 = err; + cb(error2); + }); + proc.on("close", (code) => { + this.proc = void 0; + if (!error2) { + if (error2 = ERROR[code]) + return cb(error2); + cb(); + } + }); + proc.stdin.end(data); + } + _final(cb) { + destroy(this); + cb(); + } + _destroy(err, cb) { + destroy(this); + cb(); + } + } + return class PageantAgent extends OpenSSHAgent { + getStream(cb) { + cb(null, new PageantSocket()); + } + }; + })(); + var CygwinAgent = /* @__PURE__ */ (() => { + const RE_CYGWIN_SOCK = /^!(\d+) s ([A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8})/; + return class CygwinAgent extends OpenSSHAgent { + getStream(cb) { + cb = once(cb); + let socketPath = this.socketPath; + let triedCygpath = false; + readFile(socketPath, function readCygsocket(err, data) { + if (err) { + if (triedCygpath) + return cb(new Error("Invalid cygwin unix socket path")); + execFile("cygpath", ["-w", socketPath], (err2, stdout, stderr) => { + if (err2 || stdout.length === 0) + return cb(new Error("Invalid cygwin unix socket path")); + triedCygpath = true; + socketPath = stdout.toString().replace(/[\r\n]/g, ""); + readFile(socketPath, readCygsocket); + }); + return; + } + const m = RE_CYGWIN_SOCK.exec(data.toString("ascii")); + if (!m) + return cb(new Error("Malformed cygwin unix socket file")); + let state; + let bc = 0; + let isRetrying = false; + const inBuf = []; + let sock; + let credsBuf = Buffer.alloc(12); + const port = parseInt(m[1], 10); + const secret = m[2].replace(/-/g, ""); + const secretBuf = Buffer.allocUnsafe(16); + for (let i = 0, j = 0; j < 32; ++i, j += 2) + secretBuf[i] = parseInt(secret.substring(j, j + 2), 16); + for (let i = 0; i < 16; i += 4) + writeUInt32LE(secretBuf, readUInt32BE(secretBuf, i), i); + tryConnect(); + function _onconnect() { + bc = 0; + state = "secret"; + sock.write(secretBuf); + } + function _ondata(data2) { + bc += data2.length; + if (state === "secret") { + if (bc === 16) { + bc = 0; + state = "creds"; + sock.write(credsBuf); + } + return; + } + if (state === "creds") { + if (!isRetrying) + inBuf.push(data2); + if (bc === 12) { + sock.removeListener("connect", _onconnect); + sock.removeListener("data", _ondata); + sock.removeListener("error", onFail); + sock.removeListener("end", onFail); + sock.removeListener("close", onFail); + if (isRetrying) + return cb(null, sock); + isRetrying = true; + credsBuf = Buffer.concat(inBuf); + writeUInt32LE(credsBuf, process.pid, 0); + sock.on("error", () => { + }); + sock.destroy(); + tryConnect(); + } + } + } + function onFail() { + cb(new Error("Problem negotiating cygwin unix socket security")); + } + function tryConnect() { + sock = new Socket(); + sock.on("connect", _onconnect); + sock.on("data", _ondata); + sock.on("error", onFail); + sock.on("end", onFail); + sock.on("close", onFail); + sock.connect(port); + } + }); + } + }; + })(); + var WINDOWS_PIPE_REGEX = /^[/\\][/\\]\.[/\\]pipe[/\\].+/; + function createAgent(path) { + if (process.platform === "win32" && !WINDOWS_PIPE_REGEX.test(path)) { + return path === "pageant" ? new PageantAgent() : new CygwinAgent(path); + } + return new OpenSSHAgent(path); + } + var AgentProtocol = (() => { + const SSH_AGENTC_REQUEST_IDENTITIES = 11; + const SSH_AGENTC_SIGN_REQUEST = 13; + const SSH_AGENT_FAILURE = 5; + const SSH_AGENT_IDENTITIES_ANSWER = 12; + const SSH_AGENT_SIGN_RESPONSE = 14; + const SSH_AGENT_RSA_SHA2_256 = 1 << 1; + const SSH_AGENT_RSA_SHA2_512 = 1 << 2; + const ROLE_CLIENT = 0; + const ROLE_SERVER = 1; + function processResponses(protocol) { + let ret; + while (protocol[SYM_REQS].length) { + const nextResponse = protocol[SYM_REQS][0][SYM_RESP]; + if (nextResponse === void 0) + break; + protocol[SYM_REQS].shift(); + ret = protocol.push(nextResponse); + } + return ret; + } + const SYM_TYPE = /* @__PURE__ */ Symbol("Inbound Request Type"); + const SYM_RESP = /* @__PURE__ */ Symbol("Inbound Request Response"); + const SYM_CTX = /* @__PURE__ */ Symbol("Inbound Request Context"); + class AgentInboundRequest { + constructor(type, ctx) { + this[SYM_TYPE] = type; + this[SYM_RESP] = void 0; + this[SYM_CTX] = ctx; + } + hasResponded() { + return this[SYM_RESP] !== void 0; + } + getType() { + return this[SYM_TYPE]; + } + getContext() { + return this[SYM_CTX]; + } + } + function respond(protocol, req, data) { + req[SYM_RESP] = data; + return processResponses(protocol); + } + function cleanup(protocol) { + protocol[SYM_BUFFER] = null; + if (protocol[SYM_MODE] === ROLE_CLIENT) { + const reqs = protocol[SYM_REQS]; + if (reqs && reqs.length) { + protocol[SYM_REQS] = []; + for (const req of reqs) + req.cb(new Error("No reply from server")); + } + } + try { + protocol.end(); + } catch { + } + setImmediate(() => { + if (!protocol[SYM_ENDED]) + protocol.emit("end"); + if (!protocol[SYM_CLOSED]) + protocol.emit("close"); + }); + } + function onClose() { + this[SYM_CLOSED] = true; + } + function onEnd() { + this[SYM_ENDED] = true; + } + const SYM_REQS = /* @__PURE__ */ Symbol("Requests"); + const SYM_MODE = /* @__PURE__ */ Symbol("Agent Protocol Role"); + const SYM_BUFFER = /* @__PURE__ */ Symbol("Agent Protocol Buffer"); + const SYM_MSGLEN = /* @__PURE__ */ Symbol("Agent Protocol Current Message Length"); + const SYM_CLOSED = /* @__PURE__ */ Symbol("Agent Protocol Closed"); + const SYM_ENDED = /* @__PURE__ */ Symbol("Agent Protocol Ended"); + return class AgentProtocol extends Duplex { + /* + Notes: + - `constraint` type consists of: + byte constraint_type + byte[] constraint_data + where `constraint_type` is one of: + * SSH_AGENT_CONSTRAIN_LIFETIME + - `constraint_data` consists of: + uint32 seconds + * SSH_AGENT_CONSTRAIN_CONFIRM + - `constraint_data` N/A + * SSH_AGENT_CONSTRAIN_EXTENSION + - `constraint_data` consists of: + string extension name + byte[] extension-specific details + */ + constructor(isClient) { + super({ autoDestroy: true, emitClose: false }); + this[SYM_MODE] = isClient ? ROLE_CLIENT : ROLE_SERVER; + this[SYM_REQS] = []; + this[SYM_BUFFER] = null; + this[SYM_MSGLEN] = -1; + this.once("end", onEnd); + this.once("close", onClose); + } + _read(n) { + } + _write(data, encoding, cb) { + if (this[SYM_BUFFER] === null) + this[SYM_BUFFER] = data; + else + this[SYM_BUFFER] = concat(this[SYM_BUFFER], data); + let buffer = this[SYM_BUFFER]; + let bufferLen = buffer.length; + let p = 0; + while (p < bufferLen) { + if (bufferLen < 5) + break; + if (this[SYM_MSGLEN] === -1) + this[SYM_MSGLEN] = readUInt32BE(buffer, p); + if (bufferLen < 4 + this[SYM_MSGLEN]) + break; + const msgType = buffer[p += 4]; + ++p; + if (this[SYM_MODE] === ROLE_CLIENT) { + if (this[SYM_REQS].length === 0) + return cb(new Error("Received unexpected message from server")); + const req = this[SYM_REQS].shift(); + switch (msgType) { + case SSH_AGENT_FAILURE: + req.cb(new Error("Agent responded with failure")); + break; + case SSH_AGENT_IDENTITIES_ANSWER: { + if (req.type !== SSH_AGENTC_REQUEST_IDENTITIES) + return cb(new Error("Agent responded with wrong message type")); + binaryParser.init(buffer, p); + const numKeys = binaryParser.readUInt32BE(); + if (numKeys === void 0) { + binaryParser.clear(); + return cb(new Error("Malformed agent response")); + } + const keys = []; + for (let i = 0; i < numKeys; ++i) { + let pubKey = binaryParser.readString(); + if (pubKey === void 0) { + binaryParser.clear(); + return cb(new Error("Malformed agent response")); + } + const comment = binaryParser.readString(true); + if (comment === void 0) { + binaryParser.clear(); + return cb(new Error("Malformed agent response")); + } + pubKey = parseKey(pubKey); + if (pubKey instanceof Error) + continue; + pubKey.comment = pubKey.comment || comment; + keys.push(pubKey); + } + p = binaryParser.pos(); + binaryParser.clear(); + req.cb(null, keys); + break; + } + case SSH_AGENT_SIGN_RESPONSE: { + if (req.type !== SSH_AGENTC_SIGN_REQUEST) + return cb(new Error("Agent responded with wrong message type")); + binaryParser.init(buffer, p); + let signature = binaryParser.readString(); + p = binaryParser.pos(); + binaryParser.clear(); + if (signature === void 0) + return cb(new Error("Malformed agent response")); + binaryParser.init(signature, 0); + binaryParser.readString(true); + signature = binaryParser.readString(); + binaryParser.clear(); + if (signature === void 0) + return cb(new Error("Malformed OpenSSH signature format")); + req.cb(null, signature); + break; + } + default: + return cb( + new Error("Agent responded with unsupported message type") + ); + } + } else { + switch (msgType) { + case SSH_AGENTC_REQUEST_IDENTITIES: { + const req = new AgentInboundRequest(msgType); + this[SYM_REQS].push(req); + this.emit("identities", req); + break; + } + case SSH_AGENTC_SIGN_REQUEST: { + binaryParser.init(buffer, p); + let pubKey = binaryParser.readString(); + const data2 = binaryParser.readString(); + const flagsVal = binaryParser.readUInt32BE(); + p = binaryParser.pos(); + binaryParser.clear(); + if (flagsVal === void 0) { + const req2 = new AgentInboundRequest(msgType); + this[SYM_REQS].push(req2); + return this.failureReply(req2); + } + pubKey = parseKey(pubKey); + if (pubKey instanceof Error) { + const req2 = new AgentInboundRequest(msgType); + this[SYM_REQS].push(req2); + return this.failureReply(req2); + } + const flags = { + hash: void 0 + }; + let ctx; + if (pubKey.type === "ssh-rsa") { + if (flagsVal & SSH_AGENT_RSA_SHA2_256) { + ctx = "rsa-sha2-256"; + flags.hash = "sha256"; + } else if (flagsVal & SSH_AGENT_RSA_SHA2_512) { + ctx = "rsa-sha2-512"; + flags.hash = "sha512"; + } + } + if (ctx === void 0) + ctx = pubKey.type; + const req = new AgentInboundRequest(msgType, ctx); + this[SYM_REQS].push(req); + this.emit("sign", req, pubKey, data2, flags); + break; + } + default: { + const req = new AgentInboundRequest(msgType); + this[SYM_REQS].push(req); + this.failureReply(req); + } + } + } + this[SYM_MSGLEN] = -1; + if (p === bufferLen) { + this[SYM_BUFFER] = null; + break; + } else { + this[SYM_BUFFER] = buffer = buffer.slice(p); + bufferLen = buffer.length; + p = 0; + } + } + cb(); + } + _destroy(err, cb) { + cleanup(this); + cb(); + } + _final(cb) { + cleanup(this); + cb(); + } + // Client->Server messages ================================================= + sign(pubKey, data, options, cb) { + if (this[SYM_MODE] !== ROLE_CLIENT) + throw new Error("Client-only method called with server role"); + if (typeof options === "function") { + cb = options; + options = void 0; + } else if (typeof options !== "object" || options === null) { + options = void 0; + } + let flags = 0; + pubKey = parseKey(pubKey); + if (pubKey instanceof Error) + throw new Error("Invalid public key argument"); + if (pubKey.type === "ssh-rsa" && options) { + switch (options.hash) { + case "sha256": + flags = SSH_AGENT_RSA_SHA2_256; + break; + case "sha512": + flags = SSH_AGENT_RSA_SHA2_512; + break; + } + } + pubKey = pubKey.getPublicSSH(); + const type = SSH_AGENTC_SIGN_REQUEST; + const keyLen = pubKey.length; + const dataLen = data.length; + let p = 0; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + keyLen + 4 + dataLen + 4); + writeUInt32BE(buf, buf.length - 4, p); + buf[p += 4] = type; + writeUInt32BE(buf, keyLen, ++p); + pubKey.copy(buf, p += 4); + writeUInt32BE(buf, dataLen, p += keyLen); + data.copy(buf, p += 4); + writeUInt32BE(buf, flags, p += dataLen); + if (typeof cb !== "function") + cb = noop3; + this[SYM_REQS].push({ type, cb }); + return this.push(buf); + } + getIdentities(cb) { + if (this[SYM_MODE] !== ROLE_CLIENT) + throw new Error("Client-only method called with server role"); + const type = SSH_AGENTC_REQUEST_IDENTITIES; + let p = 0; + const buf = Buffer.allocUnsafe(4 + 1); + writeUInt32BE(buf, buf.length - 4, p); + buf[p += 4] = type; + if (typeof cb !== "function") + cb = noop3; + this[SYM_REQS].push({ type, cb }); + return this.push(buf); + } + // Server->Client messages ================================================= + failureReply(req) { + if (this[SYM_MODE] !== ROLE_SERVER) + throw new Error("Server-only method called with client role"); + if (!(req instanceof AgentInboundRequest)) + throw new Error("Wrong request argument"); + if (req.hasResponded()) + return true; + let p = 0; + const buf = Buffer.allocUnsafe(4 + 1); + writeUInt32BE(buf, buf.length - 4, p); + buf[p += 4] = SSH_AGENT_FAILURE; + return respond(this, req, buf); + } + getIdentitiesReply(req, keys) { + if (this[SYM_MODE] !== ROLE_SERVER) + throw new Error("Server-only method called with client role"); + if (!(req instanceof AgentInboundRequest)) + throw new Error("Wrong request argument"); + if (req.hasResponded()) + return true; + if (req.getType() !== SSH_AGENTC_REQUEST_IDENTITIES) + throw new Error("Invalid response to request"); + if (!Array.isArray(keys)) + throw new Error("Keys argument must be an array"); + let totalKeysLen = 4; + const newKeys = []; + for (let i = 0; i < keys.length; ++i) { + const entry = keys[i]; + if (typeof entry !== "object" || entry === null) + throw new Error(`Invalid key entry: ${entry}`); + let pubKey; + let comment; + if (isParsedKey(entry)) { + pubKey = entry; + } else if (isParsedKey(entry.pubKey)) { + pubKey = entry.pubKey; + } else { + if (typeof entry.pubKey !== "object" || entry.pubKey === null) + continue; + ({ pubKey, comment } = entry.pubKey); + pubKey = parseKey(pubKey); + if (pubKey instanceof Error) + continue; + } + comment = pubKey.comment || comment; + pubKey = pubKey.getPublicSSH(); + totalKeysLen += 4 + pubKey.length; + if (comment && typeof comment === "string") + comment = Buffer.from(comment); + else if (!Buffer.isBuffer(comment)) + comment = EMPTY_BUF; + totalKeysLen += 4 + comment.length; + newKeys.push({ pubKey, comment }); + } + let p = 0; + const buf = Buffer.allocUnsafe(4 + 1 + totalKeysLen); + writeUInt32BE(buf, buf.length - 4, p); + buf[p += 4] = SSH_AGENT_IDENTITIES_ANSWER; + writeUInt32BE(buf, newKeys.length, ++p); + p += 4; + for (let i = 0; i < newKeys.length; ++i) { + const { pubKey, comment } = newKeys[i]; + writeUInt32BE(buf, pubKey.length, p); + pubKey.copy(buf, p += 4); + writeUInt32BE(buf, comment.length, p += pubKey.length); + p += 4; + if (comment.length) { + comment.copy(buf, p); + p += comment.length; + } + } + return respond(this, req, buf); + } + signReply(req, signature) { + if (this[SYM_MODE] !== ROLE_SERVER) + throw new Error("Server-only method called with client role"); + if (!(req instanceof AgentInboundRequest)) + throw new Error("Wrong request argument"); + if (req.hasResponded()) + return true; + if (req.getType() !== SSH_AGENTC_SIGN_REQUEST) + throw new Error("Invalid response to request"); + if (!Buffer.isBuffer(signature)) + throw new Error("Signature argument must be a Buffer"); + if (signature.length === 0) + throw new Error("Signature argument must be non-empty"); + let p = 0; + const sigFormat = req.getContext(); + const sigFormatLen = Buffer.byteLength(sigFormat); + const buf = Buffer.allocUnsafe( + 4 + 1 + 4 + 4 + sigFormatLen + 4 + signature.length + ); + writeUInt32BE(buf, buf.length - 4, p); + buf[p += 4] = SSH_AGENT_SIGN_RESPONSE; + writeUInt32BE(buf, 4 + sigFormatLen + 4 + signature.length, ++p); + writeUInt32BE(buf, sigFormatLen, p += 4); + buf.utf8Write(sigFormat, p += 4, sigFormatLen); + writeUInt32BE(buf, signature.length, p += sigFormatLen); + signature.copy(buf, p += 4); + return respond(this, req, buf); + } + }; + })(); + var SYM_AGENT = /* @__PURE__ */ Symbol("Agent"); + var SYM_AGENT_KEYS = /* @__PURE__ */ Symbol("Agent Keys"); + var SYM_AGENT_KEYS_IDX = /* @__PURE__ */ Symbol("Agent Keys Index"); + var SYM_AGENT_CBS = /* @__PURE__ */ Symbol("Agent Init Callbacks"); + var AgentContext = class { + constructor(agent) { + if (typeof agent === "string") + agent = createAgent(agent); + else if (!isAgent(agent)) + throw new Error("Invalid agent argument"); + this[SYM_AGENT] = agent; + this[SYM_AGENT_KEYS] = null; + this[SYM_AGENT_KEYS_IDX] = -1; + this[SYM_AGENT_CBS] = null; + } + init(cb) { + if (typeof cb !== "function") + cb = noop3; + if (this[SYM_AGENT_KEYS] === null) { + if (this[SYM_AGENT_CBS] === null) { + this[SYM_AGENT_CBS] = [cb]; + const doCbs = (...args) => { + process.nextTick(() => { + const cbs = this[SYM_AGENT_CBS]; + this[SYM_AGENT_CBS] = null; + for (const cb2 of cbs) + cb2(...args); + }); + }; + this[SYM_AGENT].getIdentities(once((err, keys) => { + if (err) + return doCbs(err); + if (!Array.isArray(keys)) { + return doCbs(new Error( + "Agent implementation failed to provide keys" + )); + } + const newKeys = []; + for (let key of keys) { + key = parseKey(key); + if (key instanceof Error) { + continue; + } + newKeys.push(key); + } + this[SYM_AGENT_KEYS] = newKeys; + this[SYM_AGENT_KEYS_IDX] = -1; + doCbs(); + })); + } else { + this[SYM_AGENT_CBS].push(cb); + } + } else { + process.nextTick(cb); + } + } + nextKey() { + if (this[SYM_AGENT_KEYS] === null || ++this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { + return false; + } + return this[SYM_AGENT_KEYS][this[SYM_AGENT_KEYS_IDX]]; + } + currentKey() { + if (this[SYM_AGENT_KEYS] === null || this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { + return null; + } + return this[SYM_AGENT_KEYS][this[SYM_AGENT_KEYS_IDX]]; + } + pos() { + if (this[SYM_AGENT_KEYS] === null || this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { + return -1; + } + return this[SYM_AGENT_KEYS_IDX]; + } + reset() { + this[SYM_AGENT_KEYS_IDX] = -1; + } + sign(...args) { + this[SYM_AGENT].sign(...args); + } + }; + function isAgent(val) { + return val instanceof BaseAgent; + } + module2.exports = { + AgentContext, + AgentProtocol, + BaseAgent, + createAgent, + CygwinAgent, + isAgent, + OpenSSHAgent, + PageantAgent + }; + } +}); + +// node_modules/ssh2/lib/protocol/zlib.js +var require_zlib = __commonJS({ + "node_modules/ssh2/lib/protocol/zlib.js"(exports2, module2) { + "use strict"; + var { kMaxLength } = require("buffer"); + var { + createInflate, + constants: { + DEFLATE, + INFLATE, + Z_DEFAULT_CHUNK, + Z_DEFAULT_COMPRESSION, + Z_DEFAULT_MEMLEVEL, + Z_DEFAULT_STRATEGY, + Z_DEFAULT_WINDOWBITS, + Z_PARTIAL_FLUSH + } + } = require("zlib"); + var ZlibHandle = createInflate()._handle.constructor; + function processCallback() { + throw new Error("Should not get here"); + } + function zlibOnError(message, errno, code) { + const self2 = this._owner; + const error2 = new Error(message); + error2.errno = errno; + error2.code = code; + self2._err = error2; + } + function _close(engine) { + if (!engine._handle) + return; + engine._handle.close(); + engine._handle = null; + } + var Zlib = class { + constructor(mode) { + const windowBits = Z_DEFAULT_WINDOWBITS; + const level = Z_DEFAULT_COMPRESSION; + const memLevel = Z_DEFAULT_MEMLEVEL; + const strategy = Z_DEFAULT_STRATEGY; + const dictionary = void 0; + this._err = void 0; + this._writeState = new Uint32Array(2); + this._chunkSize = Z_DEFAULT_CHUNK; + this._maxOutputLength = kMaxLength; + this._outBuffer = Buffer.allocUnsafe(this._chunkSize); + this._outOffset = 0; + this._handle = new ZlibHandle(mode); + this._handle._owner = this; + this._handle.onerror = zlibOnError; + this._handle.init( + windowBits, + level, + memLevel, + strategy, + this._writeState, + processCallback, + dictionary + ); + } + writeSync(chunk, retChunks) { + const handle = this._handle; + if (!handle) + throw new Error("Invalid Zlib instance"); + let availInBefore = chunk.length; + let availOutBefore = this._chunkSize - this._outOffset; + let inOff = 0; + let availOutAfter; + let availInAfter; + let buffers; + let nread = 0; + const state = this._writeState; + let buffer = this._outBuffer; + let offset = this._outOffset; + const chunkSize = this._chunkSize; + while (true) { + handle.writeSync( + Z_PARTIAL_FLUSH, + chunk, + // in + inOff, + // in_off + availInBefore, + // in_len + buffer, + // out + offset, + // out_off + availOutBefore + ); + if (this._err) + throw this._err; + availOutAfter = state[0]; + availInAfter = state[1]; + const inDelta = availInBefore - availInAfter; + const have = availOutBefore - availOutAfter; + if (have > 0) { + const out = offset === 0 && have === buffer.length ? buffer : buffer.slice(offset, offset + have); + offset += have; + if (!buffers) + buffers = out; + else if (buffers.push === void 0) + buffers = [buffers, out]; + else + buffers.push(out); + nread += out.byteLength; + if (nread > this._maxOutputLength) { + _close(this); + throw new Error( + `Output length exceeded maximum of ${this._maxOutputLength}` + ); + } + } else if (have !== 0) { + throw new Error("have should not go down"); + } + if (availOutAfter === 0 || offset >= chunkSize) { + availOutBefore = chunkSize; + offset = 0; + buffer = Buffer.allocUnsafe(chunkSize); + } + if (availOutAfter === 0) { + inOff += inDelta; + availInBefore = availInAfter; + } else { + break; + } + } + this._outBuffer = buffer; + this._outOffset = offset; + if (nread === 0) + buffers = Buffer.alloc(0); + if (retChunks) { + buffers.totalLen = nread; + return buffers; + } + if (buffers.push === void 0) + return buffers; + const output = Buffer.allocUnsafe(nread); + for (let i = 0, p = 0; i < buffers.length; ++i) { + const buf = buffers[i]; + output.set(buf, p); + p += buf.length; + } + return output; + } + }; + var ZlibPacketWriter = class { + constructor(protocol) { + this.allocStart = 0; + this.allocStartKEX = 0; + this._protocol = protocol; + this._zlib = new Zlib(DEFLATE); + } + cleanup() { + if (this._zlib) + _close(this._zlib); + } + alloc(payloadSize, force) { + return Buffer.allocUnsafe(payloadSize); + } + finalize(payload, force) { + if (this._protocol._kexinit === void 0 || force) { + const output = this._zlib.writeSync(payload, true); + const packet = this._protocol._cipher.allocPacket(output.totalLen); + if (output.push === void 0) { + packet.set(output, 5); + } else { + for (let i = 0, p = 5; i < output.length; ++i) { + const chunk = output[i]; + packet.set(chunk, p); + p += chunk.length; + } + } + return packet; + } + return payload; + } + }; + var PacketWriter = class { + constructor(protocol) { + this.allocStart = 5; + this.allocStartKEX = 5; + this._protocol = protocol; + } + cleanup() { + } + alloc(payloadSize, force) { + if (this._protocol._kexinit === void 0 || force) + return this._protocol._cipher.allocPacket(payloadSize); + return Buffer.allocUnsafe(payloadSize); + } + finalize(packet, force) { + return packet; + } + }; + var ZlibPacketReader = class { + constructor() { + this._zlib = new Zlib(INFLATE); + } + cleanup() { + if (this._zlib) + _close(this._zlib); + } + read(data) { + return this._zlib.writeSync(data, false); + } + }; + var PacketReader = class { + cleanup() { + } + read(data) { + return data; + } + }; + module2.exports = { + PacketReader, + PacketWriter, + ZlibPacketReader, + ZlibPacketWriter + }; + } +}); + +// node_modules/ssh2/lib/protocol/handlers.misc.js +var require_handlers_misc = __commonJS({ + "node_modules/ssh2/lib/protocol/handlers.misc.js"(exports2, module2) { + "use strict"; + var { + bufferSlice, + bufferParser, + doFatalError, + sigSSHToASN1, + writeUInt32BE + } = require_utils3(); + var { + CHANNEL_OPEN_FAILURE, + COMPAT, + MESSAGE, + TERMINAL_MODE + } = require_constants6(); + var { + parseKey + } = require_keyParser(); + var TERMINAL_MODE_BY_VALUE = Array.from(Object.entries(TERMINAL_MODE)).reduce((obj, [key, value]) => ({ ...obj, [key]: value }), {}); + module2.exports = { + // Transport layer protocol ================================================== + [MESSAGE.DISCONNECT]: (self2, payload) => { + bufferParser.init(payload, 1); + const reason = bufferParser.readUInt32BE(); + const desc = bufferParser.readString(true); + const lang = bufferParser.readString(); + bufferParser.clear(); + if (lang === void 0) { + return doFatalError( + self2, + "Inbound: Malformed DISCONNECT packet" + ); + } + self2._debug && self2._debug( + `Inbound: Received DISCONNECT (${reason}, "${desc}")` + ); + const handler2 = self2._handlers.DISCONNECT; + handler2 && handler2(self2, reason, desc); + }, + [MESSAGE.IGNORE]: (self2, payload) => { + self2._debug && self2._debug("Inbound: Received IGNORE"); + }, + [MESSAGE.UNIMPLEMENTED]: (self2, payload) => { + bufferParser.init(payload, 1); + const seqno = bufferParser.readUInt32BE(); + bufferParser.clear(); + if (seqno === void 0) { + return doFatalError( + self2, + "Inbound: Malformed UNIMPLEMENTED packet" + ); + } + self2._debug && self2._debug(`Inbound: Received UNIMPLEMENTED (seqno ${seqno})`); + }, + [MESSAGE.DEBUG]: (self2, payload) => { + bufferParser.init(payload, 1); + const display = bufferParser.readBool(); + const msg = bufferParser.readString(true); + const lang = bufferParser.readString(); + bufferParser.clear(); + if (lang === void 0) { + return doFatalError( + self2, + "Inbound: Malformed DEBUG packet" + ); + } + self2._debug && self2._debug("Inbound: Received DEBUG"); + const handler2 = self2._handlers.DEBUG; + handler2 && handler2(self2, display, msg); + }, + [MESSAGE.SERVICE_REQUEST]: (self2, payload) => { + bufferParser.init(payload, 1); + const name = bufferParser.readString(true); + bufferParser.clear(); + if (name === void 0) { + return doFatalError( + self2, + "Inbound: Malformed SERVICE_REQUEST packet" + ); + } + self2._debug && self2._debug(`Inbound: Received SERVICE_REQUEST (${name})`); + const handler2 = self2._handlers.SERVICE_REQUEST; + handler2 && handler2(self2, name); + }, + [MESSAGE.SERVICE_ACCEPT]: (self2, payload) => { + bufferParser.init(payload, 1); + const name = bufferParser.readString(true); + bufferParser.clear(); + if (name === void 0) { + return doFatalError( + self2, + "Inbound: Malformed SERVICE_ACCEPT packet" + ); + } + self2._debug && self2._debug(`Inbound: Received SERVICE_ACCEPT (${name})`); + const handler2 = self2._handlers.SERVICE_ACCEPT; + handler2 && handler2(self2, name); + }, + [MESSAGE.EXT_INFO]: (self2, payload) => { + bufferParser.init(payload, 1); + const numExts = bufferParser.readUInt32BE(); + let exts; + if (numExts !== void 0) { + exts = []; + for (let i = 0; i < numExts; ++i) { + const name = bufferParser.readString(true); + const data = bufferParser.readString(); + if (data !== void 0) { + switch (name) { + case "server-sig-algs": { + const algs = data.latin1Slice(0, data.length).split(","); + exts.push({ name, algs }); + continue; + } + default: + continue; + } + } + exts = void 0; + break; + } + } + bufferParser.clear(); + if (exts === void 0) + return doFatalError(self2, "Inbound: Malformed EXT_INFO packet"); + self2._debug && self2._debug("Inbound: Received EXT_INFO"); + const handler2 = self2._handlers.EXT_INFO; + handler2 && handler2(self2, exts); + }, + // User auth protocol -- generic ============================================= + [MESSAGE.USERAUTH_REQUEST]: (self2, payload) => { + bufferParser.init(payload, 1); + const user = bufferParser.readString(true); + const service = bufferParser.readString(true); + const method = bufferParser.readString(true); + let methodData; + let methodDesc; + switch (method) { + case "none": + methodData = null; + break; + case "password": { + const isChange = bufferParser.readBool(); + if (isChange !== void 0) { + methodData = bufferParser.readString(true); + if (methodData !== void 0 && isChange) { + const newPassword = bufferParser.readString(true); + if (newPassword !== void 0) + methodData = { oldPassword: methodData, newPassword }; + else + methodData = void 0; + } + } + break; + } + case "publickey": { + const hasSig = bufferParser.readBool(); + if (hasSig !== void 0) { + const keyAlgo = bufferParser.readString(true); + let realKeyAlgo = keyAlgo; + const key = bufferParser.readString(); + let hashAlgo; + switch (keyAlgo) { + case "rsa-sha2-256": + realKeyAlgo = "ssh-rsa"; + hashAlgo = "sha256"; + break; + case "rsa-sha2-512": + realKeyAlgo = "ssh-rsa"; + hashAlgo = "sha512"; + break; + } + if (hasSig) { + const blobEnd = bufferParser.pos(); + let signature = bufferParser.readString(); + if (signature !== void 0) { + if (signature.length > 4 + keyAlgo.length + 4 && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) { + signature = bufferSlice(signature, 4 + keyAlgo.length + 4); + } + signature = sigSSHToASN1(signature, realKeyAlgo); + if (signature) { + const sessionID = self2._kex.sessionID; + const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd); + writeUInt32BE(blob, sessionID.length, 0); + blob.set(sessionID, 4); + blob.set( + new Uint8Array(payload.buffer, payload.byteOffset, blobEnd), + 4 + sessionID.length + ); + methodData = { + keyAlgo: realKeyAlgo, + key, + signature, + blob, + hashAlgo + }; + } + } + } else { + methodData = { keyAlgo: realKeyAlgo, key, hashAlgo }; + methodDesc = "publickey -- check"; + } + } + break; + } + case "hostbased": { + const keyAlgo = bufferParser.readString(true); + let realKeyAlgo = keyAlgo; + const key = bufferParser.readString(); + const localHostname = bufferParser.readString(true); + const localUsername = bufferParser.readString(true); + let hashAlgo; + switch (keyAlgo) { + case "rsa-sha2-256": + realKeyAlgo = "ssh-rsa"; + hashAlgo = "sha256"; + break; + case "rsa-sha2-512": + realKeyAlgo = "ssh-rsa"; + hashAlgo = "sha512"; + break; + } + const blobEnd = bufferParser.pos(); + let signature = bufferParser.readString(); + if (signature !== void 0) { + if (signature.length > 4 + keyAlgo.length + 4 && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) { + signature = bufferSlice(signature, 4 + keyAlgo.length + 4); + } + signature = sigSSHToASN1(signature, realKeyAlgo); + if (signature !== void 0) { + const sessionID = self2._kex.sessionID; + const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd); + writeUInt32BE(blob, sessionID.length, 0); + blob.set(sessionID, 4); + blob.set( + new Uint8Array(payload.buffer, payload.byteOffset, blobEnd), + 4 + sessionID.length + ); + methodData = { + keyAlgo: realKeyAlgo, + key, + signature, + blob, + localHostname, + localUsername, + hashAlgo + }; + } + } + break; + } + case "keyboard-interactive": + bufferParser.skipString(); + methodData = bufferParser.readList(); + break; + default: + if (method !== void 0) + methodData = bufferParser.readRaw(); + } + bufferParser.clear(); + if (methodData === void 0) { + return doFatalError( + self2, + "Inbound: Malformed USERAUTH_REQUEST packet" + ); + } + if (methodDesc === void 0) + methodDesc = method; + self2._authsQueue.push(method); + self2._debug && self2._debug(`Inbound: Received USERAUTH_REQUEST (${methodDesc})`); + const handler2 = self2._handlers.USERAUTH_REQUEST; + handler2 && handler2(self2, user, service, method, methodData); + }, + [MESSAGE.USERAUTH_FAILURE]: (self2, payload) => { + bufferParser.init(payload, 1); + const authMethods = bufferParser.readList(); + const partialSuccess = bufferParser.readBool(); + bufferParser.clear(); + if (partialSuccess === void 0) { + return doFatalError( + self2, + "Inbound: Malformed USERAUTH_FAILURE packet" + ); + } + self2._debug && self2._debug(`Inbound: Received USERAUTH_FAILURE (${authMethods})`); + self2._authsQueue.shift(); + const handler2 = self2._handlers.USERAUTH_FAILURE; + handler2 && handler2(self2, authMethods, partialSuccess); + }, + [MESSAGE.USERAUTH_SUCCESS]: (self2, payload) => { + self2._debug && self2._debug("Inbound: Received USERAUTH_SUCCESS"); + self2._authsQueue.shift(); + const handler2 = self2._handlers.USERAUTH_SUCCESS; + handler2 && handler2(self2); + }, + [MESSAGE.USERAUTH_BANNER]: (self2, payload) => { + bufferParser.init(payload, 1); + const msg = bufferParser.readString(true); + const lang = bufferParser.readString(); + bufferParser.clear(); + if (lang === void 0) { + return doFatalError( + self2, + "Inbound: Malformed USERAUTH_BANNER packet" + ); + } + self2._debug && self2._debug("Inbound: Received USERAUTH_BANNER"); + const handler2 = self2._handlers.USERAUTH_BANNER; + handler2 && handler2(self2, msg); + }, + // User auth protocol -- method-specific ===================================== + 60: (self2, payload) => { + if (!self2._authsQueue.length) { + self2._debug && self2._debug("Inbound: Received payload type 60 without auth"); + return; + } + switch (self2._authsQueue[0]) { + case "password": { + bufferParser.init(payload, 1); + const prompt = bufferParser.readString(true); + const lang = bufferParser.readString(); + bufferParser.clear(); + if (lang === void 0) { + return doFatalError( + self2, + "Inbound: Malformed USERAUTH_PASSWD_CHANGEREQ packet" + ); + } + self2._debug && self2._debug("Inbound: Received USERAUTH_PASSWD_CHANGEREQ"); + const handler2 = self2._handlers.USERAUTH_PASSWD_CHANGEREQ; + handler2 && handler2(self2, prompt); + break; + } + case "publickey": { + bufferParser.init(payload, 1); + const keyAlgo = bufferParser.readString(true); + const key = bufferParser.readString(); + bufferParser.clear(); + if (key === void 0) { + return doFatalError( + self2, + "Inbound: Malformed USERAUTH_PK_OK packet" + ); + } + self2._debug && self2._debug("Inbound: Received USERAUTH_PK_OK"); + self2._authsQueue.shift(); + const handler2 = self2._handlers.USERAUTH_PK_OK; + handler2 && handler2(self2, keyAlgo, key); + break; + } + case "keyboard-interactive": { + bufferParser.init(payload, 1); + const name = bufferParser.readString(true); + const instructions = bufferParser.readString(true); + bufferParser.readString(); + const numPrompts = bufferParser.readUInt32BE(); + let prompts; + if (numPrompts !== void 0) { + prompts = new Array(numPrompts); + let i; + for (i = 0; i < numPrompts; ++i) { + const prompt = bufferParser.readString(true); + const echo = bufferParser.readBool(); + if (echo === void 0) + break; + prompts[i] = { prompt, echo }; + } + if (i !== numPrompts) + prompts = void 0; + } + bufferParser.clear(); + if (prompts === void 0) { + return doFatalError( + self2, + "Inbound: Malformed USERAUTH_INFO_REQUEST packet" + ); + } + self2._debug && self2._debug("Inbound: Received USERAUTH_INFO_REQUEST"); + const handler2 = self2._handlers.USERAUTH_INFO_REQUEST; + handler2 && handler2(self2, name, instructions, prompts); + break; + } + default: + self2._debug && self2._debug("Inbound: Received unexpected payload type 60"); + } + }, + 61: (self2, payload) => { + if (!self2._authsQueue.length) { + self2._debug && self2._debug("Inbound: Received payload type 61 without auth"); + return; + } + if (self2._authsQueue[0] !== "keyboard-interactive") { + return doFatalError( + self2, + "Inbound: Received unexpected payload type 61" + ); + } + bufferParser.init(payload, 1); + const numResponses = bufferParser.readUInt32BE(); + let responses; + if (numResponses !== void 0) { + responses = new Array(numResponses); + let i; + for (i = 0; i < numResponses; ++i) { + const response = bufferParser.readString(true); + if (response === void 0) + break; + responses[i] = response; + } + if (i !== numResponses) + responses = void 0; + } + bufferParser.clear(); + if (responses === void 0) { + return doFatalError( + self2, + "Inbound: Malformed USERAUTH_INFO_RESPONSE packet" + ); + } + self2._debug && self2._debug("Inbound: Received USERAUTH_INFO_RESPONSE"); + const handler2 = self2._handlers.USERAUTH_INFO_RESPONSE; + handler2 && handler2(self2, responses); + }, + // Connection protocol -- generic ============================================ + [MESSAGE.GLOBAL_REQUEST]: (self2, payload) => { + bufferParser.init(payload, 1); + const name = bufferParser.readString(true); + const wantReply = bufferParser.readBool(); + let data; + if (wantReply !== void 0) { + switch (name) { + case "tcpip-forward": + case "cancel-tcpip-forward": { + const bindAddr = bufferParser.readString(true); + const bindPort = bufferParser.readUInt32BE(); + if (bindPort !== void 0) + data = { bindAddr, bindPort }; + break; + } + case "streamlocal-forward@openssh.com": + case "cancel-streamlocal-forward@openssh.com": { + const socketPath = bufferParser.readString(true); + if (socketPath !== void 0) + data = { socketPath }; + break; + } + case "no-more-sessions@openssh.com": + data = null; + break; + case "hostkeys-00@openssh.com": { + data = []; + while (bufferParser.avail() > 0) { + const keyRaw = bufferParser.readString(); + if (keyRaw === void 0) { + data = void 0; + break; + } + const key = parseKey(keyRaw); + if (!(key instanceof Error)) + data.push(key); + } + break; + } + default: + data = bufferParser.readRaw(); + } + } + bufferParser.clear(); + if (data === void 0) { + return doFatalError( + self2, + "Inbound: Malformed GLOBAL_REQUEST packet" + ); + } + self2._debug && self2._debug(`Inbound: GLOBAL_REQUEST (${name})`); + const handler2 = self2._handlers.GLOBAL_REQUEST; + if (handler2) + handler2(self2, name, wantReply, data); + else + self2.requestFailure(); + }, + [MESSAGE.REQUEST_SUCCESS]: (self2, payload) => { + const data = payload.length > 1 ? bufferSlice(payload, 1) : null; + self2._debug && self2._debug("Inbound: REQUEST_SUCCESS"); + const handler2 = self2._handlers.REQUEST_SUCCESS; + handler2 && handler2(self2, data); + }, + [MESSAGE.REQUEST_FAILURE]: (self2, payload) => { + self2._debug && self2._debug("Inbound: Received REQUEST_FAILURE"); + const handler2 = self2._handlers.REQUEST_FAILURE; + handler2 && handler2(self2); + }, + // Connection protocol -- channel-related ==================================== + [MESSAGE.CHANNEL_OPEN]: (self2, payload) => { + bufferParser.init(payload, 1); + const type = bufferParser.readString(true); + const sender = bufferParser.readUInt32BE(); + const window2 = bufferParser.readUInt32BE(); + const packetSize = bufferParser.readUInt32BE(); + let channelInfo; + switch (type) { + case "forwarded-tcpip": + // S->C + case "direct-tcpip": { + const destIP = bufferParser.readString(true); + const destPort = bufferParser.readUInt32BE(); + const srcIP = bufferParser.readString(true); + const srcPort = bufferParser.readUInt32BE(); + if (srcPort !== void 0) { + channelInfo = { + type, + sender, + window: window2, + packetSize, + data: { destIP, destPort, srcIP, srcPort } + }; + } + break; + } + case "forwarded-streamlocal@openssh.com": + // S->C + case "direct-streamlocal@openssh.com": { + const socketPath = bufferParser.readString(true); + if (socketPath !== void 0) { + channelInfo = { + type, + sender, + window: window2, + packetSize, + data: { socketPath } + }; + } + break; + } + case "x11": { + const srcIP = bufferParser.readString(true); + const srcPort = bufferParser.readUInt32BE(); + if (srcPort !== void 0) { + channelInfo = { + type, + sender, + window: window2, + packetSize, + data: { srcIP, srcPort } + }; + } + break; + } + default: + channelInfo = { + type, + sender, + window: window2, + packetSize, + data: {} + }; + } + bufferParser.clear(); + if (channelInfo === void 0) { + return doFatalError( + self2, + "Inbound: Malformed CHANNEL_OPEN packet" + ); + } + self2._debug && self2._debug(`Inbound: CHANNEL_OPEN (s:${sender}, ${type})`); + const handler2 = self2._handlers.CHANNEL_OPEN; + if (handler2) { + handler2(self2, channelInfo); + } else { + self2.channelOpenFail( + channelInfo.sender, + CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED, + "", + "" + ); + } + }, + [MESSAGE.CHANNEL_OPEN_CONFIRMATION]: (self2, payload) => { + bufferParser.init(payload, 1); + const recipient = bufferParser.readUInt32BE(); + const sender = bufferParser.readUInt32BE(); + const window2 = bufferParser.readUInt32BE(); + const packetSize = bufferParser.readUInt32BE(); + const data = bufferParser.avail() ? bufferParser.readRaw() : void 0; + bufferParser.clear(); + if (packetSize === void 0) { + return doFatalError( + self2, + "Inbound: Malformed CHANNEL_OPEN_CONFIRMATION packet" + ); + } + self2._debug && self2._debug( + `Inbound: CHANNEL_OPEN_CONFIRMATION (r:${recipient}, s:${sender})` + ); + const handler2 = self2._handlers.CHANNEL_OPEN_CONFIRMATION; + if (handler2) + handler2(self2, { recipient, sender, window: window2, packetSize, data }); + }, + [MESSAGE.CHANNEL_OPEN_FAILURE]: (self2, payload) => { + bufferParser.init(payload, 1); + const recipient = bufferParser.readUInt32BE(); + const reason = bufferParser.readUInt32BE(); + const description = bufferParser.readString(true); + const lang = bufferParser.readString(); + bufferParser.clear(); + if (lang === void 0) { + return doFatalError( + self2, + "Inbound: Malformed CHANNEL_OPEN_FAILURE packet" + ); + } + self2._debug && self2._debug(`Inbound: CHANNEL_OPEN_FAILURE (r:${recipient})`); + const handler2 = self2._handlers.CHANNEL_OPEN_FAILURE; + handler2 && handler2(self2, recipient, reason, description); + }, + [MESSAGE.CHANNEL_WINDOW_ADJUST]: (self2, payload) => { + bufferParser.init(payload, 1); + const recipient = bufferParser.readUInt32BE(); + const bytesToAdd = bufferParser.readUInt32BE(); + bufferParser.clear(); + if (bytesToAdd === void 0) { + return doFatalError( + self2, + "Inbound: Malformed CHANNEL_WINDOW_ADJUST packet" + ); + } + self2._debug && self2._debug( + `Inbound: CHANNEL_WINDOW_ADJUST (r:${recipient}, ${bytesToAdd})` + ); + const handler2 = self2._handlers.CHANNEL_WINDOW_ADJUST; + handler2 && handler2(self2, recipient, bytesToAdd); + }, + [MESSAGE.CHANNEL_DATA]: (self2, payload) => { + bufferParser.init(payload, 1); + const recipient = bufferParser.readUInt32BE(); + const data = bufferParser.readString(); + bufferParser.clear(); + if (data === void 0) { + return doFatalError( + self2, + "Inbound: Malformed CHANNEL_DATA packet" + ); + } + self2._debug && self2._debug(`Inbound: CHANNEL_DATA (r:${recipient}, ${data.length})`); + const handler2 = self2._handlers.CHANNEL_DATA; + handler2 && handler2(self2, recipient, data); + }, + [MESSAGE.CHANNEL_EXTENDED_DATA]: (self2, payload) => { + bufferParser.init(payload, 1); + const recipient = bufferParser.readUInt32BE(); + const type = bufferParser.readUInt32BE(); + const data = bufferParser.readString(); + bufferParser.clear(); + if (data === void 0) { + return doFatalError( + self2, + "Inbound: Malformed CHANNEL_EXTENDED_DATA packet" + ); + } + self2._debug && self2._debug( + `Inbound: CHANNEL_EXTENDED_DATA (r:${recipient}, ${data.length})` + ); + const handler2 = self2._handlers.CHANNEL_EXTENDED_DATA; + handler2 && handler2(self2, recipient, data, type); + }, + [MESSAGE.CHANNEL_EOF]: (self2, payload) => { + bufferParser.init(payload, 1); + const recipient = bufferParser.readUInt32BE(); + bufferParser.clear(); + if (recipient === void 0) { + return doFatalError( + self2, + "Inbound: Malformed CHANNEL_EOF packet" + ); + } + self2._debug && self2._debug(`Inbound: CHANNEL_EOF (r:${recipient})`); + const handler2 = self2._handlers.CHANNEL_EOF; + handler2 && handler2(self2, recipient); + }, + [MESSAGE.CHANNEL_CLOSE]: (self2, payload) => { + bufferParser.init(payload, 1); + const recipient = bufferParser.readUInt32BE(); + bufferParser.clear(); + if (recipient === void 0) { + return doFatalError( + self2, + "Inbound: Malformed CHANNEL_CLOSE packet" + ); + } + self2._debug && self2._debug(`Inbound: CHANNEL_CLOSE (r:${recipient})`); + const handler2 = self2._handlers.CHANNEL_CLOSE; + handler2 && handler2(self2, recipient); + }, + [MESSAGE.CHANNEL_REQUEST]: (self2, payload) => { + bufferParser.init(payload, 1); + const recipient = bufferParser.readUInt32BE(); + const type = bufferParser.readString(true); + const wantReply = bufferParser.readBool(); + let data; + if (wantReply !== void 0) { + switch (type) { + case "exit-status": + data = bufferParser.readUInt32BE(); + self2._debug && self2._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` + ); + break; + case "exit-signal": { + let signal; + let coreDumped; + if (self2._compatFlags & COMPAT.OLD_EXIT) { + const num = bufferParser.readUInt32BE(); + switch (num) { + case 1: + signal = "HUP"; + break; + case 2: + signal = "INT"; + break; + case 3: + signal = "QUIT"; + break; + case 6: + signal = "ABRT"; + break; + case 9: + signal = "KILL"; + break; + case 14: + signal = "ALRM"; + break; + case 15: + signal = "TERM"; + break; + default: + if (num !== void 0) { + signal = `UNKNOWN (${num})`; + } + } + coreDumped = false; + } else { + signal = bufferParser.readString(true); + coreDumped = bufferParser.readBool(); + if (coreDumped === void 0) + signal = void 0; + } + const errorMessage = bufferParser.readString(true); + if (bufferParser.skipString() !== void 0) + data = { signal, coreDumped, errorMessage }; + self2._debug && self2._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${signal})` + ); + break; + } + case "pty-req": { + const term = bufferParser.readString(true); + const cols = bufferParser.readUInt32BE(); + const rows = bufferParser.readUInt32BE(); + const width = bufferParser.readUInt32BE(); + const height = bufferParser.readUInt32BE(); + const modesBinary = bufferParser.readString(); + if (modesBinary !== void 0) { + bufferParser.init(modesBinary, 1); + let modes = {}; + while (bufferParser.avail()) { + const opcode = bufferParser.readByte(); + if (opcode === TERMINAL_MODE.TTY_OP_END) + break; + const name = TERMINAL_MODE_BY_VALUE[opcode]; + const value = bufferParser.readUInt32BE(); + if (opcode === void 0 || name === void 0 || value === void 0) { + modes = void 0; + break; + } + modes[name] = value; + } + if (modes !== void 0) + data = { term, cols, rows, width, height, modes }; + } + self2._debug && self2._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` + ); + break; + } + case "window-change": { + const cols = bufferParser.readUInt32BE(); + const rows = bufferParser.readUInt32BE(); + const width = bufferParser.readUInt32BE(); + const height = bufferParser.readUInt32BE(); + if (height !== void 0) + data = { cols, rows, width, height }; + self2._debug && self2._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` + ); + break; + } + case "x11-req": { + const single = bufferParser.readBool(); + const protocol = bufferParser.readString(true); + const cookie = bufferParser.readString(); + const screen = bufferParser.readUInt32BE(); + if (screen !== void 0) + data = { single, protocol, cookie, screen }; + self2._debug && self2._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` + ); + break; + } + case "env": { + const name = bufferParser.readString(true); + const value = bufferParser.readString(true); + if (value !== void 0) + data = { name, value }; + if (self2._debug) { + self2._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${name}=${value})` + ); + } + break; + } + case "shell": + data = null; + self2._debug && self2._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` + ); + break; + case "exec": + data = bufferParser.readString(true); + self2._debug && self2._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` + ); + break; + case "subsystem": + data = bufferParser.readString(true); + self2._debug && self2._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` + ); + break; + case "signal": + data = bufferParser.readString(true); + self2._debug && self2._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` + ); + break; + case "xon-xoff": + data = bufferParser.readBool(); + self2._debug && self2._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` + ); + break; + case "auth-agent-req@openssh.com": + data = null; + self2._debug && self2._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` + ); + break; + default: + data = bufferParser.avail() ? bufferParser.readRaw() : null; + self2._debug && self2._debug( + `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` + ); + } + } + bufferParser.clear(); + if (data === void 0) { + return doFatalError( + self2, + "Inbound: Malformed CHANNEL_REQUEST packet" + ); + } + const handler2 = self2._handlers.CHANNEL_REQUEST; + handler2 && handler2(self2, recipient, type, wantReply, data); + }, + [MESSAGE.CHANNEL_SUCCESS]: (self2, payload) => { + bufferParser.init(payload, 1); + const recipient = bufferParser.readUInt32BE(); + bufferParser.clear(); + if (recipient === void 0) { + return doFatalError( + self2, + "Inbound: Malformed CHANNEL_SUCCESS packet" + ); + } + self2._debug && self2._debug(`Inbound: CHANNEL_SUCCESS (r:${recipient})`); + const handler2 = self2._handlers.CHANNEL_SUCCESS; + handler2 && handler2(self2, recipient); + }, + [MESSAGE.CHANNEL_FAILURE]: (self2, payload) => { + bufferParser.init(payload, 1); + const recipient = bufferParser.readUInt32BE(); + bufferParser.clear(); + if (recipient === void 0) { + return doFatalError( + self2, + "Inbound: Malformed CHANNEL_FAILURE packet" + ); + } + self2._debug && self2._debug(`Inbound: CHANNEL_FAILURE (r:${recipient})`); + const handler2 = self2._handlers.CHANNEL_FAILURE; + handler2 && handler2(self2, recipient); + } + }; + } +}); + +// node_modules/ssh2/lib/protocol/handlers.js +var require_handlers = __commonJS({ + "node_modules/ssh2/lib/protocol/handlers.js"(exports2, module2) { + "use strict"; + var MESSAGE_HANDLERS = new Array(256); + [ + require_kex().HANDLERS, + require_handlers_misc() + ].forEach((handlers) => { + for (let [type, handler2] of Object.entries(handlers)) { + type = +type; + if (isFinite(type) && type >= 0 && type < MESSAGE_HANDLERS.length) + MESSAGE_HANDLERS[type] = handler2; + } + }); + module2.exports = MESSAGE_HANDLERS; + } +}); + +// node_modules/ssh2/lib/protocol/kex.js +var require_kex = __commonJS({ + "node_modules/ssh2/lib/protocol/kex.js"(exports2, module2) { + "use strict"; + var { + createDiffieHellman, + createDiffieHellmanGroup, + createECDH, + createHash, + createPublicKey, + diffieHellman, + generateKeyPairSync, + randomFillSync + } = require("crypto"); + var { Ber } = require_lib2(); + var { + COMPAT, + curve25519Supported, + DEFAULT_KEX, + DEFAULT_SERVER_HOST_KEY, + DEFAULT_CIPHER, + DEFAULT_MAC, + DEFAULT_COMPRESSION, + DISCONNECT_REASON, + MESSAGE + } = require_constants6(); + var { + CIPHER_INFO, + createCipher, + createDecipher, + MAC_INFO + } = require_crypto(); + var { parseDERKey } = require_keyParser(); + var { + bufferFill, + bufferParser, + convertSignature, + doFatalError, + FastBuffer, + sigSSHToASN1, + writeUInt32BE + } = require_utils3(); + var { + PacketReader, + PacketWriter, + ZlibPacketReader, + ZlibPacketWriter + } = require_zlib(); + var MESSAGE_HANDLERS; + var GEX_MIN_BITS = 2048; + var GEX_MAX_BITS = 8192; + var EMPTY_BUFFER = Buffer.alloc(0); + function kexinit(self2) { + let payload; + if (self2._compatFlags & COMPAT.BAD_DHGEX) { + const entry = self2._offer.lists.kex; + let kex = entry.array; + let found = false; + for (let i = 0; i < kex.length; ++i) { + if (kex[i].includes("group-exchange")) { + if (!found) { + found = true; + kex = kex.slice(); + } + kex.splice(i--, 1); + } + } + if (found) { + let len = 1 + 16 + self2._offer.totalSize + 1 + 4; + const newKexBuf = Buffer.from(kex.join(",")); + len -= entry.buffer.length - newKexBuf.length; + const all = self2._offer.lists.all; + const rest = new Uint8Array( + all.buffer, + all.byteOffset + 4 + entry.buffer.length, + all.length - (4 + entry.buffer.length) + ); + payload = Buffer.allocUnsafe(len); + writeUInt32BE(payload, newKexBuf.length, 17); + payload.set(newKexBuf, 17 + 4); + payload.set(rest, 17 + 4 + newKexBuf.length); + } + } + if (payload === void 0) { + payload = Buffer.allocUnsafe(1 + 16 + self2._offer.totalSize + 1 + 4); + self2._offer.copyAllTo(payload, 17); + } + self2._debug && self2._debug("Outbound: Sending KEXINIT"); + payload[0] = MESSAGE.KEXINIT; + randomFillSync(payload, 1, 16); + bufferFill(payload, 0, payload.length - 5); + self2._kexinit = payload; + self2._packetRW.write.allocStart = 0; + { + const p = self2._packetRW.write.allocStartKEX; + const packet = self2._packetRW.write.alloc(payload.length, true); + packet.set(payload, p); + self2._cipher.encrypt(self2._packetRW.write.finalize(packet, true)); + } + } + function handleKexInit(self2, payload) { + const init = { + kex: void 0, + serverHostKey: void 0, + cs: { + cipher: void 0, + mac: void 0, + compress: void 0, + lang: void 0 + }, + sc: { + cipher: void 0, + mac: void 0, + compress: void 0, + lang: void 0 + } + }; + bufferParser.init(payload, 17); + if ((init.kex = bufferParser.readList()) === void 0 || (init.serverHostKey = bufferParser.readList()) === void 0 || (init.cs.cipher = bufferParser.readList()) === void 0 || (init.sc.cipher = bufferParser.readList()) === void 0 || (init.cs.mac = bufferParser.readList()) === void 0 || (init.sc.mac = bufferParser.readList()) === void 0 || (init.cs.compress = bufferParser.readList()) === void 0 || (init.sc.compress = bufferParser.readList()) === void 0 || (init.cs.lang = bufferParser.readList()) === void 0 || (init.sc.lang = bufferParser.readList()) === void 0) { + bufferParser.clear(); + return doFatalError( + self2, + "Received malformed KEXINIT", + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + const pos = bufferParser.pos(); + const firstFollows = pos < payload.length && payload[pos] === 1; + bufferParser.clear(); + const local = self2._offer; + const remote = init; + let localKex = local.lists.kex.array; + if (self2._compatFlags & COMPAT.BAD_DHGEX) { + let found = false; + for (let i2 = 0; i2 < localKex.length; ++i2) { + if (localKex[i2].indexOf("group-exchange") !== -1) { + if (!found) { + found = true; + localKex = localKex.slice(); + } + localKex.splice(i2--, 1); + } + } + } + let clientList; + let serverList; + let i; + const debug2 = self2._debug; + debug2 && debug2("Inbound: Handshake in progress"); + debug2 && debug2(`Handshake: (local) KEX method: ${localKex}`); + debug2 && debug2(`Handshake: (remote) KEX method: ${remote.kex}`); + let remoteExtInfoEnabled; + if (self2._server) { + serverList = localKex; + clientList = remote.kex; + remoteExtInfoEnabled = clientList.indexOf("ext-info-c") !== -1; + } else { + serverList = remote.kex; + clientList = localKex; + remoteExtInfoEnabled = serverList.indexOf("ext-info-s") !== -1; + } + if (self2._strictMode === void 0) { + if (self2._server) { + self2._strictMode = clientList.indexOf("kex-strict-c-v00@openssh.com") !== -1; + } else { + self2._strictMode = serverList.indexOf("kex-strict-s-v00@openssh.com") !== -1; + } + if (self2._strictMode) { + debug2 && debug2("Handshake: strict KEX mode enabled"); + if (self2._decipher.inSeqno !== 1) { + if (debug2) + debug2("Handshake: KEXINIT not first packet in strict KEX mode"); + return doFatalError( + self2, + "Handshake failed: KEXINIT not first packet in strict KEX mode", + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + } + } + for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i) ; + if (i === clientList.length) { + debug2 && debug2("Handshake: no matching key exchange algorithm"); + return doFatalError( + self2, + "Handshake failed: no matching key exchange algorithm", + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + init.kex = clientList[i]; + debug2 && debug2(`Handshake: KEX algorithm: ${clientList[i]}`); + if (firstFollows && (!remote.kex.length || clientList[i] !== remote.kex[0])) { + self2._skipNextInboundPacket = true; + } + const localSrvHostKey = local.lists.serverHostKey.array; + debug2 && debug2(`Handshake: (local) Host key format: ${localSrvHostKey}`); + debug2 && debug2( + `Handshake: (remote) Host key format: ${remote.serverHostKey}` + ); + if (self2._server) { + serverList = localSrvHostKey; + clientList = remote.serverHostKey; + } else { + serverList = remote.serverHostKey; + clientList = localSrvHostKey; + } + for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i) ; + if (i === clientList.length) { + debug2 && debug2("Handshake: No matching host key format"); + return doFatalError( + self2, + "Handshake failed: no matching host key format", + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + init.serverHostKey = clientList[i]; + debug2 && debug2(`Handshake: Host key format: ${clientList[i]}`); + const localCSCipher = local.lists.cs.cipher.array; + debug2 && debug2(`Handshake: (local) C->S cipher: ${localCSCipher}`); + debug2 && debug2(`Handshake: (remote) C->S cipher: ${remote.cs.cipher}`); + if (self2._server) { + serverList = localCSCipher; + clientList = remote.cs.cipher; + } else { + serverList = remote.cs.cipher; + clientList = localCSCipher; + } + for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i) ; + if (i === clientList.length) { + debug2 && debug2("Handshake: No matching C->S cipher"); + return doFatalError( + self2, + "Handshake failed: no matching C->S cipher", + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + init.cs.cipher = clientList[i]; + debug2 && debug2(`Handshake: C->S Cipher: ${clientList[i]}`); + const localSCCipher = local.lists.sc.cipher.array; + debug2 && debug2(`Handshake: (local) S->C cipher: ${localSCCipher}`); + debug2 && debug2(`Handshake: (remote) S->C cipher: ${remote.sc.cipher}`); + if (self2._server) { + serverList = localSCCipher; + clientList = remote.sc.cipher; + } else { + serverList = remote.sc.cipher; + clientList = localSCCipher; + } + for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i) ; + if (i === clientList.length) { + debug2 && debug2("Handshake: No matching S->C cipher"); + return doFatalError( + self2, + "Handshake failed: no matching S->C cipher", + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + init.sc.cipher = clientList[i]; + debug2 && debug2(`Handshake: S->C cipher: ${clientList[i]}`); + const localCSMAC = local.lists.cs.mac.array; + debug2 && debug2(`Handshake: (local) C->S MAC: ${localCSMAC}`); + debug2 && debug2(`Handshake: (remote) C->S MAC: ${remote.cs.mac}`); + if (CIPHER_INFO[init.cs.cipher].authLen > 0) { + init.cs.mac = ""; + debug2 && debug2("Handshake: C->S MAC: "); + } else { + if (self2._server) { + serverList = localCSMAC; + clientList = remote.cs.mac; + } else { + serverList = remote.cs.mac; + clientList = localCSMAC; + } + for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i) ; + if (i === clientList.length) { + debug2 && debug2("Handshake: No matching C->S MAC"); + return doFatalError( + self2, + "Handshake failed: no matching C->S MAC", + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + init.cs.mac = clientList[i]; + debug2 && debug2(`Handshake: C->S MAC: ${clientList[i]}`); + } + const localSCMAC = local.lists.sc.mac.array; + debug2 && debug2(`Handshake: (local) S->C MAC: ${localSCMAC}`); + debug2 && debug2(`Handshake: (remote) S->C MAC: ${remote.sc.mac}`); + if (CIPHER_INFO[init.sc.cipher].authLen > 0) { + init.sc.mac = ""; + debug2 && debug2("Handshake: S->C MAC: "); + } else { + if (self2._server) { + serverList = localSCMAC; + clientList = remote.sc.mac; + } else { + serverList = remote.sc.mac; + clientList = localSCMAC; + } + for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i) ; + if (i === clientList.length) { + debug2 && debug2("Handshake: No matching S->C MAC"); + return doFatalError( + self2, + "Handshake failed: no matching S->C MAC", + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + init.sc.mac = clientList[i]; + debug2 && debug2(`Handshake: S->C MAC: ${clientList[i]}`); + } + const localCSCompress = local.lists.cs.compress.array; + debug2 && debug2(`Handshake: (local) C->S compression: ${localCSCompress}`); + debug2 && debug2(`Handshake: (remote) C->S compression: ${remote.cs.compress}`); + if (self2._server) { + serverList = localCSCompress; + clientList = remote.cs.compress; + } else { + serverList = remote.cs.compress; + clientList = localCSCompress; + } + for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i) ; + if (i === clientList.length) { + debug2 && debug2("Handshake: No matching C->S compression"); + return doFatalError( + self2, + "Handshake failed: no matching C->S compression", + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + init.cs.compress = clientList[i]; + debug2 && debug2(`Handshake: C->S compression: ${clientList[i]}`); + const localSCCompress = local.lists.sc.compress.array; + debug2 && debug2(`Handshake: (local) S->C compression: ${localSCCompress}`); + debug2 && debug2(`Handshake: (remote) S->C compression: ${remote.sc.compress}`); + if (self2._server) { + serverList = localSCCompress; + clientList = remote.sc.compress; + } else { + serverList = remote.sc.compress; + clientList = localSCCompress; + } + for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i) ; + if (i === clientList.length) { + debug2 && debug2("Handshake: No matching S->C compression"); + return doFatalError( + self2, + "Handshake failed: no matching S->C compression", + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + init.sc.compress = clientList[i]; + debug2 && debug2(`Handshake: S->C compression: ${clientList[i]}`); + init.cs.lang = ""; + init.sc.lang = ""; + if (self2._kex) { + if (!self2._kexinit) { + kexinit(self2); + } + self2._decipher._onPayload = onKEXPayload.bind(self2, { firstPacket: false }); + } + self2._kex = createKeyExchange(init, self2, payload); + self2._kex.remoteExtInfoEnabled = remoteExtInfoEnabled; + self2._kex.start(); + } + var createKeyExchange = /* @__PURE__ */ (() => { + function convertToMpint(buf) { + let idx = 0; + let length = buf.length; + while (buf[idx] === 0) { + ++idx; + --length; + } + let newBuf; + if (buf[idx] & 128) { + newBuf = Buffer.allocUnsafe(1 + length); + newBuf[0] = 0; + buf.copy(newBuf, 1, idx); + buf = newBuf; + } else if (length !== buf.length) { + newBuf = Buffer.allocUnsafe(length); + buf.copy(newBuf, 0, idx); + buf = newBuf; + } + return buf; + } + class KeyExchange { + constructor(negotiated, protocol, remoteKexinit) { + this._protocol = protocol; + this.sessionID = protocol._kex ? protocol._kex.sessionID : void 0; + this.negotiated = negotiated; + this.remoteExtInfoEnabled = false; + this._step = 1; + this._public = null; + this._dh = null; + this._sentNEWKEYS = false; + this._receivedNEWKEYS = false; + this._finished = false; + this._hostVerified = false; + this._kexinit = protocol._kexinit; + this._remoteKexinit = remoteKexinit; + this._identRaw = protocol._identRaw; + this._remoteIdentRaw = protocol._remoteIdentRaw; + this._hostKey = void 0; + this._dhData = void 0; + this._sig = void 0; + } + finish(scOnly) { + if (this._finished) + return false; + this._finished = true; + const isServer = this._protocol._server; + const negotiated = this.negotiated; + const pubKey = this.convertPublicKey(this._dhData); + let secret = this.computeSecret(this._dhData); + if (secret instanceof Error) { + secret.message = `Error while computing DH secret (${this.type}): ${secret.message}`; + secret.level = "handshake"; + return doFatalError( + this._protocol, + secret, + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + const hash = createHash(this.hashName); + hashString(hash, isServer ? this._remoteIdentRaw : this._identRaw); + hashString(hash, isServer ? this._identRaw : this._remoteIdentRaw); + hashString(hash, isServer ? this._remoteKexinit : this._kexinit); + hashString(hash, isServer ? this._kexinit : this._remoteKexinit); + const serverPublicHostKey = isServer ? this._hostKey.getPublicSSH() : this._hostKey; + hashString(hash, serverPublicHostKey); + if (this.type === "groupex") { + const params = this.getDHParams(); + const num = Buffer.allocUnsafe(4); + writeUInt32BE(num, this._minBits, 0); + hash.update(num); + writeUInt32BE(num, this._prefBits, 0); + hash.update(num); + writeUInt32BE(num, this._maxBits, 0); + hash.update(num); + hashString(hash, params.prime); + hashString(hash, params.generator); + } + hashString(hash, isServer ? pubKey : this.getPublicKey()); + const serverPublicKey = isServer ? this.getPublicKey() : pubKey; + hashString(hash, serverPublicKey); + hashString(hash, secret); + const exchangeHash = hash.digest(); + if (!isServer) { + bufferParser.init(this._sig, 0); + const sigType = bufferParser.readString(true); + if (!sigType) { + return doFatalError( + this._protocol, + "Malformed packet while reading signature", + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + if (sigType !== negotiated.serverHostKey) { + return doFatalError( + this._protocol, + `Wrong signature type: ${sigType}, expected: ${negotiated.serverHostKey}`, + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + let sigValue = bufferParser.readString(); + bufferParser.clear(); + if (sigValue === void 0) { + return doFatalError( + this._protocol, + "Malformed packet while reading signature", + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + if (!(sigValue = sigSSHToASN1(sigValue, sigType))) { + return doFatalError( + this._protocol, + "Malformed signature", + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + let parsedHostKey; + { + bufferParser.init(this._hostKey, 0); + const name = bufferParser.readString(true); + const hostKey = this._hostKey.slice(bufferParser.pos()); + bufferParser.clear(); + parsedHostKey = parseDERKey(hostKey, name); + if (parsedHostKey instanceof Error) { + parsedHostKey.level = "handshake"; + return doFatalError( + this._protocol, + parsedHostKey, + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + } + let hashAlgo; + switch (this.negotiated.serverHostKey) { + case "rsa-sha2-256": + hashAlgo = "sha256"; + break; + case "rsa-sha2-512": + hashAlgo = "sha512"; + break; + } + this._protocol._debug && this._protocol._debug("Verifying signature ..."); + const verified = parsedHostKey.verify(exchangeHash, sigValue, hashAlgo); + if (verified !== true) { + if (verified instanceof Error) { + this._protocol._debug && this._protocol._debug( + `Signature verification failed: ${verified.stack}` + ); + } else { + this._protocol._debug && this._protocol._debug( + "Signature verification failed" + ); + } + return doFatalError( + this._protocol, + "Handshake failed: signature verification failed", + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + this._protocol._debug && this._protocol._debug("Verified signature"); + } else { + let hashAlgo; + switch (this.negotiated.serverHostKey) { + case "rsa-sha2-256": + hashAlgo = "sha256"; + break; + case "rsa-sha2-512": + hashAlgo = "sha512"; + break; + } + this._protocol._debug && this._protocol._debug( + "Generating signature ..." + ); + let signature = this._hostKey.sign(exchangeHash, hashAlgo); + if (signature instanceof Error) { + return doFatalError( + this._protocol, + `Handshake failed: signature generation failed for ${this._hostKey.type} host key: ${signature.message}`, + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + signature = convertSignature(signature, this._hostKey.type); + if (signature === false) { + return doFatalError( + this._protocol, + `Handshake failed: signature conversion failed for ${this._hostKey.type} host key`, + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + const sigType = this.negotiated.serverHostKey; + const sigTypeLen = Buffer.byteLength(sigType); + const sigLen = 4 + sigTypeLen + 4 + signature.length; + let p = this._protocol._packetRW.write.allocStartKEX; + const packet = this._protocol._packetRW.write.alloc( + 1 + 4 + serverPublicHostKey.length + 4 + serverPublicKey.length + 4 + sigLen, + true + ); + packet[p] = MESSAGE.KEXDH_REPLY; + writeUInt32BE(packet, serverPublicHostKey.length, ++p); + packet.set(serverPublicHostKey, p += 4); + writeUInt32BE( + packet, + serverPublicKey.length, + p += serverPublicHostKey.length + ); + packet.set(serverPublicKey, p += 4); + writeUInt32BE(packet, sigLen, p += serverPublicKey.length); + writeUInt32BE(packet, sigTypeLen, p += 4); + packet.utf8Write(sigType, p += 4, sigTypeLen); + writeUInt32BE(packet, signature.length, p += sigTypeLen); + packet.set(signature, p += 4); + if (this._protocol._debug) { + let type; + switch (this.type) { + case "group": + type = "KEXDH_REPLY"; + break; + case "groupex": + type = "KEXDH_GEX_REPLY"; + break; + default: + type = "KEXECDH_REPLY"; + } + this._protocol._debug(`Outbound: Sending ${type}`); + } + this._protocol._cipher.encrypt( + this._protocol._packetRW.write.finalize(packet, true) + ); + } + if (isServer || !scOnly) + trySendNEWKEYS(this); + let hsCipherConfig; + let hsWrite; + const completeHandshake = (partial) => { + if (hsCipherConfig) { + trySendNEWKEYS(this); + hsCipherConfig.outbound.seqno = this._protocol._cipher.outSeqno; + this._protocol._cipher.free(); + this._protocol._cipher = createCipher(hsCipherConfig); + this._protocol._packetRW.write = hsWrite; + hsCipherConfig = void 0; + hsWrite = void 0; + this._protocol._onHandshakeComplete(negotiated); + return false; + } + if (!this.sessionID) + this.sessionID = exchangeHash; + { + const newSecret = Buffer.allocUnsafe(4 + secret.length); + writeUInt32BE(newSecret, secret.length, 0); + newSecret.set(secret, 4); + secret = newSecret; + } + const csCipherInfo = CIPHER_INFO[negotiated.cs.cipher]; + const scCipherInfo = CIPHER_INFO[negotiated.sc.cipher]; + const csIV = generateKEXVal( + csCipherInfo.ivLen, + this.hashName, + secret, + exchangeHash, + this.sessionID, + "A" + ); + const scIV = generateKEXVal( + scCipherInfo.ivLen, + this.hashName, + secret, + exchangeHash, + this.sessionID, + "B" + ); + const csKey = generateKEXVal( + csCipherInfo.keyLen, + this.hashName, + secret, + exchangeHash, + this.sessionID, + "C" + ); + const scKey = generateKEXVal( + scCipherInfo.keyLen, + this.hashName, + secret, + exchangeHash, + this.sessionID, + "D" + ); + let csMacInfo; + let csMacKey; + if (!csCipherInfo.authLen) { + csMacInfo = MAC_INFO[negotiated.cs.mac]; + csMacKey = generateKEXVal( + csMacInfo.len, + this.hashName, + secret, + exchangeHash, + this.sessionID, + "E" + ); + } + let scMacInfo; + let scMacKey; + if (!scCipherInfo.authLen) { + scMacInfo = MAC_INFO[negotiated.sc.mac]; + scMacKey = generateKEXVal( + scMacInfo.len, + this.hashName, + secret, + exchangeHash, + this.sessionID, + "F" + ); + } + const config = { + inbound: { + onPayload: this._protocol._onPayload, + seqno: this._protocol._decipher.inSeqno, + decipherInfo: !isServer ? scCipherInfo : csCipherInfo, + decipherIV: !isServer ? scIV : csIV, + decipherKey: !isServer ? scKey : csKey, + macInfo: !isServer ? scMacInfo : csMacInfo, + macKey: !isServer ? scMacKey : csMacKey + }, + outbound: { + onWrite: this._protocol._onWrite, + seqno: this._protocol._cipher.outSeqno, + cipherInfo: isServer ? scCipherInfo : csCipherInfo, + cipherIV: isServer ? scIV : csIV, + cipherKey: isServer ? scKey : csKey, + macInfo: isServer ? scMacInfo : csMacInfo, + macKey: isServer ? scMacKey : csMacKey + } + }; + this._protocol._decipher.free(); + hsCipherConfig = config; + this._protocol._decipher = createDecipher(config); + const rw = { + read: void 0, + write: void 0 + }; + switch (negotiated.cs.compress) { + case "zlib": + if (isServer) + rw.read = new ZlibPacketReader(); + else + rw.write = new ZlibPacketWriter(this._protocol); + break; + case "zlib@openssh.com": + if (this._protocol._authenticated) { + if (isServer) + rw.read = new ZlibPacketReader(); + else + rw.write = new ZlibPacketWriter(this._protocol); + break; + } + // FALLTHROUGH + default: + if (isServer) + rw.read = new PacketReader(); + else + rw.write = new PacketWriter(this._protocol); + } + switch (negotiated.sc.compress) { + case "zlib": + if (isServer) + rw.write = new ZlibPacketWriter(this._protocol); + else + rw.read = new ZlibPacketReader(); + break; + case "zlib@openssh.com": + if (this._protocol._authenticated) { + if (isServer) + rw.write = new ZlibPacketWriter(this._protocol); + else + rw.read = new ZlibPacketReader(); + break; + } + // FALLTHROUGH + default: + if (isServer) + rw.write = new PacketWriter(this._protocol); + else + rw.read = new PacketReader(); + } + this._protocol._packetRW.read.cleanup(); + this._protocol._packetRW.write.cleanup(); + this._protocol._packetRW.read = rw.read; + hsWrite = rw.write; + this._public = null; + this._dh = null; + this._kexinit = this._protocol._kexinit = void 0; + this._remoteKexinit = void 0; + this._identRaw = void 0; + this._remoteIdentRaw = void 0; + this._hostKey = void 0; + this._dhData = void 0; + this._sig = void 0; + if (!partial) + return completeHandshake(); + return false; + }; + if (isServer || scOnly) + this.finish = completeHandshake; + if (!isServer) + return completeHandshake(scOnly); + } + start() { + if (!this._protocol._server) { + if (this._protocol._debug) { + let type; + switch (this.type) { + case "group": + type = "KEXDH_INIT"; + break; + default: + type = "KEXECDH_INIT"; + } + this._protocol._debug(`Outbound: Sending ${type}`); + } + const pubKey = this.getPublicKey(); + let p = this._protocol._packetRW.write.allocStartKEX; + const packet = this._protocol._packetRW.write.alloc( + 1 + 4 + pubKey.length, + true + ); + packet[p] = MESSAGE.KEXDH_INIT; + writeUInt32BE(packet, pubKey.length, ++p); + packet.set(pubKey, p += 4); + this._protocol._cipher.encrypt( + this._protocol._packetRW.write.finalize(packet, true) + ); + } + } + getPublicKey() { + this.generateKeys(); + const key = this._public; + if (key) + return this.convertPublicKey(key); + } + convertPublicKey(key) { + let newKey; + let idx = 0; + let len = key.length; + while (key[idx] === 0) { + ++idx; + --len; + } + if (key[idx] & 128) { + newKey = Buffer.allocUnsafe(1 + len); + newKey[0] = 0; + key.copy(newKey, 1, idx); + return newKey; + } + if (len !== key.length) { + newKey = Buffer.allocUnsafe(len); + key.copy(newKey, 0, idx); + key = newKey; + } + return key; + } + computeSecret(otherPublicKey) { + this.generateKeys(); + try { + return convertToMpint(this._dh.computeSecret(otherPublicKey)); + } catch (ex) { + return ex; + } + } + parse(payload) { + const type = payload[0]; + switch (this._step) { + case 1: + if (this._protocol._server) { + if (type !== MESSAGE.KEXDH_INIT) { + return doFatalError( + this._protocol, + `Received packet ${type} instead of ${MESSAGE.KEXDH_INIT}`, + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + this._protocol._debug && this._protocol._debug( + "Received DH Init" + ); + bufferParser.init(payload, 1); + const dhData = bufferParser.readString(); + bufferParser.clear(); + if (dhData === void 0) { + return doFatalError( + this._protocol, + "Received malformed KEX*_INIT", + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + this._dhData = dhData; + let hostKey = this._protocol._hostKeys[this.negotiated.serverHostKey]; + if (Array.isArray(hostKey)) + hostKey = hostKey[0]; + this._hostKey = hostKey; + this.finish(); + } else { + if (type !== MESSAGE.KEXDH_REPLY) { + return doFatalError( + this._protocol, + `Received packet ${type} instead of ${MESSAGE.KEXDH_REPLY}`, + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + this._protocol._debug && this._protocol._debug( + "Received DH Reply" + ); + bufferParser.init(payload, 1); + let hostPubKey; + let dhData; + let sig; + if ((hostPubKey = bufferParser.readString()) === void 0 || (dhData = bufferParser.readString()) === void 0 || (sig = bufferParser.readString()) === void 0) { + bufferParser.clear(); + return doFatalError( + this._protocol, + "Received malformed KEX*_REPLY", + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + bufferParser.clear(); + bufferParser.init(hostPubKey, 0); + const hostPubKeyType = bufferParser.readString(true); + bufferParser.clear(); + if (hostPubKeyType === void 0) { + return doFatalError( + this._protocol, + "Received malformed host public key", + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + if (hostPubKeyType !== this.negotiated.serverHostKey) { + switch (this.negotiated.serverHostKey) { + case "rsa-sha2-256": + case "rsa-sha2-512": + if (hostPubKeyType === "ssh-rsa") + break; + // FALLTHROUGH + default: + return doFatalError( + this._protocol, + "Host key does not match negotiated type", + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + } + this._hostKey = hostPubKey; + this._dhData = dhData; + this._sig = sig; + let checked = false; + let ret; + if (this._protocol._hostVerifier === void 0) { + ret = true; + this._protocol._debug && this._protocol._debug( + "Host accepted by default (no verification)" + ); + } else { + ret = this._protocol._hostVerifier(hostPubKey, (permitted) => { + if (checked) + return; + checked = true; + if (permitted === false) { + this._protocol._debug && this._protocol._debug( + "Host denied (verification failed)" + ); + return doFatalError( + this._protocol, + "Host denied (verification failed)", + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + this._protocol._debug && this._protocol._debug( + "Host accepted (verified)" + ); + this._hostVerified = true; + if (this._receivedNEWKEYS) + this.finish(); + else + trySendNEWKEYS(this); + }); + } + if (ret === void 0) { + ++this._step; + return; + } + checked = true; + if (ret === false) { + this._protocol._debug && this._protocol._debug( + "Host denied (verification failed)" + ); + return doFatalError( + this._protocol, + "Host denied (verification failed)", + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + this._protocol._debug && this._protocol._debug( + "Host accepted (verified)" + ); + this._hostVerified = true; + trySendNEWKEYS(this); + } + ++this._step; + break; + case 2: + if (type !== MESSAGE.NEWKEYS) { + return doFatalError( + this._protocol, + `Received packet ${type} instead of ${MESSAGE.NEWKEYS}`, + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + this._protocol._debug && this._protocol._debug( + "Inbound: NEWKEYS" + ); + this._receivedNEWKEYS = true; + if (this._protocol._strictMode) + this._protocol._decipher.inSeqno = 0; + ++this._step; + return this.finish(!this._protocol._server && !this._hostVerified); + default: + return doFatalError( + this._protocol, + `Received unexpected packet ${type} after NEWKEYS`, + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + } + } + class Curve25519Exchange extends KeyExchange { + constructor(hashName, ...args) { + super(...args); + this.type = "25519"; + this.hashName = hashName; + this._keys = null; + } + generateKeys() { + if (!this._keys) + this._keys = generateKeyPairSync("x25519"); + } + getPublicKey() { + this.generateKeys(); + const key = this._keys.publicKey.export({ type: "spki", format: "der" }); + return key.slice(-32); + } + convertPublicKey(key) { + let newKey; + let idx = 0; + let len = key.length; + while (key[idx] === 0) { + ++idx; + --len; + } + if (key.length === 32) + return key; + if (len !== key.length) { + newKey = Buffer.allocUnsafe(len); + key.copy(newKey, 0, idx); + key = newKey; + } + return key; + } + computeSecret(otherPublicKey) { + this.generateKeys(); + try { + const asnWriter = new Ber.Writer(); + asnWriter.startSequence(); + asnWriter.startSequence(); + asnWriter.writeOID("1.3.101.110"); + asnWriter.endSequence(); + asnWriter.startSequence(Ber.BitString); + asnWriter.writeByte(0); + asnWriter._ensure(otherPublicKey.length); + otherPublicKey.copy( + asnWriter._buf, + asnWriter._offset, + 0, + otherPublicKey.length + ); + asnWriter._offset += otherPublicKey.length; + asnWriter.endSequence(); + asnWriter.endSequence(); + return convertToMpint(diffieHellman({ + privateKey: this._keys.privateKey, + publicKey: createPublicKey({ + key: asnWriter.buffer, + type: "spki", + format: "der" + }) + })); + } catch (ex) { + return ex; + } + } + } + class ECDHExchange extends KeyExchange { + constructor(curveName, hashName, ...args) { + super(...args); + this.type = "ecdh"; + this.curveName = curveName; + this.hashName = hashName; + } + generateKeys() { + if (!this._dh) { + this._dh = createECDH(this.curveName); + this._public = this._dh.generateKeys(); + } + } + } + class DHGroupExchange extends KeyExchange { + constructor(hashName, ...args) { + super(...args); + this.type = "groupex"; + this.hashName = hashName; + this._prime = null; + this._generator = null; + this._minBits = GEX_MIN_BITS; + this._prefBits = dhEstimate(this.negotiated); + if (this._protocol._compatFlags & COMPAT.BUG_DHGEX_LARGE) + this._prefBits = Math.min(this._prefBits, 4096); + this._maxBits = GEX_MAX_BITS; + } + start() { + if (this._protocol._server) + return; + this._protocol._debug && this._protocol._debug( + "Outbound: Sending KEXDH_GEX_REQUEST" + ); + let p = this._protocol._packetRW.write.allocStartKEX; + const packet = this._protocol._packetRW.write.alloc( + 1 + 4 + 4 + 4, + true + ); + packet[p] = MESSAGE.KEXDH_GEX_REQUEST; + writeUInt32BE(packet, this._minBits, ++p); + writeUInt32BE(packet, this._prefBits, p += 4); + writeUInt32BE(packet, this._maxBits, p += 4); + this._protocol._cipher.encrypt( + this._protocol._packetRW.write.finalize(packet, true) + ); + } + generateKeys() { + if (!this._dh && this._prime && this._generator) { + this._dh = createDiffieHellman(this._prime, this._generator); + this._public = this._dh.generateKeys(); + } + } + setDHParams(prime, generator) { + if (!Buffer.isBuffer(prime)) + throw new Error("Invalid prime value"); + if (!Buffer.isBuffer(generator)) + throw new Error("Invalid generator value"); + this._prime = prime; + this._generator = generator; + } + getDHParams() { + if (this._dh) { + return { + prime: convertToMpint(this._dh.getPrime()), + generator: convertToMpint(this._dh.getGenerator()) + }; + } + } + parse(payload) { + const type = payload[0]; + switch (this._step) { + case 1: { + if (this._protocol._server) { + if (type !== MESSAGE.KEXDH_GEX_REQUEST) { + return doFatalError( + this._protocol, + `Received packet ${type} instead of ` + MESSAGE.KEXDH_GEX_REQUEST, + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + return doFatalError( + this._protocol, + "Group exchange not implemented for server", + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + if (type !== MESSAGE.KEXDH_GEX_GROUP) { + return doFatalError( + this._protocol, + `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_GROUP}`, + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + this._protocol._debug && this._protocol._debug( + "Received DH GEX Group" + ); + bufferParser.init(payload, 1); + let prime; + let gen; + if ((prime = bufferParser.readString()) === void 0 || (gen = bufferParser.readString()) === void 0) { + bufferParser.clear(); + return doFatalError( + this._protocol, + "Received malformed KEXDH_GEX_GROUP", + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + bufferParser.clear(); + this.setDHParams(prime, gen); + this.generateKeys(); + const pubkey = this.getPublicKey(); + this._protocol._debug && this._protocol._debug( + "Outbound: Sending KEXDH_GEX_INIT" + ); + let p = this._protocol._packetRW.write.allocStartKEX; + const packet = this._protocol._packetRW.write.alloc(1 + 4 + pubkey.length, true); + packet[p] = MESSAGE.KEXDH_GEX_INIT; + writeUInt32BE(packet, pubkey.length, ++p); + packet.set(pubkey, p += 4); + this._protocol._cipher.encrypt( + this._protocol._packetRW.write.finalize(packet, true) + ); + ++this._step; + break; + } + case 2: + if (this._protocol._server) { + if (type !== MESSAGE.KEXDH_GEX_INIT) { + return doFatalError( + this._protocol, + `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_INIT}`, + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + this._protocol._debug && this._protocol._debug( + "Received DH GEX Init" + ); + return doFatalError( + this._protocol, + "Group exchange not implemented for server", + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } else if (type !== MESSAGE.KEXDH_GEX_REPLY) { + return doFatalError( + this._protocol, + `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_REPLY}`, + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + this._protocol._debug && this._protocol._debug( + "Received DH GEX Reply" + ); + this._step = 1; + payload[0] = MESSAGE.KEXDH_REPLY; + this.parse = KeyExchange.prototype.parse; + this.parse(payload); + } + } + } + class DHExchange extends KeyExchange { + constructor(groupName, hashName, ...args) { + super(...args); + this.type = "group"; + this.groupName = groupName; + this.hashName = hashName; + } + start() { + if (!this._protocol._server) { + this._protocol._debug && this._protocol._debug( + "Outbound: Sending KEXDH_INIT" + ); + const pubKey = this.getPublicKey(); + let p = this._protocol._packetRW.write.allocStartKEX; + const packet = this._protocol._packetRW.write.alloc(1 + 4 + pubKey.length, true); + packet[p] = MESSAGE.KEXDH_INIT; + writeUInt32BE(packet, pubKey.length, ++p); + packet.set(pubKey, p += 4); + this._protocol._cipher.encrypt( + this._protocol._packetRW.write.finalize(packet, true) + ); + } + } + generateKeys() { + if (!this._dh) { + this._dh = createDiffieHellmanGroup(this.groupName); + this._public = this._dh.generateKeys(); + } + } + getDHParams() { + if (this._dh) { + return { + prime: convertToMpint(this._dh.getPrime()), + generator: convertToMpint(this._dh.getGenerator()) + }; + } + } + } + return (negotiated, ...args) => { + if (typeof negotiated !== "object" || negotiated === null) + throw new Error("Invalid negotiated argument"); + const kexType = negotiated.kex; + if (typeof kexType === "string") { + args = [negotiated, ...args]; + switch (kexType) { + case "curve25519-sha256": + case "curve25519-sha256@libssh.org": + if (!curve25519Supported) + break; + return new Curve25519Exchange("sha256", ...args); + case "ecdh-sha2-nistp256": + return new ECDHExchange("prime256v1", "sha256", ...args); + case "ecdh-sha2-nistp384": + return new ECDHExchange("secp384r1", "sha384", ...args); + case "ecdh-sha2-nistp521": + return new ECDHExchange("secp521r1", "sha512", ...args); + case "diffie-hellman-group1-sha1": + return new DHExchange("modp2", "sha1", ...args); + case "diffie-hellman-group14-sha1": + return new DHExchange("modp14", "sha1", ...args); + case "diffie-hellman-group14-sha256": + return new DHExchange("modp14", "sha256", ...args); + case "diffie-hellman-group15-sha512": + return new DHExchange("modp15", "sha512", ...args); + case "diffie-hellman-group16-sha512": + return new DHExchange("modp16", "sha512", ...args); + case "diffie-hellman-group17-sha512": + return new DHExchange("modp17", "sha512", ...args); + case "diffie-hellman-group18-sha512": + return new DHExchange("modp18", "sha512", ...args); + case "diffie-hellman-group-exchange-sha1": + return new DHGroupExchange("sha1", ...args); + case "diffie-hellman-group-exchange-sha256": + return new DHGroupExchange("sha256", ...args); + } + throw new Error(`Unsupported key exchange algorithm: ${kexType}`); + } + throw new Error(`Invalid key exchange type: ${kexType}`); + }; + })(); + var KexInit = /* @__PURE__ */ (() => { + const KEX_PROPERTY_NAMES = [ + "kex", + "serverHostKey", + ["cs", "cipher"], + ["sc", "cipher"], + ["cs", "mac"], + ["sc", "mac"], + ["cs", "compress"], + ["sc", "compress"], + ["cs", "lang"], + ["sc", "lang"] + ]; + return class KexInit { + constructor(obj) { + if (typeof obj !== "object" || obj === null) + throw new TypeError("Argument must be an object"); + const lists = { + kex: void 0, + serverHostKey: void 0, + cs: { + cipher: void 0, + mac: void 0, + compress: void 0, + lang: void 0 + }, + sc: { + cipher: void 0, + mac: void 0, + compress: void 0, + lang: void 0 + }, + all: void 0 + }; + let totalSize = 0; + for (const prop of KEX_PROPERTY_NAMES) { + let base; + let val; + let desc; + let key; + if (typeof prop === "string") { + base = lists; + val = obj[prop]; + desc = key = prop; + } else { + const parent = prop[0]; + base = lists[parent]; + key = prop[1]; + val = obj[parent][key]; + desc = `${parent}.${key}`; + } + const entry = { array: void 0, buffer: void 0 }; + if (Buffer.isBuffer(val)) { + entry.array = ("" + val).split(","); + entry.buffer = val; + totalSize += 4 + val.length; + } else { + if (typeof val === "string") + val = val.split(","); + if (Array.isArray(val)) { + entry.array = val; + entry.buffer = Buffer.from(val.join(",")); + } else { + throw new TypeError(`Invalid \`${desc}\` type: ${typeof val}`); + } + totalSize += 4 + entry.buffer.length; + } + base[key] = entry; + } + const all = Buffer.allocUnsafe(totalSize); + lists.all = all; + let allPos = 0; + for (const prop of KEX_PROPERTY_NAMES) { + let data; + if (typeof prop === "string") + data = lists[prop].buffer; + else + data = lists[prop[0]][prop[1]].buffer; + allPos = writeUInt32BE(all, data.length, allPos); + all.set(data, allPos); + allPos += data.length; + } + this.totalSize = totalSize; + this.lists = lists; + } + copyAllTo(buf, offset) { + const src = this.lists.all; + if (typeof offset !== "number") + throw new TypeError(`Invalid offset value: ${typeof offset}`); + if (buf.length - offset < src.length) + throw new Error("Insufficient space to copy list"); + buf.set(src, offset); + return src.length; + } + }; + })(); + var hashString = (() => { + const LEN = Buffer.allocUnsafe(4); + return (hash, buf) => { + writeUInt32BE(LEN, buf.length, 0); + hash.update(LEN); + hash.update(buf); + }; + })(); + function generateKEXVal(len, hashName, secret, exchangeHash, sessionID, char) { + let ret; + if (len) { + let digest = createHash(hashName).update(secret).update(exchangeHash).update(char).update(sessionID).digest(); + while (digest.length < len) { + const chunk = createHash(hashName).update(secret).update(exchangeHash).update(digest).digest(); + const extended = Buffer.allocUnsafe(digest.length + chunk.length); + extended.set(digest, 0); + extended.set(chunk, digest.length); + digest = extended; + } + if (digest.length === len) + ret = digest; + else + ret = new FastBuffer(digest.buffer, digest.byteOffset, len); + } else { + ret = EMPTY_BUFFER; + } + return ret; + } + function onKEXPayload(state, payload) { + if (payload.length === 0) { + this._debug && this._debug("Inbound: Skipping empty packet payload"); + return; + } + if (this._skipNextInboundPacket) { + this._skipNextInboundPacket = false; + return; + } + payload = this._packetRW.read.read(payload); + const type = payload[0]; + if (!this._strictMode) { + switch (type) { + case MESSAGE.IGNORE: + case MESSAGE.UNIMPLEMENTED: + case MESSAGE.DEBUG: + if (!MESSAGE_HANDLERS) + MESSAGE_HANDLERS = require_handlers(); + return MESSAGE_HANDLERS[type](this, payload); + } + } + switch (type) { + case MESSAGE.DISCONNECT: + if (!MESSAGE_HANDLERS) + MESSAGE_HANDLERS = require_handlers(); + return MESSAGE_HANDLERS[type](this, payload); + case MESSAGE.KEXINIT: + if (!state.firstPacket) { + return doFatalError( + this, + "Received extra KEXINIT during handshake", + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + state.firstPacket = false; + return handleKexInit(this, payload); + default: + if (type < 20 || type > 49) { + return doFatalError( + this, + `Received unexpected packet type ${type}`, + "handshake", + DISCONNECT_REASON.KEY_EXCHANGE_FAILED + ); + } + } + return this._kex.parse(payload); + } + function dhEstimate(neg) { + const csCipher = CIPHER_INFO[neg.cs.cipher]; + const scCipher = CIPHER_INFO[neg.sc.cipher]; + const bits = Math.max( + 0, + csCipher.sslName === "des-ede3-cbc" ? 14 : csCipher.keyLen, + csCipher.blockLen, + csCipher.ivLen, + scCipher.sslName === "des-ede3-cbc" ? 14 : scCipher.keyLen, + scCipher.blockLen, + scCipher.ivLen + ) * 8; + if (bits <= 112) + return 2048; + if (bits <= 128) + return 3072; + if (bits <= 192) + return 7680; + return 8192; + } + function trySendNEWKEYS(kex) { + if (!kex._sentNEWKEYS) { + kex._protocol._debug && kex._protocol._debug( + "Outbound: Sending NEWKEYS" + ); + const p = kex._protocol._packetRW.write.allocStartKEX; + const packet = kex._protocol._packetRW.write.alloc(1, true); + packet[p] = MESSAGE.NEWKEYS; + kex._protocol._cipher.encrypt( + kex._protocol._packetRW.write.finalize(packet, true) + ); + kex._sentNEWKEYS = true; + if (kex._protocol._strictMode) + kex._protocol._cipher.outSeqno = 0; + } + } + module2.exports = { + KexInit, + kexinit, + onKEXPayload, + DEFAULT_KEXINIT_CLIENT: new KexInit({ + kex: DEFAULT_KEX.concat(["ext-info-c", "kex-strict-c-v00@openssh.com"]), + serverHostKey: DEFAULT_SERVER_HOST_KEY, + cs: { + cipher: DEFAULT_CIPHER, + mac: DEFAULT_MAC, + compress: DEFAULT_COMPRESSION, + lang: [] + }, + sc: { + cipher: DEFAULT_CIPHER, + mac: DEFAULT_MAC, + compress: DEFAULT_COMPRESSION, + lang: [] + } + }), + DEFAULT_KEXINIT_SERVER: new KexInit({ + kex: DEFAULT_KEX.concat(["kex-strict-s-v00@openssh.com"]), + serverHostKey: DEFAULT_SERVER_HOST_KEY, + cs: { + cipher: DEFAULT_CIPHER, + mac: DEFAULT_MAC, + compress: DEFAULT_COMPRESSION, + lang: [] + }, + sc: { + cipher: DEFAULT_CIPHER, + mac: DEFAULT_MAC, + compress: DEFAULT_COMPRESSION, + lang: [] + } + }), + HANDLERS: { + [MESSAGE.KEXINIT]: handleKexInit + } + }; + } +}); + +// node_modules/ssh2/package.json +var require_package = __commonJS({ + "node_modules/ssh2/package.json"(exports2, module2) { + module2.exports = { + name: "ssh2", + version: "1.17.0", + author: "Brian White ", + description: "SSH2 client and server modules written in pure JavaScript for node.js", + main: "./lib/index.js", + engines: { + node: ">=10.16.0" + }, + dependencies: { + asn1: "^0.2.6", + "bcrypt-pbkdf": "^1.0.2" + }, + devDependencies: { + "@mscdex/eslint-config": "^1.1.0", + eslint: "^7.32.0" + }, + optionalDependencies: { + "cpu-features": "~0.0.10", + nan: "^2.23.0" + }, + scripts: { + install: "node install.js", + rebuild: "node install.js", + test: "node test/test.js", + lint: "eslint --cache --report-unused-disable-directives --ext=.js .eslintrc.js examples lib test", + "lint:fix": "npm run lint -- --fix" + }, + keywords: [ + "ssh", + "ssh2", + "sftp", + "secure", + "shell", + "exec", + "remote", + "client" + ], + licenses: [ + { + type: "MIT", + url: "http://github.com/mscdex/ssh2/raw/master/LICENSE" + } + ], + repository: { + type: "git", + url: "http://github.com/mscdex/ssh2.git" + } + }; + } +}); + +// node_modules/ssh2/lib/protocol/Protocol.js +var require_Protocol = __commonJS({ + "node_modules/ssh2/lib/protocol/Protocol.js"(exports2, module2) { + "use strict"; + var { inspect } = require("util"); + var { bindingAvailable, NullCipher, NullDecipher } = require_crypto(); + var { + COMPAT_CHECKS, + DISCONNECT_REASON, + eddsaSupported, + MESSAGE, + SIGNALS, + TERMINAL_MODE + } = require_constants6(); + var { + DEFAULT_KEXINIT_CLIENT, + DEFAULT_KEXINIT_SERVER, + KexInit, + kexinit, + onKEXPayload + } = require_kex(); + var { + parseKey + } = require_keyParser(); + var MESSAGE_HANDLERS = require_handlers(); + var { + bufferCopy, + bufferFill, + bufferSlice, + convertSignature, + sendPacket, + writeUInt32BE + } = require_utils3(); + var { + PacketReader, + PacketWriter, + ZlibPacketReader, + ZlibPacketWriter + } = require_zlib(); + var MODULE_VER = require_package().version; + var VALID_DISCONNECT_REASONS = new Map( + Object.values(DISCONNECT_REASON).map((n) => [n, 1]) + ); + var IDENT_RAW = Buffer.from(`SSH-2.0-ssh2js${MODULE_VER}`); + var IDENT = Buffer.from(`${IDENT_RAW}\r +`); + var MAX_LINE_LEN = 8192; + var MAX_LINES = 1024; + var PING_PAYLOAD = Buffer.from([ + MESSAGE.GLOBAL_REQUEST, + // "keepalive@openssh.com" + 0, + 0, + 0, + 21, + 107, + 101, + 101, + 112, + 97, + 108, + 105, + 118, + 101, + 64, + 111, + 112, + 101, + 110, + 115, + 115, + 104, + 46, + 99, + 111, + 109, + // Request a reply + 1 + ]); + var NO_TERMINAL_MODES_BUFFER = Buffer.from([TERMINAL_MODE.TTY_OP_END]); + function noop3() { + } + var Protocol = class { + constructor(config) { + const onWrite = config.onWrite; + if (typeof onWrite !== "function") + throw new Error("Missing onWrite function"); + this._onWrite = (data) => { + onWrite(data); + }; + const onError = config.onError; + if (typeof onError !== "function") + throw new Error("Missing onError function"); + this._onError = (err) => { + onError(err); + }; + const debug2 = config.debug; + this._debug = typeof debug2 === "function" ? (msg) => { + debug2(msg); + } : void 0; + const onHeader = config.onHeader; + this._onHeader = typeof onHeader === "function" ? (...args) => { + onHeader(...args); + } : noop3; + const onPacket = config.onPacket; + this._onPacket = typeof onPacket === "function" ? () => { + onPacket(); + } : noop3; + let onHandshakeComplete = config.onHandshakeComplete; + if (typeof onHandshakeComplete !== "function") + onHandshakeComplete = noop3; + let firstHandshake; + this._onHandshakeComplete = (...args) => { + this._debug && this._debug("Handshake completed"); + if (firstHandshake === void 0) + firstHandshake = true; + else + firstHandshake = false; + const oldQueue = this._queue; + if (oldQueue) { + this._queue = void 0; + this._debug && this._debug( + `Draining outbound queue (${oldQueue.length}) ...` + ); + for (let i = 0; i < oldQueue.length; ++i) { + const data = oldQueue[i]; + let finalized = this._packetRW.write.finalize(data); + if (finalized === data) { + const packet = this._cipher.allocPacket(data.length); + packet.set(data, 5); + finalized = packet; + } + sendPacket(this, finalized); + } + this._debug && this._debug("... finished draining outbound queue"); + } + if (firstHandshake && this._server && this._kex.remoteExtInfoEnabled) + sendExtInfo(this); + onHandshakeComplete(...args); + }; + this._queue = void 0; + const messageHandlers = config.messageHandlers; + if (typeof messageHandlers === "object" && messageHandlers !== null) + this._handlers = messageHandlers; + else + this._handlers = {}; + this._onPayload = onPayload.bind(this); + this._server = !!config.server; + this._banner = void 0; + let greeting; + if (this._server) { + if (typeof config.hostKeys !== "object" || config.hostKeys === null) + throw new Error("Missing server host key(s)"); + this._hostKeys = config.hostKeys; + if (typeof config.greeting === "string" && config.greeting.length) { + greeting = config.greeting.slice(-2) === "\r\n" ? config.greeting : `${config.greeting}\r +`; + } + if (typeof config.banner === "string" && config.banner.length) { + this._banner = config.banner.slice(-2) === "\r\n" ? config.banner : `${config.banner}\r +`; + } + } else { + this._hostKeys = void 0; + } + let offer = config.offer; + if (typeof offer !== "object" || offer === null) { + offer = this._server ? DEFAULT_KEXINIT_SERVER : DEFAULT_KEXINIT_CLIENT; + } else if (offer.constructor !== KexInit) { + if (this._server) { + offer.kex = offer.kex.concat(["kex-strict-s-v00@openssh.com"]); + } else { + offer.kex = offer.kex.concat([ + "ext-info-c", + "kex-strict-c-v00@openssh.com" + ]); + } + offer = new KexInit(offer); + } + this._kex = void 0; + this._strictMode = void 0; + this._kexinit = void 0; + this._offer = offer; + this._cipher = new NullCipher(0, this._onWrite); + this._decipher = void 0; + this._skipNextInboundPacket = false; + this._packetRW = { + read: new PacketReader(), + write: new PacketWriter(this) + }; + this._hostVerifier = !this._server && typeof config.hostVerifier === "function" ? config.hostVerifier : void 0; + this._parse = parseHeader; + this._buffer = void 0; + this._authsQueue = []; + this._authenticated = false; + this._remoteIdentRaw = void 0; + let sentIdent; + if (typeof config.ident === "string") { + this._identRaw = Buffer.from(`SSH-2.0-${config.ident}`); + sentIdent = Buffer.allocUnsafe(this._identRaw.length + 2); + sentIdent.set(this._identRaw, 0); + sentIdent[sentIdent.length - 2] = 13; + sentIdent[sentIdent.length - 1] = 10; + } else if (Buffer.isBuffer(config.ident)) { + const fullIdent = Buffer.allocUnsafe(8 + config.ident.length); + fullIdent.latin1Write("SSH-2.0-", 0, 8); + fullIdent.set(config.ident, 8); + this._identRaw = fullIdent; + sentIdent = Buffer.allocUnsafe(fullIdent.length + 2); + sentIdent.set(fullIdent, 0); + sentIdent[sentIdent.length - 2] = 13; + sentIdent[sentIdent.length - 1] = 10; + } else { + this._identRaw = IDENT_RAW; + sentIdent = IDENT; + } + this._compatFlags = 0; + if (this._debug) { + if (bindingAvailable) + this._debug("Custom crypto binding available"); + else + this._debug("Custom crypto binding not available"); + } + this._debug && this._debug( + `Local ident: ${inspect(this._identRaw.toString())}` + ); + this.start = () => { + this.start = void 0; + if (greeting) + this._onWrite(greeting); + this._onWrite(sentIdent); + }; + } + _destruct(reason) { + this._packetRW.read.cleanup(); + this._packetRW.write.cleanup(); + this._cipher && this._cipher.free(); + this._decipher && this._decipher.free(); + if (typeof reason !== "string" || reason.length === 0) + reason = "fatal error"; + this.parse = () => { + throw new Error(`Instance unusable after ${reason}`); + }; + this._onWrite = () => { + throw new Error(`Instance unusable after ${reason}`); + }; + this._destruct = void 0; + } + cleanup() { + this._destruct && this._destruct(); + } + parse(chunk, i, len) { + while (i < len) + i = this._parse(chunk, i, len); + } + // Protocol message API + // =========================================================================== + // Common/Shared ============================================================= + // =========================================================================== + // Global + // ------ + disconnect(reason) { + const pktLen = 1 + 4 + 4 + 4; + let p = this._packetRW.write.allocStartKEX; + const packet = this._packetRW.write.alloc(pktLen, true); + const end = p + pktLen; + if (!VALID_DISCONNECT_REASONS.has(reason)) + reason = DISCONNECT_REASON.PROTOCOL_ERROR; + packet[p] = MESSAGE.DISCONNECT; + writeUInt32BE(packet, reason, ++p); + packet.fill(0, p += 4, end); + this._debug && this._debug(`Outbound: Sending DISCONNECT (${reason})`); + sendPacket(this, this._packetRW.write.finalize(packet, true), true); + } + ping() { + const p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(PING_PAYLOAD.length); + packet.set(PING_PAYLOAD, p); + this._debug && this._debug( + "Outbound: Sending ping (GLOBAL_REQUEST: keepalive@openssh.com)" + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + rekey() { + if (this._kexinit === void 0) { + this._debug && this._debug("Outbound: Initiated explicit rekey"); + this._queue = []; + kexinit(this); + } else { + this._debug && this._debug("Outbound: Ignoring rekey during handshake"); + } + } + // 'ssh-connection' service-specific + // --------------------------------- + requestSuccess(data) { + let p = this._packetRW.write.allocStart; + let packet; + if (Buffer.isBuffer(data)) { + packet = this._packetRW.write.alloc(1 + data.length); + packet[p] = MESSAGE.REQUEST_SUCCESS; + packet.set(data, ++p); + } else { + packet = this._packetRW.write.alloc(1); + packet[p] = MESSAGE.REQUEST_SUCCESS; + } + this._debug && this._debug("Outbound: Sending REQUEST_SUCCESS"); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + requestFailure() { + const p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1); + packet[p] = MESSAGE.REQUEST_FAILURE; + this._debug && this._debug("Outbound: Sending REQUEST_FAILURE"); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + channelSuccess(chan) { + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4); + packet[p] = MESSAGE.CHANNEL_SUCCESS; + writeUInt32BE(packet, chan, ++p); + this._debug && this._debug(`Outbound: Sending CHANNEL_SUCCESS (r:${chan})`); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + channelFailure(chan) { + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4); + packet[p] = MESSAGE.CHANNEL_FAILURE; + writeUInt32BE(packet, chan, ++p); + this._debug && this._debug(`Outbound: Sending CHANNEL_FAILURE (r:${chan})`); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + channelEOF(chan) { + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4); + packet[p] = MESSAGE.CHANNEL_EOF; + writeUInt32BE(packet, chan, ++p); + this._debug && this._debug(`Outbound: Sending CHANNEL_EOF (r:${chan})`); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + channelClose(chan) { + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4); + packet[p] = MESSAGE.CHANNEL_CLOSE; + writeUInt32BE(packet, chan, ++p); + this._debug && this._debug(`Outbound: Sending CHANNEL_CLOSE (r:${chan})`); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + channelWindowAdjust(chan, amount) { + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 4); + packet[p] = MESSAGE.CHANNEL_WINDOW_ADJUST; + writeUInt32BE(packet, chan, ++p); + writeUInt32BE(packet, amount, p += 4); + this._debug && this._debug( + `Outbound: Sending CHANNEL_WINDOW_ADJUST (r:${chan}, ${amount})` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + channelData(chan, data) { + const isBuffer = Buffer.isBuffer(data); + const dataLen = isBuffer ? data.length : Buffer.byteLength(data); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 4 + dataLen); + packet[p] = MESSAGE.CHANNEL_DATA; + writeUInt32BE(packet, chan, ++p); + writeUInt32BE(packet, dataLen, p += 4); + if (isBuffer) + packet.set(data, p += 4); + else + packet.utf8Write(data, p += 4, dataLen); + this._debug && this._debug( + `Outbound: Sending CHANNEL_DATA (r:${chan}, ${dataLen})` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + channelExtData(chan, data, type) { + const isBuffer = Buffer.isBuffer(data); + const dataLen = isBuffer ? data.length : Buffer.byteLength(data); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + dataLen); + packet[p] = MESSAGE.CHANNEL_EXTENDED_DATA; + writeUInt32BE(packet, chan, ++p); + writeUInt32BE(packet, type, p += 4); + writeUInt32BE(packet, dataLen, p += 4); + if (isBuffer) + packet.set(data, p += 4); + else + packet.utf8Write(data, p += 4, dataLen); + this._debug && this._debug(`Outbound: Sending CHANNEL_EXTENDED_DATA (r:${chan})`); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + channelOpenConfirm(remote, local, initWindow, maxPacket) { + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 4); + packet[p] = MESSAGE.CHANNEL_OPEN_CONFIRMATION; + writeUInt32BE(packet, remote, ++p); + writeUInt32BE(packet, local, p += 4); + writeUInt32BE(packet, initWindow, p += 4); + writeUInt32BE(packet, maxPacket, p += 4); + this._debug && this._debug( + `Outbound: Sending CHANNEL_OPEN_CONFIRMATION (r:${remote}, l:${local})` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + channelOpenFail(remote, reason, desc) { + if (typeof desc !== "string") + desc = ""; + const descLen = Buffer.byteLength(desc); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + descLen + 4); + packet[p] = MESSAGE.CHANNEL_OPEN_FAILURE; + writeUInt32BE(packet, remote, ++p); + writeUInt32BE(packet, reason, p += 4); + writeUInt32BE(packet, descLen, p += 4); + p += 4; + if (descLen) { + packet.utf8Write(desc, p, descLen); + p += descLen; + } + writeUInt32BE(packet, 0, p); + this._debug && this._debug(`Outbound: Sending CHANNEL_OPEN_FAILURE (r:${remote})`); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + // =========================================================================== + // Client-specific =========================================================== + // =========================================================================== + // Global + // ------ + service(name) { + if (this._server) + throw new Error("Client-only method called in server mode"); + const nameLen = Buffer.byteLength(name); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + nameLen); + packet[p] = MESSAGE.SERVICE_REQUEST; + writeUInt32BE(packet, nameLen, ++p); + packet.utf8Write(name, p += 4, nameLen); + this._debug && this._debug(`Outbound: Sending SERVICE_REQUEST (${name})`); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + // 'ssh-userauth' service-specific + // ------------------------------- + authPassword(username, password, newPassword) { + if (this._server) + throw new Error("Client-only method called in server mode"); + const userLen = Buffer.byteLength(username); + const passLen = Buffer.byteLength(password); + const newPassLen = newPassword ? Buffer.byteLength(newPassword) : 0; + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + userLen + 4 + 14 + 4 + 8 + 1 + 4 + passLen + (newPassword ? 4 + newPassLen : 0) + ); + packet[p] = MESSAGE.USERAUTH_REQUEST; + writeUInt32BE(packet, userLen, ++p); + packet.utf8Write(username, p += 4, userLen); + writeUInt32BE(packet, 14, p += userLen); + packet.utf8Write("ssh-connection", p += 4, 14); + writeUInt32BE(packet, 8, p += 14); + packet.utf8Write("password", p += 4, 8); + packet[p += 8] = newPassword ? 1 : 0; + writeUInt32BE(packet, passLen, ++p); + if (Buffer.isBuffer(password)) + bufferCopy(password, packet, 0, passLen, p += 4); + else + packet.utf8Write(password, p += 4, passLen); + if (newPassword) { + writeUInt32BE(packet, newPassLen, p += passLen); + if (Buffer.isBuffer(newPassword)) + bufferCopy(newPassword, packet, 0, newPassLen, p += 4); + else + packet.utf8Write(newPassword, p += 4, newPassLen); + this._debug && this._debug( + "Outbound: Sending USERAUTH_REQUEST (changed password)" + ); + } else { + this._debug && this._debug( + "Outbound: Sending USERAUTH_REQUEST (password)" + ); + } + this._authsQueue.push("password"); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + authPK(username, pubKey, keyAlgo, cbSign) { + if (this._server) + throw new Error("Client-only method called in server mode"); + pubKey = parseKey(pubKey); + if (pubKey instanceof Error) + throw new Error("Invalid key"); + const keyType = pubKey.type; + pubKey = pubKey.getPublicSSH(); + if (typeof keyAlgo === "function") { + cbSign = keyAlgo; + keyAlgo = void 0; + } + if (!keyAlgo) + keyAlgo = keyType; + const userLen = Buffer.byteLength(username); + const algoLen = Buffer.byteLength(keyAlgo); + const pubKeyLen = pubKey.length; + const sessionID = this._kex.sessionID; + const sesLen = sessionID.length; + const payloadLen = (cbSign ? 4 + sesLen : 0) + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen; + let packet; + let p; + if (cbSign) { + packet = Buffer.allocUnsafe(payloadLen); + p = 0; + writeUInt32BE(packet, sesLen, p); + packet.set(sessionID, p += 4); + p += sesLen; + } else { + packet = this._packetRW.write.alloc(payloadLen); + p = this._packetRW.write.allocStart; + } + packet[p] = MESSAGE.USERAUTH_REQUEST; + writeUInt32BE(packet, userLen, ++p); + packet.utf8Write(username, p += 4, userLen); + writeUInt32BE(packet, 14, p += userLen); + packet.utf8Write("ssh-connection", p += 4, 14); + writeUInt32BE(packet, 9, p += 14); + packet.utf8Write("publickey", p += 4, 9); + packet[p += 9] = cbSign ? 1 : 0; + writeUInt32BE(packet, algoLen, ++p); + packet.utf8Write(keyAlgo, p += 4, algoLen); + writeUInt32BE(packet, pubKeyLen, p += algoLen); + packet.set(pubKey, p += 4); + if (!cbSign) { + this._authsQueue.push("publickey"); + this._debug && this._debug( + "Outbound: Sending USERAUTH_REQUEST (publickey -- check)" + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + return; + } + cbSign(packet, (signature) => { + signature = convertSignature(signature, keyType); + if (signature === false) + throw new Error("Error while converting handshake signature"); + const sigLen = signature.length; + p = this._packetRW.write.allocStart; + packet = this._packetRW.write.alloc( + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen + 4 + 4 + algoLen + 4 + sigLen + ); + packet[p] = MESSAGE.USERAUTH_REQUEST; + writeUInt32BE(packet, userLen, ++p); + packet.utf8Write(username, p += 4, userLen); + writeUInt32BE(packet, 14, p += userLen); + packet.utf8Write("ssh-connection", p += 4, 14); + writeUInt32BE(packet, 9, p += 14); + packet.utf8Write("publickey", p += 4, 9); + packet[p += 9] = 1; + writeUInt32BE(packet, algoLen, ++p); + packet.utf8Write(keyAlgo, p += 4, algoLen); + writeUInt32BE(packet, pubKeyLen, p += algoLen); + packet.set(pubKey, p += 4); + writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += pubKeyLen); + writeUInt32BE(packet, algoLen, p += 4); + packet.utf8Write(keyAlgo, p += 4, algoLen); + writeUInt32BE(packet, sigLen, p += algoLen); + packet.set(signature, p += 4); + this._authsQueue.push("publickey"); + this._debug && this._debug( + "Outbound: Sending USERAUTH_REQUEST (publickey)" + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + }); + } + authHostbased(username, pubKey, hostname, userlocal, keyAlgo, cbSign) { + if (this._server) + throw new Error("Client-only method called in server mode"); + pubKey = parseKey(pubKey); + if (pubKey instanceof Error) + throw new Error("Invalid key"); + const keyType = pubKey.type; + pubKey = pubKey.getPublicSSH(); + if (typeof keyAlgo === "function") { + cbSign = keyAlgo; + keyAlgo = void 0; + } + if (!keyAlgo) + keyAlgo = keyType; + const userLen = Buffer.byteLength(username); + const algoLen = Buffer.byteLength(keyAlgo); + const pubKeyLen = pubKey.length; + const sessionID = this._kex.sessionID; + const sesLen = sessionID.length; + const hostnameLen = Buffer.byteLength(hostname); + const userlocalLen = Buffer.byteLength(userlocal); + const data = Buffer.allocUnsafe( + 4 + sesLen + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 4 + algoLen + 4 + pubKeyLen + 4 + hostnameLen + 4 + userlocalLen + ); + let p = 0; + writeUInt32BE(data, sesLen, p); + data.set(sessionID, p += 4); + data[p += sesLen] = MESSAGE.USERAUTH_REQUEST; + writeUInt32BE(data, userLen, ++p); + data.utf8Write(username, p += 4, userLen); + writeUInt32BE(data, 14, p += userLen); + data.utf8Write("ssh-connection", p += 4, 14); + writeUInt32BE(data, 9, p += 14); + data.utf8Write("hostbased", p += 4, 9); + writeUInt32BE(data, algoLen, p += 9); + data.utf8Write(keyAlgo, p += 4, algoLen); + writeUInt32BE(data, pubKeyLen, p += algoLen); + data.set(pubKey, p += 4); + writeUInt32BE(data, hostnameLen, p += pubKeyLen); + data.utf8Write(hostname, p += 4, hostnameLen); + writeUInt32BE(data, userlocalLen, p += hostnameLen); + data.utf8Write(userlocal, p += 4, userlocalLen); + cbSign(data, (signature) => { + signature = convertSignature(signature, keyType); + if (!signature) + throw new Error("Error while converting handshake signature"); + const sigLen = signature.length; + const reqDataLen = data.length - sesLen - 4; + p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + reqDataLen + 4 + 4 + algoLen + 4 + sigLen + ); + bufferCopy(data, packet, 4 + sesLen, data.length, p); + writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += reqDataLen); + writeUInt32BE(packet, algoLen, p += 4); + packet.utf8Write(keyAlgo, p += 4, algoLen); + writeUInt32BE(packet, sigLen, p += algoLen); + packet.set(signature, p += 4); + this._authsQueue.push("hostbased"); + this._debug && this._debug( + "Outbound: Sending USERAUTH_REQUEST (hostbased)" + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + }); + } + authKeyboard(username) { + if (this._server) + throw new Error("Client-only method called in server mode"); + const userLen = Buffer.byteLength(username); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + userLen + 4 + 14 + 4 + 20 + 4 + 4 + ); + packet[p] = MESSAGE.USERAUTH_REQUEST; + writeUInt32BE(packet, userLen, ++p); + packet.utf8Write(username, p += 4, userLen); + writeUInt32BE(packet, 14, p += userLen); + packet.utf8Write("ssh-connection", p += 4, 14); + writeUInt32BE(packet, 20, p += 14); + packet.utf8Write("keyboard-interactive", p += 4, 20); + writeUInt32BE(packet, 0, p += 20); + writeUInt32BE(packet, 0, p += 4); + this._authsQueue.push("keyboard-interactive"); + this._debug && this._debug( + "Outbound: Sending USERAUTH_REQUEST (keyboard-interactive)" + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + authNone(username) { + if (this._server) + throw new Error("Client-only method called in server mode"); + const userLen = Buffer.byteLength(username); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + userLen + 4 + 14 + 4 + 4); + packet[p] = MESSAGE.USERAUTH_REQUEST; + writeUInt32BE(packet, userLen, ++p); + packet.utf8Write(username, p += 4, userLen); + writeUInt32BE(packet, 14, p += userLen); + packet.utf8Write("ssh-connection", p += 4, 14); + writeUInt32BE(packet, 4, p += 14); + packet.utf8Write("none", p += 4, 4); + this._authsQueue.push("none"); + this._debug && this._debug("Outbound: Sending USERAUTH_REQUEST (none)"); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + authInfoRes(responses) { + if (this._server) + throw new Error("Client-only method called in server mode"); + let responsesTotalLen = 0; + let responseLens; + if (responses) { + responseLens = new Array(responses.length); + for (let i = 0; i < responses.length; ++i) { + const len = Buffer.byteLength(responses[i]); + responseLens[i] = len; + responsesTotalLen += 4 + len; + } + } + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + responsesTotalLen); + packet[p] = MESSAGE.USERAUTH_INFO_RESPONSE; + if (responses) { + writeUInt32BE(packet, responses.length, ++p); + p += 4; + for (let i = 0; i < responses.length; ++i) { + const len = responseLens[i]; + writeUInt32BE(packet, len, p); + p += 4; + if (len) { + packet.utf8Write(responses[i], p, len); + p += len; + } + } + } else { + writeUInt32BE(packet, 0, ++p); + } + this._debug && this._debug("Outbound: Sending USERAUTH_INFO_RESPONSE"); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + // 'ssh-connection' service-specific + // --------------------------------- + tcpipForward(bindAddr, bindPort, wantReply) { + if (this._server) + throw new Error("Client-only method called in server mode"); + const addrLen = Buffer.byteLength(bindAddr); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 13 + 1 + 4 + addrLen + 4); + packet[p] = MESSAGE.GLOBAL_REQUEST; + writeUInt32BE(packet, 13, ++p); + packet.utf8Write("tcpip-forward", p += 4, 13); + packet[p += 13] = wantReply === void 0 || wantReply === true ? 1 : 0; + writeUInt32BE(packet, addrLen, ++p); + packet.utf8Write(bindAddr, p += 4, addrLen); + writeUInt32BE(packet, bindPort, p += addrLen); + this._debug && this._debug("Outbound: Sending GLOBAL_REQUEST (tcpip-forward)"); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + cancelTcpipForward(bindAddr, bindPort, wantReply) { + if (this._server) + throw new Error("Client-only method called in server mode"); + const addrLen = Buffer.byteLength(bindAddr); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 20 + 1 + 4 + addrLen + 4); + packet[p] = MESSAGE.GLOBAL_REQUEST; + writeUInt32BE(packet, 20, ++p); + packet.utf8Write("cancel-tcpip-forward", p += 4, 20); + packet[p += 20] = wantReply === void 0 || wantReply === true ? 1 : 0; + writeUInt32BE(packet, addrLen, ++p); + packet.utf8Write(bindAddr, p += 4, addrLen); + writeUInt32BE(packet, bindPort, p += addrLen); + this._debug && this._debug("Outbound: Sending GLOBAL_REQUEST (cancel-tcpip-forward)"); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + openssh_streamLocalForward(socketPath, wantReply) { + if (this._server) + throw new Error("Client-only method called in server mode"); + const socketPathLen = Buffer.byteLength(socketPath); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 31 + 1 + 4 + socketPathLen + ); + packet[p] = MESSAGE.GLOBAL_REQUEST; + writeUInt32BE(packet, 31, ++p); + packet.utf8Write("streamlocal-forward@openssh.com", p += 4, 31); + packet[p += 31] = wantReply === void 0 || wantReply === true ? 1 : 0; + writeUInt32BE(packet, socketPathLen, ++p); + packet.utf8Write(socketPath, p += 4, socketPathLen); + this._debug && this._debug( + "Outbound: Sending GLOBAL_REQUEST (streamlocal-forward@openssh.com)" + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + openssh_cancelStreamLocalForward(socketPath, wantReply) { + if (this._server) + throw new Error("Client-only method called in server mode"); + const socketPathLen = Buffer.byteLength(socketPath); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 38 + 1 + 4 + socketPathLen + ); + packet[p] = MESSAGE.GLOBAL_REQUEST; + writeUInt32BE(packet, 38, ++p); + packet.utf8Write("cancel-streamlocal-forward@openssh.com", p += 4, 38); + packet[p += 38] = wantReply === void 0 || wantReply === true ? 1 : 0; + writeUInt32BE(packet, socketPathLen, ++p); + packet.utf8Write(socketPath, p += 4, socketPathLen); + if (this._debug) { + this._debug( + "Outbound: Sending GLOBAL_REQUEST (cancel-streamlocal-forward@openssh.com)" + ); + } + sendPacket(this, this._packetRW.write.finalize(packet)); + } + directTcpip(chan, initWindow, maxPacket, cfg) { + if (this._server) + throw new Error("Client-only method called in server mode"); + const srcLen = Buffer.byteLength(cfg.srcIP); + const dstLen = Buffer.byteLength(cfg.dstIP); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 12 + 4 + 4 + 4 + 4 + srcLen + 4 + 4 + dstLen + 4 + ); + packet[p] = MESSAGE.CHANNEL_OPEN; + writeUInt32BE(packet, 12, ++p); + packet.utf8Write("direct-tcpip", p += 4, 12); + writeUInt32BE(packet, chan, p += 12); + writeUInt32BE(packet, initWindow, p += 4); + writeUInt32BE(packet, maxPacket, p += 4); + writeUInt32BE(packet, dstLen, p += 4); + packet.utf8Write(cfg.dstIP, p += 4, dstLen); + writeUInt32BE(packet, cfg.dstPort, p += dstLen); + writeUInt32BE(packet, srcLen, p += 4); + packet.utf8Write(cfg.srcIP, p += 4, srcLen); + writeUInt32BE(packet, cfg.srcPort, p += srcLen); + this._debug && this._debug( + `Outbound: Sending CHANNEL_OPEN (r:${chan}, direct-tcpip)` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + openssh_directStreamLocal(chan, initWindow, maxPacket, cfg) { + if (this._server) + throw new Error("Client-only method called in server mode"); + const pathLen = Buffer.byteLength(cfg.socketPath); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 30 + 4 + 4 + 4 + 4 + pathLen + 4 + 4 + ); + packet[p] = MESSAGE.CHANNEL_OPEN; + writeUInt32BE(packet, 30, ++p); + packet.utf8Write("direct-streamlocal@openssh.com", p += 4, 30); + writeUInt32BE(packet, chan, p += 30); + writeUInt32BE(packet, initWindow, p += 4); + writeUInt32BE(packet, maxPacket, p += 4); + writeUInt32BE(packet, pathLen, p += 4); + packet.utf8Write(cfg.socketPath, p += 4, pathLen); + bufferFill(packet, 0, p += pathLen, p + 8); + if (this._debug) { + this._debug( + `Outbound: Sending CHANNEL_OPEN (r:${chan}, direct-streamlocal@openssh.com)` + ); + } + sendPacket(this, this._packetRW.write.finalize(packet)); + } + openssh_noMoreSessions(wantReply) { + if (this._server) + throw new Error("Client-only method called in server mode"); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 28 + 1); + packet[p] = MESSAGE.GLOBAL_REQUEST; + writeUInt32BE(packet, 28, ++p); + packet.utf8Write("no-more-sessions@openssh.com", p += 4, 28); + packet[p += 28] = wantReply === void 0 || wantReply === true ? 1 : 0; + this._debug && this._debug( + "Outbound: Sending GLOBAL_REQUEST (no-more-sessions@openssh.com)" + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + session(chan, initWindow, maxPacket) { + if (this._server) + throw new Error("Client-only method called in server mode"); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 7 + 4 + 4 + 4); + packet[p] = MESSAGE.CHANNEL_OPEN; + writeUInt32BE(packet, 7, ++p); + packet.utf8Write("session", p += 4, 7); + writeUInt32BE(packet, chan, p += 7); + writeUInt32BE(packet, initWindow, p += 4); + writeUInt32BE(packet, maxPacket, p += 4); + this._debug && this._debug(`Outbound: Sending CHANNEL_OPEN (r:${chan}, session)`); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + windowChange(chan, rows, cols, height, width) { + if (this._server) + throw new Error("Client-only method called in server mode"); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 4 + 13 + 1 + 4 + 4 + 4 + 4 + ); + packet[p] = MESSAGE.CHANNEL_REQUEST; + writeUInt32BE(packet, chan, ++p); + writeUInt32BE(packet, 13, p += 4); + packet.utf8Write("window-change", p += 4, 13); + packet[p += 13] = 0; + writeUInt32BE(packet, cols, ++p); + writeUInt32BE(packet, rows, p += 4); + writeUInt32BE(packet, width, p += 4); + writeUInt32BE(packet, height, p += 4); + this._debug && this._debug( + `Outbound: Sending CHANNEL_REQUEST (r:${chan}, window-change)` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + pty(chan, rows, cols, height, width, term, modes, wantReply) { + if (this._server) + throw new Error("Client-only method called in server mode"); + if (!term || !term.length) + term = "vt100"; + if (modes && !Buffer.isBuffer(modes) && !Array.isArray(modes) && typeof modes === "object" && modes !== null) { + modes = modesToBytes(modes); + } + if (!modes || !modes.length) + modes = NO_TERMINAL_MODES_BUFFER; + const termLen = term.length; + const modesLen = modes.length; + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 4 + 7 + 1 + 4 + termLen + 4 + 4 + 4 + 4 + 4 + modesLen + ); + packet[p] = MESSAGE.CHANNEL_REQUEST; + writeUInt32BE(packet, chan, ++p); + writeUInt32BE(packet, 7, p += 4); + packet.utf8Write("pty-req", p += 4, 7); + packet[p += 7] = wantReply === void 0 || wantReply === true ? 1 : 0; + writeUInt32BE(packet, termLen, ++p); + packet.utf8Write(term, p += 4, termLen); + writeUInt32BE(packet, cols, p += termLen); + writeUInt32BE(packet, rows, p += 4); + writeUInt32BE(packet, width, p += 4); + writeUInt32BE(packet, height, p += 4); + writeUInt32BE(packet, modesLen, p += 4); + p += 4; + if (Array.isArray(modes)) { + for (let i = 0; i < modesLen; ++i) + packet[p++] = modes[i]; + } else if (Buffer.isBuffer(modes)) { + packet.set(modes, p); + } + this._debug && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, pty-req)`); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + shell(chan, wantReply) { + if (this._server) + throw new Error("Client-only method called in server mode"); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 4 + 5 + 1); + packet[p] = MESSAGE.CHANNEL_REQUEST; + writeUInt32BE(packet, chan, ++p); + writeUInt32BE(packet, 5, p += 4); + packet.utf8Write("shell", p += 4, 5); + packet[p += 5] = wantReply === void 0 || wantReply === true ? 1 : 0; + this._debug && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, shell)`); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + exec(chan, cmd, wantReply) { + if (this._server) + throw new Error("Client-only method called in server mode"); + const isBuf = Buffer.isBuffer(cmd); + const cmdLen = isBuf ? cmd.length : Buffer.byteLength(cmd); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 1 + 4 + cmdLen); + packet[p] = MESSAGE.CHANNEL_REQUEST; + writeUInt32BE(packet, chan, ++p); + writeUInt32BE(packet, 4, p += 4); + packet.utf8Write("exec", p += 4, 4); + packet[p += 4] = wantReply === void 0 || wantReply === true ? 1 : 0; + writeUInt32BE(packet, cmdLen, ++p); + if (isBuf) + packet.set(cmd, p += 4); + else + packet.utf8Write(cmd, p += 4, cmdLen); + this._debug && this._debug( + `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exec: ${cmd})` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + signal(chan, signal) { + if (this._server) + throw new Error("Client-only method called in server mode"); + const origSignal = signal; + signal = signal.toUpperCase(); + if (signal.slice(0, 3) === "SIG") + signal = signal.slice(3); + if (SIGNALS[signal] !== 1) + throw new Error(`Invalid signal: ${origSignal}`); + const signalLen = signal.length; + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 4 + 6 + 1 + 4 + signalLen + ); + packet[p] = MESSAGE.CHANNEL_REQUEST; + writeUInt32BE(packet, chan, ++p); + writeUInt32BE(packet, 6, p += 4); + packet.utf8Write("signal", p += 4, 6); + packet[p += 6] = 0; + writeUInt32BE(packet, signalLen, ++p); + packet.utf8Write(signal, p += 4, signalLen); + this._debug && this._debug( + `Outbound: Sending CHANNEL_REQUEST (r:${chan}, signal: ${signal})` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + env(chan, key, val, wantReply) { + if (this._server) + throw new Error("Client-only method called in server mode"); + const keyLen = Buffer.byteLength(key); + const isBuf = Buffer.isBuffer(val); + const valLen = isBuf ? val.length : Buffer.byteLength(val); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 4 + 3 + 1 + 4 + keyLen + 4 + valLen + ); + packet[p] = MESSAGE.CHANNEL_REQUEST; + writeUInt32BE(packet, chan, ++p); + writeUInt32BE(packet, 3, p += 4); + packet.utf8Write("env", p += 4, 3); + packet[p += 3] = wantReply === void 0 || wantReply === true ? 1 : 0; + writeUInt32BE(packet, keyLen, ++p); + packet.utf8Write(key, p += 4, keyLen); + writeUInt32BE(packet, valLen, p += keyLen); + if (isBuf) + packet.set(val, p += 4); + else + packet.utf8Write(val, p += 4, valLen); + this._debug && this._debug( + `Outbound: Sending CHANNEL_REQUEST (r:${chan}, env: ${key}=${val})` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + x11Forward(chan, cfg, wantReply) { + if (this._server) + throw new Error("Client-only method called in server mode"); + const protocol = cfg.protocol; + const cookie = cfg.cookie; + const isBufProto = Buffer.isBuffer(protocol); + const protoLen = isBufProto ? protocol.length : Buffer.byteLength(protocol); + const isBufCookie = Buffer.isBuffer(cookie); + const cookieLen = isBufCookie ? cookie.length : Buffer.byteLength(cookie); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 4 + 7 + 1 + 1 + 4 + protoLen + 4 + cookieLen + 4 + ); + packet[p] = MESSAGE.CHANNEL_REQUEST; + writeUInt32BE(packet, chan, ++p); + writeUInt32BE(packet, 7, p += 4); + packet.utf8Write("x11-req", p += 4, 7); + packet[p += 7] = wantReply === void 0 || wantReply === true ? 1 : 0; + packet[++p] = cfg.single ? 1 : 0; + writeUInt32BE(packet, protoLen, ++p); + if (isBufProto) + packet.set(protocol, p += 4); + else + packet.utf8Write(protocol, p += 4, protoLen); + writeUInt32BE(packet, cookieLen, p += protoLen); + if (isBufCookie) + packet.set(cookie, p += 4); + else + packet.latin1Write(cookie, p += 4, cookieLen); + writeUInt32BE(packet, cfg.screen || 0, p += cookieLen); + this._debug && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, x11-req)`); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + subsystem(chan, name, wantReply) { + if (this._server) + throw new Error("Client-only method called in server mode"); + const nameLen = Buffer.byteLength(name); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 4 + 9 + 1 + 4 + nameLen); + packet[p] = MESSAGE.CHANNEL_REQUEST; + writeUInt32BE(packet, chan, ++p); + writeUInt32BE(packet, 9, p += 4); + packet.utf8Write("subsystem", p += 4, 9); + packet[p += 9] = wantReply === void 0 || wantReply === true ? 1 : 0; + writeUInt32BE(packet, nameLen, ++p); + packet.utf8Write(name, p += 4, nameLen); + this._debug && this._debug( + `Outbound: Sending CHANNEL_REQUEST (r:${chan}, subsystem: ${name})` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + openssh_agentForward(chan, wantReply) { + if (this._server) + throw new Error("Client-only method called in server mode"); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 4 + 26 + 1); + packet[p] = MESSAGE.CHANNEL_REQUEST; + writeUInt32BE(packet, chan, ++p); + writeUInt32BE(packet, 26, p += 4); + packet.utf8Write("auth-agent-req@openssh.com", p += 4, 26); + packet[p += 26] = wantReply === void 0 || wantReply === true ? 1 : 0; + if (this._debug) { + this._debug( + `Outbound: Sending CHANNEL_REQUEST (r:${chan}, auth-agent-req@openssh.com)` + ); + } + sendPacket(this, this._packetRW.write.finalize(packet)); + } + openssh_hostKeysProve(keys) { + if (this._server) + throw new Error("Client-only method called in server mode"); + let keysTotal = 0; + const publicKeys = []; + for (const key of keys) { + const publicKey = key.getPublicSSH(); + keysTotal += 4 + publicKey.length; + publicKeys.push(publicKey); + } + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 29 + 1 + keysTotal); + packet[p] = MESSAGE.GLOBAL_REQUEST; + writeUInt32BE(packet, 29, ++p); + packet.utf8Write("hostkeys-prove-00@openssh.com", p += 4, 29); + packet[p += 29] = 1; + ++p; + for (const buf of publicKeys) { + writeUInt32BE(packet, buf.length, p); + bufferCopy(buf, packet, 0, buf.length, p += 4); + p += buf.length; + } + if (this._debug) { + this._debug( + "Outbound: Sending GLOBAL_REQUEST (hostkeys-prove-00@openssh.com)" + ); + } + sendPacket(this, this._packetRW.write.finalize(packet)); + } + // =========================================================================== + // Server-specific =========================================================== + // =========================================================================== + // Global + // ------ + serviceAccept(svcName) { + if (!this._server) + throw new Error("Server-only method called in client mode"); + const svcNameLen = Buffer.byteLength(svcName); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + svcNameLen); + packet[p] = MESSAGE.SERVICE_ACCEPT; + writeUInt32BE(packet, svcNameLen, ++p); + packet.utf8Write(svcName, p += 4, svcNameLen); + this._debug && this._debug(`Outbound: Sending SERVICE_ACCEPT (${svcName})`); + sendPacket(this, this._packetRW.write.finalize(packet)); + if (this._server && this._banner && svcName === "ssh-userauth") { + const banner = this._banner; + this._banner = void 0; + const bannerLen = Buffer.byteLength(banner); + p = this._packetRW.write.allocStart; + const packet2 = this._packetRW.write.alloc(1 + 4 + bannerLen + 4); + packet2[p] = MESSAGE.USERAUTH_BANNER; + writeUInt32BE(packet2, bannerLen, ++p); + packet2.utf8Write(banner, p += 4, bannerLen); + writeUInt32BE(packet2, 0, p += bannerLen); + this._debug && this._debug("Outbound: Sending USERAUTH_BANNER"); + sendPacket(this, this._packetRW.write.finalize(packet2)); + } + } + // 'ssh-connection' service-specific + forwardedTcpip(chan, initWindow, maxPacket, cfg) { + if (!this._server) + throw new Error("Server-only method called in client mode"); + const boundAddrLen = Buffer.byteLength(cfg.boundAddr); + const remoteAddrLen = Buffer.byteLength(cfg.remoteAddr); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 15 + 4 + 4 + 4 + 4 + boundAddrLen + 4 + 4 + remoteAddrLen + 4 + ); + packet[p] = MESSAGE.CHANNEL_OPEN; + writeUInt32BE(packet, 15, ++p); + packet.utf8Write("forwarded-tcpip", p += 4, 15); + writeUInt32BE(packet, chan, p += 15); + writeUInt32BE(packet, initWindow, p += 4); + writeUInt32BE(packet, maxPacket, p += 4); + writeUInt32BE(packet, boundAddrLen, p += 4); + packet.utf8Write(cfg.boundAddr, p += 4, boundAddrLen); + writeUInt32BE(packet, cfg.boundPort, p += boundAddrLen); + writeUInt32BE(packet, remoteAddrLen, p += 4); + packet.utf8Write(cfg.remoteAddr, p += 4, remoteAddrLen); + writeUInt32BE(packet, cfg.remotePort, p += remoteAddrLen); + this._debug && this._debug( + `Outbound: Sending CHANNEL_OPEN (r:${chan}, forwarded-tcpip)` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + x11(chan, initWindow, maxPacket, cfg) { + if (!this._server) + throw new Error("Server-only method called in client mode"); + const addrLen = Buffer.byteLength(cfg.originAddr); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 3 + 4 + 4 + 4 + 4 + addrLen + 4 + ); + packet[p] = MESSAGE.CHANNEL_OPEN; + writeUInt32BE(packet, 3, ++p); + packet.utf8Write("x11", p += 4, 3); + writeUInt32BE(packet, chan, p += 3); + writeUInt32BE(packet, initWindow, p += 4); + writeUInt32BE(packet, maxPacket, p += 4); + writeUInt32BE(packet, addrLen, p += 4); + packet.utf8Write(cfg.originAddr, p += 4, addrLen); + writeUInt32BE(packet, cfg.originPort, p += addrLen); + this._debug && this._debug( + `Outbound: Sending CHANNEL_OPEN (r:${chan}, x11)` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + openssh_authAgent(chan, initWindow, maxPacket) { + if (!this._server) + throw new Error("Server-only method called in client mode"); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 22 + 4 + 4 + 4); + packet[p] = MESSAGE.CHANNEL_OPEN; + writeUInt32BE(packet, 22, ++p); + packet.utf8Write("auth-agent@openssh.com", p += 4, 22); + writeUInt32BE(packet, chan, p += 22); + writeUInt32BE(packet, initWindow, p += 4); + writeUInt32BE(packet, maxPacket, p += 4); + this._debug && this._debug( + `Outbound: Sending CHANNEL_OPEN (r:${chan}, auth-agent@openssh.com)` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + openssh_forwardedStreamLocal(chan, initWindow, maxPacket, cfg) { + if (!this._server) + throw new Error("Server-only method called in client mode"); + const pathLen = Buffer.byteLength(cfg.socketPath); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 33 + 4 + 4 + 4 + 4 + pathLen + 4 + ); + packet[p] = MESSAGE.CHANNEL_OPEN; + writeUInt32BE(packet, 33, ++p); + packet.utf8Write("forwarded-streamlocal@openssh.com", p += 4, 33); + writeUInt32BE(packet, chan, p += 33); + writeUInt32BE(packet, initWindow, p += 4); + writeUInt32BE(packet, maxPacket, p += 4); + writeUInt32BE(packet, pathLen, p += 4); + packet.utf8Write(cfg.socketPath, p += 4, pathLen); + writeUInt32BE(packet, 0, p += pathLen); + if (this._debug) { + this._debug( + `Outbound: Sending CHANNEL_OPEN (r:${chan}, forwarded-streamlocal@openssh.com)` + ); + } + sendPacket(this, this._packetRW.write.finalize(packet)); + } + exitStatus(chan, status) { + if (!this._server) + throw new Error("Server-only method called in client mode"); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + 4 + 11 + 1 + 4); + packet[p] = MESSAGE.CHANNEL_REQUEST; + writeUInt32BE(packet, chan, ++p); + writeUInt32BE(packet, 11, p += 4); + packet.utf8Write("exit-status", p += 4, 11); + packet[p += 11] = 0; + writeUInt32BE(packet, status, ++p); + this._debug && this._debug( + `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-status: ${status})` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + exitSignal(chan, name, coreDumped, msg) { + if (!this._server) + throw new Error("Server-only method called in client mode"); + const origSignal = name; + if (typeof origSignal !== "string" || !origSignal) + throw new Error(`Invalid signal: ${origSignal}`); + let signal = name.toUpperCase(); + if (signal.slice(0, 3) === "SIG") + signal = signal.slice(3); + if (SIGNALS[signal] !== 1) + throw new Error(`Invalid signal: ${origSignal}`); + const nameLen = Buffer.byteLength(signal); + const msgLen = msg ? Buffer.byteLength(msg) : 0; + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + 4 + 11 + 1 + 4 + nameLen + 1 + 4 + msgLen + 4 + ); + packet[p] = MESSAGE.CHANNEL_REQUEST; + writeUInt32BE(packet, chan, ++p); + writeUInt32BE(packet, 11, p += 4); + packet.utf8Write("exit-signal", p += 4, 11); + packet[p += 11] = 0; + writeUInt32BE(packet, nameLen, ++p); + packet.utf8Write(signal, p += 4, nameLen); + packet[p += nameLen] = coreDumped ? 1 : 0; + writeUInt32BE(packet, msgLen, ++p); + p += 4; + if (msgLen) { + packet.utf8Write(msg, p, msgLen); + p += msgLen; + } + writeUInt32BE(packet, 0, p); + this._debug && this._debug( + `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-signal: ${name})` + ); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + // 'ssh-userauth' service-specific + authFailure(authMethods, isPartial) { + if (!this._server) + throw new Error("Server-only method called in client mode"); + if (this._authsQueue.length === 0) + throw new Error("No auth in progress"); + let methods; + if (typeof authMethods === "boolean") { + isPartial = authMethods; + authMethods = void 0; + } + if (authMethods) { + methods = []; + for (let i = 0; i < authMethods.length; ++i) { + if (authMethods[i].toLowerCase() === "none") + continue; + methods.push(authMethods[i]); + } + methods = methods.join(","); + } else { + methods = ""; + } + const methodsLen = methods.length; + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + methodsLen + 1); + packet[p] = MESSAGE.USERAUTH_FAILURE; + writeUInt32BE(packet, methodsLen, ++p); + packet.utf8Write(methods, p += 4, methodsLen); + packet[p += methodsLen] = isPartial === true ? 1 : 0; + this._authsQueue.shift(); + this._debug && this._debug("Outbound: Sending USERAUTH_FAILURE"); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + authSuccess() { + if (!this._server) + throw new Error("Server-only method called in client mode"); + if (this._authsQueue.length === 0) + throw new Error("No auth in progress"); + const p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1); + packet[p] = MESSAGE.USERAUTH_SUCCESS; + this._authsQueue.shift(); + this._authenticated = true; + this._debug && this._debug("Outbound: Sending USERAUTH_SUCCESS"); + sendPacket(this, this._packetRW.write.finalize(packet)); + if (this._kex.negotiated.cs.compress === "zlib@openssh.com") + this._packetRW.read = new ZlibPacketReader(); + if (this._kex.negotiated.sc.compress === "zlib@openssh.com") + this._packetRW.write = new ZlibPacketWriter(this); + } + authPKOK(keyAlgo, key) { + if (!this._server) + throw new Error("Server-only method called in client mode"); + if (this._authsQueue.length === 0 || this._authsQueue[0] !== "publickey") + throw new Error('"publickey" auth not in progress'); + const keyAlgoLen = Buffer.byteLength(keyAlgo); + const keyLen = key.length; + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + keyAlgoLen + 4 + keyLen); + packet[p] = MESSAGE.USERAUTH_PK_OK; + writeUInt32BE(packet, keyAlgoLen, ++p); + packet.utf8Write(keyAlgo, p += 4, keyAlgoLen); + writeUInt32BE(packet, keyLen, p += keyAlgoLen); + packet.set(key, p += 4); + this._authsQueue.shift(); + this._debug && this._debug("Outbound: Sending USERAUTH_PK_OK"); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + authPasswdChg(prompt) { + if (!this._server) + throw new Error("Server-only method called in client mode"); + const promptLen = Buffer.byteLength(prompt); + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc(1 + 4 + promptLen + 4); + packet[p] = MESSAGE.USERAUTH_PASSWD_CHANGEREQ; + writeUInt32BE(packet, promptLen, ++p); + packet.utf8Write(prompt, p += 4, promptLen); + writeUInt32BE(packet, 0, p += promptLen); + this._debug && this._debug("Outbound: Sending USERAUTH_PASSWD_CHANGEREQ"); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + authInfoReq(name, instructions, prompts) { + if (!this._server) + throw new Error("Server-only method called in client mode"); + let promptsLen = 0; + const nameLen = name ? Buffer.byteLength(name) : 0; + const instrLen = instructions ? Buffer.byteLength(instructions) : 0; + for (let i = 0; i < prompts.length; ++i) + promptsLen += 4 + Buffer.byteLength(prompts[i].prompt) + 1; + let p = this._packetRW.write.allocStart; + const packet = this._packetRW.write.alloc( + 1 + 4 + nameLen + 4 + instrLen + 4 + 4 + promptsLen + ); + packet[p] = MESSAGE.USERAUTH_INFO_REQUEST; + writeUInt32BE(packet, nameLen, ++p); + p += 4; + if (name) { + packet.utf8Write(name, p, nameLen); + p += nameLen; + } + writeUInt32BE(packet, instrLen, p); + p += 4; + if (instructions) { + packet.utf8Write(instructions, p, instrLen); + p += instrLen; + } + writeUInt32BE(packet, 0, p); + writeUInt32BE(packet, prompts.length, p += 4); + p += 4; + for (let i = 0; i < prompts.length; ++i) { + const prompt = prompts[i]; + const promptLen = Buffer.byteLength(prompt.prompt); + writeUInt32BE(packet, promptLen, p); + p += 4; + if (promptLen) { + packet.utf8Write(prompt.prompt, p, promptLen); + p += promptLen; + } + packet[p++] = prompt.echo ? 1 : 0; + } + this._debug && this._debug("Outbound: Sending USERAUTH_INFO_REQUEST"); + sendPacket(this, this._packetRW.write.finalize(packet)); + } + }; + var RE_IDENT = /^SSH-(2\.0|1\.99)-([^ ]+)(?: (.*))?$/; + function parseHeader(chunk, p, len) { + let data; + let chunkOffset; + if (this._buffer) { + data = Buffer.allocUnsafe(this._buffer.length + (len - p)); + data.set(this._buffer, 0); + if (p === 0) { + data.set(chunk, this._buffer.length); + } else { + data.set( + new Uint8Array( + chunk.buffer, + chunk.byteOffset + p, + len - p + ), + this._buffer.length + ); + } + chunkOffset = this._buffer.length; + p = 0; + } else { + data = chunk; + chunkOffset = 0; + } + const op = p; + let start = p; + let end = p; + let needNL = false; + let lineLen = 0; + let lines = 0; + for (; p < data.length; ++p) { + const ch = data[p]; + if (ch === 13) { + needNL = true; + continue; + } + if (ch === 10) { + if (end > start && end - start > 4 && data[start] === 83 && data[start + 1] === 83 && data[start + 2] === 72 && data[start + 3] === 45) { + const full = data.latin1Slice(op, end + 1); + const identRaw = start === op ? full : full.slice(start - op); + const m = RE_IDENT.exec(identRaw); + if (!m) + throw new Error("Invalid identification string"); + const header = { + greeting: start === op ? "" : full.slice(0, start - op), + identRaw, + versions: { + protocol: m[1], + software: m[2] + }, + comments: m[3] + }; + this._remoteIdentRaw = Buffer.from(identRaw); + this._debug && this._debug(`Remote ident: ${inspect(identRaw)}`); + this._compatFlags = getCompatFlags(header); + this._buffer = void 0; + this._decipher = new NullDecipher(0, onKEXPayload.bind(this, { firstPacket: true })); + this._parse = parsePacket; + this._onHeader(header); + if (!this._destruct) { + return len; + } + kexinit(this); + return p + 1 - chunkOffset; + } + if (this._server) + throw new Error("Greetings from clients not permitted"); + if (++lines > MAX_LINES) + throw new Error("Max greeting lines exceeded"); + needNL = false; + start = p + 1; + lineLen = 0; + } else if (needNL) { + throw new Error("Invalid header: expected newline"); + } else if (++lineLen >= MAX_LINE_LEN) { + throw new Error("Header line too long"); + } + end = p; + } + if (!this._buffer) + this._buffer = bufferSlice(data, op); + return p - chunkOffset; + } + function parsePacket(chunk, p, len) { + return this._decipher.decrypt(chunk, p, len); + } + function onPayload(payload) { + this._onPacket(); + if (payload.length === 0) { + this._debug && this._debug("Inbound: Skipping empty packet payload"); + return; + } + payload = this._packetRW.read.read(payload); + const type = payload[0]; + if (type === MESSAGE.USERAUTH_SUCCESS && !this._server && !this._authenticated) { + this._authenticated = true; + if (this._kex.negotiated.cs.compress === "zlib@openssh.com") + this._packetRW.write = new ZlibPacketWriter(this); + if (this._kex.negotiated.sc.compress === "zlib@openssh.com") + this._packetRW.read = new ZlibPacketReader(); + } + const handler2 = MESSAGE_HANDLERS[type]; + if (handler2 === void 0) { + this._debug && this._debug(`Inbound: Unsupported message type: ${type}`); + return; + } + return handler2(this, payload); + } + function getCompatFlags(header) { + const software = header.versions.software; + let flags = 0; + for (const rule of COMPAT_CHECKS) { + if (typeof rule[0] === "string") { + if (software === rule[0]) + flags |= rule[1]; + } else if (rule[0].test(software)) { + flags |= rule[1]; + } + } + return flags; + } + function modesToBytes(modes) { + const keys = Object.keys(modes); + const bytes = Buffer.allocUnsafe(5 * keys.length + 1); + let b = 0; + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (key === "TTY_OP_END") + continue; + const opcode = TERMINAL_MODE[key]; + if (opcode === void 0) + continue; + const val = modes[key]; + if (typeof val === "number" && isFinite(val)) { + bytes[b++] = opcode; + bytes[b++] = val >>> 24; + bytes[b++] = val >>> 16; + bytes[b++] = val >>> 8; + bytes[b++] = val; + } + } + bytes[b++] = TERMINAL_MODE.TTY_OP_END; + if (b < bytes.length) + return bufferSlice(bytes, 0, b); + return bytes; + } + function sendExtInfo(proto) { + let serverSigAlgs = "ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521rsa-sha2-512,rsa-sha2-256,ssh-rsa,ssh-dss"; + if (eddsaSupported) + serverSigAlgs = `ssh-ed25519,${serverSigAlgs}`; + const algsLen = Buffer.byteLength(serverSigAlgs); + let p = proto._packetRW.write.allocStart; + const packet = proto._packetRW.write.alloc(1 + 4 + 4 + 15 + 4 + algsLen); + packet[p] = MESSAGE.EXT_INFO; + writeUInt32BE(packet, 1, ++p); + writeUInt32BE(packet, 15, p += 4); + packet.utf8Write("server-sig-algs", p += 4, 15); + writeUInt32BE(packet, algsLen, p += 15); + packet.utf8Write(serverSigAlgs, p += 4, algsLen); + proto._debug && proto._debug("Outbound: Sending EXT_INFO"); + sendPacket(proto, proto._packetRW.write.finalize(packet)); + } + module2.exports = Protocol; + } +}); + +// node_modules/ssh2/lib/protocol/node-fs-compat.js +var require_node_fs_compat = __commonJS({ + "node_modules/ssh2/lib/protocol/node-fs-compat.js"(exports2) { + "use strict"; + var assert = require("assert"); + var { inspect } = require("util"); + function addNumericalSeparator(val) { + let res = ""; + let i = val.length; + const start = val[0] === "-" ? 1 : 0; + for (; i >= start + 4; i -= 3) + res = `_${val.slice(i - 3, i)}${res}`; + return `${val.slice(0, i)}${res}`; + } + function oneOf(expected, thing) { + assert(typeof thing === "string", "`thing` has to be of type string"); + if (Array.isArray(expected)) { + const len = expected.length; + assert(len > 0, "At least one expected value needs to be specified"); + 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]}`; + } + return `of ${thing} ${expected[0]}`; + } + return `of ${thing} ${String(expected)}`; + } + exports2.ERR_INTERNAL_ASSERTION = class ERR_INTERNAL_ASSERTION extends Error { + constructor(message) { + super(); + Error.captureStackTrace(this, ERR_INTERNAL_ASSERTION); + const suffix = "This is caused by either a bug in ssh2 or incorrect usage of ssh2 internals.\nPlease open an issue with this stack trace at https://github.com/mscdex/ssh2/issues\n"; + this.message = message === void 0 ? suffix : `${message} +${suffix}`; + } + }; + var MAX_32BIT_INT = 2 ** 32; + var MAX_32BIT_BIGINT = (() => { + try { + return new Function("return 2n ** 32n")(); + } catch { + } + })(); + exports2.ERR_OUT_OF_RANGE = class ERR_OUT_OF_RANGE extends RangeError { + constructor(str, range, input, replaceDefaultBoolean) { + super(); + Error.captureStackTrace(this, ERR_OUT_OF_RANGE); + assert(range, 'Missing "range" argument'); + let msg = replaceDefaultBoolean ? str : `The value of "${str}" is out of range.`; + let received; + if (Number.isInteger(input) && Math.abs(input) > MAX_32BIT_INT) { + received = addNumericalSeparator(String(input)); + } else if (typeof input === "bigint") { + received = String(input); + if (input > MAX_32BIT_BIGINT || input < -MAX_32BIT_BIGINT) + received = addNumericalSeparator(received); + received += "n"; + } else { + received = inspect(input); + } + msg += ` It must be ${range}. Received ${received}`; + this.message = msg; + } + }; + var ERR_INVALID_ARG_TYPE = class _ERR_INVALID_ARG_TYPE extends TypeError { + constructor(name, expected, actual) { + super(); + Error.captureStackTrace(this, _ERR_INVALID_ARG_TYPE); + assert(typeof name === "string", `'name' must be a string`); + let determiner; + if (typeof expected === "string" && expected.startsWith("not ")) { + determiner = "must not be"; + expected = expected.replace(/^not /, ""); + } else { + determiner = "must be"; + } + let msg; + if (name.endsWith(" argument")) { + msg = `The ${name} ${determiner} ${oneOf(expected, "type")}`; + } else { + const type = name.includes(".") ? "property" : "argument"; + msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, "type")}`; + } + msg += `. Received type ${typeof actual}`; + this.message = msg; + } + }; + exports2.ERR_INVALID_ARG_TYPE = ERR_INVALID_ARG_TYPE; + exports2.validateNumber = function validateNumber(value, name) { + if (typeof value !== "number") + throw new ERR_INVALID_ARG_TYPE(name, "number", value); + }; + } +}); + +// node_modules/ssh2/lib/protocol/SFTP.js +var require_SFTP = __commonJS({ + "node_modules/ssh2/lib/protocol/SFTP.js"(exports2, module2) { + "use strict"; + var EventEmitter = require("events"); + var fs4 = require("fs"); + var { constants: constants3 } = fs4; + var { + Readable: ReadableStream2, + Writable: WritableStream + } = require("stream"); + var { inherits, types: { isDate } } = require("util"); + var FastBuffer = Buffer[Symbol.species]; + var { + bufferCopy, + bufferSlice, + makeBufferParser, + writeUInt32BE + } = require_utils3(); + var ATTR = { + SIZE: 1, + UIDGID: 2, + PERMISSIONS: 4, + ACMODTIME: 8, + EXTENDED: 2147483648 + }; + var ATTRS_BUF = Buffer.alloc(28); + var STATUS_CODE = { + OK: 0, + EOF: 1, + NO_SUCH_FILE: 2, + PERMISSION_DENIED: 3, + FAILURE: 4, + BAD_MESSAGE: 5, + NO_CONNECTION: 6, + CONNECTION_LOST: 7, + OP_UNSUPPORTED: 8 + }; + var VALID_STATUS_CODES = new Map( + Object.values(STATUS_CODE).map((n) => [n, 1]) + ); + var STATUS_CODE_STR = { + [STATUS_CODE.OK]: "No error", + [STATUS_CODE.EOF]: "End of file", + [STATUS_CODE.NO_SUCH_FILE]: "No such file or directory", + [STATUS_CODE.PERMISSION_DENIED]: "Permission denied", + [STATUS_CODE.FAILURE]: "Failure", + [STATUS_CODE.BAD_MESSAGE]: "Bad message", + [STATUS_CODE.NO_CONNECTION]: "No connection", + [STATUS_CODE.CONNECTION_LOST]: "Connection lost", + [STATUS_CODE.OP_UNSUPPORTED]: "Operation unsupported" + }; + var REQUEST = { + INIT: 1, + OPEN: 3, + CLOSE: 4, + READ: 5, + WRITE: 6, + LSTAT: 7, + FSTAT: 8, + SETSTAT: 9, + FSETSTAT: 10, + OPENDIR: 11, + READDIR: 12, + REMOVE: 13, + MKDIR: 14, + RMDIR: 15, + REALPATH: 16, + STAT: 17, + RENAME: 18, + READLINK: 19, + SYMLINK: 20, + EXTENDED: 200 + }; + var RESPONSE = { + VERSION: 2, + STATUS: 101, + HANDLE: 102, + DATA: 103, + NAME: 104, + ATTRS: 105, + EXTENDED: 201 + }; + var OPEN_MODE = { + READ: 1, + WRITE: 2, + APPEND: 4, + CREAT: 8, + TRUNC: 16, + EXCL: 32 + }; + var PKT_RW_OVERHEAD = 2 * 1024; + var MAX_REQID = 2 ** 32 - 1; + var CLIENT_VERSION_BUFFER = Buffer.from([ + 0, + 0, + 0, + 5, + REQUEST.INIT, + 0, + 0, + 0, + 3 + /* version */ + ]); + var SERVER_VERSION_BUFFER = Buffer.from([ + 0, + 0, + 0, + 5, + RESPONSE.VERSION, + 0, + 0, + 0, + 3 + /* version */ + ]); + var RE_OPENSSH = /^SSH-2.0-(?:OpenSSH|dropbear)/; + var OPENSSH_MAX_PKT_LEN = 256 * 1024; + var bufferParser = makeBufferParser(); + var fakeStderr = { + readable: false, + writable: false, + push: (data) => { + }, + once: () => { + }, + on: () => { + }, + emit: () => { + }, + end: () => { + } + }; + function noop3() { + } + var SFTP = class extends EventEmitter { + constructor(client, chanInfo, cfg) { + super(); + if (typeof cfg !== "object" || !cfg) + cfg = {}; + const remoteIdentRaw = client._protocol._remoteIdentRaw; + this.server = !!cfg.server; + this._debug = typeof cfg.debug === "function" ? cfg.debug : void 0; + this._isOpenSSH = remoteIdentRaw && RE_OPENSSH.test(remoteIdentRaw); + this._version = -1; + this._extensions = {}; + this._biOpt = cfg.biOpt; + this._pktLenBytes = 0; + this._pktLen = 0; + this._pktPos = 0; + this._pktType = 0; + this._pktData = void 0; + this._writeReqid = -1; + this._requests = {}; + this._maxInPktLen = OPENSSH_MAX_PKT_LEN; + this._maxOutPktLen = 34e3; + this._maxReadLen = (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34e3) - PKT_RW_OVERHEAD; + this._maxWriteLen = (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34e3) - PKT_RW_OVERHEAD; + this.maxOpenHandles = void 0; + this._client = client; + this._protocol = client._protocol; + this._callbacks = []; + this._hasX11 = false; + this._exit = { + code: void 0, + signal: void 0, + dump: void 0, + desc: void 0 + }; + this._waitWindow = false; + this._chunkcb = void 0; + this._buffer = []; + this.type = chanInfo.type; + this.subtype = void 0; + this.incoming = chanInfo.incoming; + this.outgoing = chanInfo.outgoing; + this.stderr = fakeStderr; + this.readable = true; + } + // This handles incoming data to parse + push(data) { + if (data === null) { + cleanupRequests(this); + if (!this.readable) + return; + this.readable = false; + this.emit("end"); + return; + } + let p = 0; + while (p < data.length) { + if (this._pktLenBytes < 4) { + let nb = Math.min(4 - this._pktLenBytes, data.length - p); + this._pktLenBytes += nb; + while (nb--) + this._pktLen = (this._pktLen << 8) + data[p++]; + if (this._pktLenBytes < 4) + return; + if (this._pktLen === 0) + return doFatalSFTPError(this, "Invalid packet length"); + if (this._pktLen > this._maxInPktLen) { + const max = this._maxInPktLen; + return doFatalSFTPError( + this, + `Packet length ${this._pktLen} exceeds max length of ${max}` + ); + } + if (p >= data.length) + return; + } + if (this._pktPos < this._pktLen) { + const nb = Math.min(this._pktLen - this._pktPos, data.length - p); + if (p !== 0 || nb !== data.length) { + if (nb === this._pktLen) { + this._pkt = new FastBuffer(data.buffer, data.byteOffset + p, nb); + } else { + if (!this._pkt) + this._pkt = Buffer.allocUnsafe(this._pktLen); + this._pkt.set( + new Uint8Array(data.buffer, data.byteOffset + p, nb), + this._pktPos + ); + } + } else if (nb === this._pktLen) { + this._pkt = data; + } else { + if (!this._pkt) + this._pkt = Buffer.allocUnsafe(this._pktLen); + this._pkt.set(data, this._pktPos); + } + p += nb; + this._pktPos += nb; + if (this._pktPos < this._pktLen) + return; + } + const type = this._pkt[0]; + const payload = this._pkt; + this._pktLen = 0; + this._pktLenBytes = 0; + this._pkt = void 0; + this._pktPos = 0; + const handler2 = this.server ? SERVER_HANDLERS[type] : CLIENT_HANDLERS[type]; + if (!handler2) + return doFatalSFTPError(this, `Unknown packet type ${type}`); + if (this._version === -1) { + if (this.server) { + if (type !== REQUEST.INIT) + return doFatalSFTPError(this, `Expected INIT packet, got ${type}`); + } else if (type !== RESPONSE.VERSION) { + return doFatalSFTPError(this, `Expected VERSION packet, got ${type}`); + } + } + if (handler2(this, payload) === false) + return; + } + } + end() { + this.destroy(); + } + destroy() { + if (this.outgoing.state === "open" || this.outgoing.state === "eof") { + this.outgoing.state = "closing"; + this._protocol.channelClose(this.outgoing.id); + } + } + _init() { + this._init = noop3; + if (!this.server) + sendOrBuffer(this, CLIENT_VERSION_BUFFER); + } + // =========================================================================== + // Client-specific =========================================================== + // =========================================================================== + createReadStream(path, options) { + if (this.server) + throw new Error("Client-only method called in server mode"); + return new ReadStream(this, path, options); + } + createWriteStream(path, options) { + if (this.server) + throw new Error("Client-only method called in server mode"); + return new WriteStream(this, path, options); + } + open(path, flags_, attrs, cb) { + if (this.server) + throw new Error("Client-only method called in server mode"); + if (typeof attrs === "function") { + cb = attrs; + attrs = void 0; + } + const flags = typeof flags_ === "number" ? flags_ : stringToFlags(flags_); + if (flags === null) + throw new Error(`Unknown flags string: ${flags_}`); + let attrsFlags = 0; + let attrsLen = 0; + if (typeof attrs === "string" || typeof attrs === "number") + attrs = { mode: attrs }; + if (typeof attrs === "object" && attrs !== null) { + attrs = attrsToBytes(attrs); + attrsFlags = attrs.flags; + attrsLen = attrs.nb; + } + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + 4 + attrsLen); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.OPEN; + const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; + writeUInt32BE(buf, reqid, 5); + writeUInt32BE(buf, pathLen, p); + buf.utf8Write(path, p += 4, pathLen); + writeUInt32BE(buf, flags, p += pathLen); + writeUInt32BE(buf, attrsFlags, p += 4); + if (attrsLen) { + p += 4; + if (attrsLen === ATTRS_BUF.length) + buf.set(ATTRS_BUF, p); + else + bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); + p += attrsLen; + } + this._requests[reqid] = { cb }; + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} OPEN` + ); + } + close(handle, cb) { + if (this.server) + throw new Error("Client-only method called in server mode"); + if (!Buffer.isBuffer(handle)) + throw new Error("handle is not a Buffer"); + const handleLen = handle.length; + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.CLOSE; + const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; + writeUInt32BE(buf, reqid, 5); + writeUInt32BE(buf, handleLen, p); + buf.set(handle, p += 4); + this._requests[reqid] = { cb }; + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} CLOSE` + ); + } + read(handle, buf, off, len, position, cb) { + if (this.server) + throw new Error("Client-only method called in server mode"); + if (!Buffer.isBuffer(handle)) + throw new Error("handle is not a Buffer"); + if (!Buffer.isBuffer(buf)) + throw new Error("buffer is not a Buffer"); + if (off >= buf.length) + throw new Error("offset is out of bounds"); + if (off + len > buf.length) + throw new Error("length extends beyond buffer"); + if (position === null) + throw new Error("null position currently unsupported"); + read_(this, handle, buf, off, len, position, cb); + } + readData(handle, buf, off, len, position, cb) { + this.read(handle, buf, off, len, position, cb); + } + write(handle, buf, off, len, position, cb) { + if (this.server) + throw new Error("Client-only method called in server mode"); + if (!Buffer.isBuffer(handle)) + throw new Error("handle is not a Buffer"); + if (!Buffer.isBuffer(buf)) + throw new Error("buffer is not a Buffer"); + if (off > buf.length) + throw new Error("offset is out of bounds"); + if (off + len > buf.length) + throw new Error("length extends beyond buffer"); + if (position === null) + throw new Error("null position currently unsupported"); + if (!len) { + cb && process.nextTick(cb, void 0, 0); + return; + } + const maxDataLen = this._maxWriteLen; + const overflow = Math.max(len - maxDataLen, 0); + const origPosition = position; + if (overflow) + len = maxDataLen; + const handleLen = handle.length; + let p = 9; + const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4 + len); + writeUInt32BE(out, out.length - 4, 0); + out[4] = REQUEST.WRITE; + const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; + writeUInt32BE(out, reqid, 5); + writeUInt32BE(out, handleLen, p); + out.set(handle, p += 4); + p += handleLen; + for (let i = 7; i >= 0; --i) { + out[p + i] = position & 255; + position /= 256; + } + writeUInt32BE(out, len, p += 8); + bufferCopy(buf, out, off, off + len, p += 4); + this._requests[reqid] = { + cb: (err) => { + if (err) { + if (typeof cb === "function") + cb(err); + } else if (overflow) { + this.write( + handle, + buf, + off + len, + overflow, + origPosition + len, + cb + ); + } else if (typeof cb === "function") { + cb(void 0, off + len); + } + } + }; + const isSent = sendOrBuffer(this, out); + if (this._debug) { + const how = isSent ? "Sent" : "Buffered"; + this._debug(`SFTP: Outbound: ${how} WRITE (id:${reqid})`); + } + } + writeData(handle, buf, off, len, position, cb) { + this.write(handle, buf, off, len, position, cb); + } + fastGet(remotePath, localPath, opts, cb) { + if (this.server) + throw new Error("Client-only method called in server mode"); + fastXfer(this, fs4, remotePath, localPath, opts, cb); + } + fastPut(localPath, remotePath, opts, cb) { + if (this.server) + throw new Error("Client-only method called in server mode"); + fastXfer(fs4, this, localPath, remotePath, opts, cb); + } + readFile(path, options, callback_) { + if (this.server) + throw new Error("Client-only method called in server mode"); + let callback; + if (typeof callback_ === "function") { + callback = callback_; + } else if (typeof options === "function") { + callback = options; + options = void 0; + } + if (typeof options === "string") + options = { encoding: options, flag: "r" }; + else if (!options) + options = { encoding: null, flag: "r" }; + else if (typeof options !== "object") + throw new TypeError("Bad arguments"); + const encoding = options.encoding; + if (encoding && !Buffer.isEncoding(encoding)) + throw new Error(`Unknown encoding: ${encoding}`); + let size; + let buffer; + let buffers; + let pos = 0; + let handle; + let bytesRead = 0; + const flag = options.flag || "r"; + const read = () => { + if (size === 0) { + buffer = Buffer.allocUnsafe(8192); + this.read(handle, buffer, 0, 8192, bytesRead, afterRead); + } else { + this.read(handle, buffer, pos, size - pos, bytesRead, afterRead); + } + }; + const afterRead = (er, nbytes) => { + let eof; + if (er) { + eof = er.code === STATUS_CODE.EOF; + if (!eof) { + return this.close(handle, () => { + return callback && callback(er); + }); + } + } else { + eof = false; + } + if (eof || size === 0 && nbytes === 0) + return close(); + bytesRead += nbytes; + pos += nbytes; + if (size !== 0) { + if (pos === size) + close(); + else + read(); + } else { + buffers.push(bufferSlice(buffer, 0, nbytes)); + read(); + } + }; + afterRead._wantEOFError = true; + const close = () => { + this.close(handle, (er) => { + if (size === 0) { + buffer = Buffer.concat(buffers, pos); + } else if (pos < size) { + buffer = bufferSlice(buffer, 0, pos); + } + if (encoding) + buffer = buffer.toString(encoding); + return callback && callback(er, buffer); + }); + }; + this.open(path, flag, 438, (er, handle_) => { + if (er) + return callback && callback(er); + handle = handle_; + const tryStat = (er2, st) => { + if (er2) { + this.stat(path, (er_, st_) => { + if (er_) { + return this.close(handle, () => { + callback && callback(er2); + }); + } + tryStat(null, st_); + }); + return; + } + size = st.size || 0; + if (size === 0) { + buffers = []; + return read(); + } + buffer = Buffer.allocUnsafe(size); + read(); + }; + this.fstat(handle, tryStat); + }); + } + writeFile(path, data, options, callback_) { + if (this.server) + throw new Error("Client-only method called in server mode"); + let callback; + if (typeof callback_ === "function") { + callback = callback_; + } else if (typeof options === "function") { + callback = options; + options = void 0; + } + if (typeof options === "string") + options = { encoding: options, mode: 438, flag: "w" }; + else if (!options) + options = { encoding: "utf8", mode: 438, flag: "w" }; + else if (typeof options !== "object") + throw new TypeError("Bad arguments"); + if (options.encoding && !Buffer.isEncoding(options.encoding)) + throw new Error(`Unknown encoding: ${options.encoding}`); + const flag = options.flag || "w"; + this.open(path, flag, options.mode, (openErr, handle) => { + if (openErr) { + callback && callback(openErr); + } else { + const buffer = Buffer.isBuffer(data) ? data : Buffer.from("" + data, options.encoding || "utf8"); + const position = /a/.test(flag) ? null : 0; + if (position === null) { + const tryStat = (er, st) => { + if (er) { + this.stat(path, (er_, st_) => { + if (er_) { + return this.close(handle, () => { + callback && callback(er); + }); + } + tryStat(null, st_); + }); + return; + } + writeAll(this, handle, buffer, 0, buffer.length, st.size, callback); + }; + this.fstat(handle, tryStat); + return; + } + writeAll(this, handle, buffer, 0, buffer.length, position, callback); + } + }); + } + appendFile(path, data, options, callback_) { + if (this.server) + throw new Error("Client-only method called in server mode"); + let callback; + if (typeof callback_ === "function") { + callback = callback_; + } else if (typeof options === "function") { + callback = options; + options = void 0; + } + if (typeof options === "string") + options = { encoding: options, mode: 438, flag: "a" }; + else if (!options) + options = { encoding: "utf8", mode: 438, flag: "a" }; + else if (typeof options !== "object") + throw new TypeError("Bad arguments"); + if (!options.flag) + options = Object.assign({ flag: "a" }, options); + this.writeFile(path, data, options, callback); + } + exists(path, cb) { + if (this.server) + throw new Error("Client-only method called in server mode"); + this.stat(path, (err) => { + cb && cb(err ? false : true); + }); + } + unlink(filename, cb) { + if (this.server) + throw new Error("Client-only method called in server mode"); + const fnameLen = Buffer.byteLength(filename); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + fnameLen); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.REMOVE; + const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; + writeUInt32BE(buf, reqid, 5); + writeUInt32BE(buf, fnameLen, p); + buf.utf8Write(filename, p += 4, fnameLen); + this._requests[reqid] = { cb }; + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} REMOVE` + ); + } + rename(oldPath, newPath, cb) { + if (this.server) + throw new Error("Client-only method called in server mode"); + const oldLen = Buffer.byteLength(oldPath); + const newLen = Buffer.byteLength(newPath); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + oldLen + 4 + newLen); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.RENAME; + const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; + writeUInt32BE(buf, reqid, 5); + writeUInt32BE(buf, oldLen, p); + buf.utf8Write(oldPath, p += 4, oldLen); + writeUInt32BE(buf, newLen, p += oldLen); + buf.utf8Write(newPath, p += 4, newLen); + this._requests[reqid] = { cb }; + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} RENAME` + ); + } + mkdir(path, attrs, cb) { + if (this.server) + throw new Error("Client-only method called in server mode"); + let flags = 0; + let attrsLen = 0; + if (typeof attrs === "function") { + cb = attrs; + attrs = void 0; + } + if (typeof attrs === "object" && attrs !== null) { + attrs = attrsToBytes(attrs); + flags = attrs.flags; + attrsLen = attrs.nb; + } + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.MKDIR; + const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; + writeUInt32BE(buf, reqid, 5); + writeUInt32BE(buf, pathLen, p); + buf.utf8Write(path, p += 4, pathLen); + writeUInt32BE(buf, flags, p += pathLen); + if (attrsLen) { + p += 4; + if (attrsLen === ATTRS_BUF.length) + buf.set(ATTRS_BUF, p); + else + bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); + p += attrsLen; + } + this._requests[reqid] = { cb }; + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} MKDIR` + ); + } + rmdir(path, cb) { + if (this.server) + throw new Error("Client-only method called in server mode"); + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.RMDIR; + const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; + writeUInt32BE(buf, reqid, 5); + writeUInt32BE(buf, pathLen, p); + buf.utf8Write(path, p += 4, pathLen); + this._requests[reqid] = { cb }; + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} RMDIR` + ); + } + readdir(where, opts, cb) { + if (this.server) + throw new Error("Client-only method called in server mode"); + if (typeof opts === "function") { + cb = opts; + opts = {}; + } + if (typeof opts !== "object" || opts === null) + opts = {}; + const doFilter = opts && opts.full ? false : true; + if (!Buffer.isBuffer(where) && typeof where !== "string") + throw new Error("missing directory handle or path"); + if (typeof where === "string") { + const entries = []; + let e = 0; + const reread = (err, handle) => { + if (err) + return cb(err); + this.readdir(handle, opts, (err2, list) => { + const eof = err2 && err2.code === STATUS_CODE.EOF; + if (err2 && !eof) + return this.close(handle, () => cb(err2)); + if (eof) { + return this.close(handle, (err3) => { + if (err3) + return cb(err3); + cb(void 0, entries); + }); + } + for (let i = 0; i < list.length; ++i, ++e) + entries[e] = list[i]; + reread(void 0, handle); + }); + }; + return this.opendir(where, reread); + } + const handleLen = where.length; + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.READDIR; + const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; + writeUInt32BE(buf, reqid, 5); + writeUInt32BE(buf, handleLen, p); + buf.set(where, p += 4); + this._requests[reqid] = { + cb: doFilter ? (err, list) => { + if (typeof cb !== "function") + return; + if (err) + return cb(err); + for (let i = list.length - 1; i >= 0; --i) { + if (list[i].filename === "." || list[i].filename === "..") + list.splice(i, 1); + } + cb(void 0, list); + } : cb + }; + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} READDIR` + ); + } + fstat(handle, cb) { + if (this.server) + throw new Error("Client-only method called in server mode"); + if (!Buffer.isBuffer(handle)) + throw new Error("handle is not a Buffer"); + const handleLen = handle.length; + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.FSTAT; + const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; + writeUInt32BE(buf, reqid, 5); + writeUInt32BE(buf, handleLen, p); + buf.set(handle, p += 4); + this._requests[reqid] = { cb }; + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} FSTAT` + ); + } + stat(path, cb) { + if (this.server) + throw new Error("Client-only method called in server mode"); + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.STAT; + const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; + writeUInt32BE(buf, reqid, 5); + writeUInt32BE(buf, pathLen, p); + buf.utf8Write(path, p += 4, pathLen); + this._requests[reqid] = { cb }; + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} STAT` + ); + } + lstat(path, cb) { + if (this.server) + throw new Error("Client-only method called in server mode"); + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.LSTAT; + const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; + writeUInt32BE(buf, reqid, 5); + writeUInt32BE(buf, pathLen, p); + buf.utf8Write(path, p += 4, pathLen); + this._requests[reqid] = { cb }; + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} LSTAT` + ); + } + opendir(path, cb) { + if (this.server) + throw new Error("Client-only method called in server mode"); + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.OPENDIR; + const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; + writeUInt32BE(buf, reqid, 5); + writeUInt32BE(buf, pathLen, p); + buf.utf8Write(path, p += 4, pathLen); + this._requests[reqid] = { cb }; + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} OPENDIR` + ); + } + setstat(path, attrs, cb) { + if (this.server) + throw new Error("Client-only method called in server mode"); + let flags = 0; + let attrsLen = 0; + if (typeof attrs === "object" && attrs !== null) { + attrs = attrsToBytes(attrs); + flags = attrs.flags; + attrsLen = attrs.nb; + } else if (typeof attrs === "function") { + cb = attrs; + } + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.SETSTAT; + const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; + writeUInt32BE(buf, reqid, 5); + writeUInt32BE(buf, pathLen, p); + buf.utf8Write(path, p += 4, pathLen); + writeUInt32BE(buf, flags, p += pathLen); + if (attrsLen) { + p += 4; + if (attrsLen === ATTRS_BUF.length) + buf.set(ATTRS_BUF, p); + else + bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); + p += attrsLen; + } + this._requests[reqid] = { cb }; + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} SETSTAT` + ); + } + fsetstat(handle, attrs, cb) { + if (this.server) + throw new Error("Client-only method called in server mode"); + if (!Buffer.isBuffer(handle)) + throw new Error("handle is not a Buffer"); + let flags = 0; + let attrsLen = 0; + if (typeof attrs === "object" && attrs !== null) { + attrs = attrsToBytes(attrs); + flags = attrs.flags; + attrsLen = attrs.nb; + } else if (typeof attrs === "function") { + cb = attrs; + } + const handleLen = handle.length; + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 4 + attrsLen); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.FSETSTAT; + const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; + writeUInt32BE(buf, reqid, 5); + writeUInt32BE(buf, handleLen, p); + buf.set(handle, p += 4); + writeUInt32BE(buf, flags, p += handleLen); + if (attrsLen) { + p += 4; + if (attrsLen === ATTRS_BUF.length) + buf.set(ATTRS_BUF, p); + else + bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); + p += attrsLen; + } + this._requests[reqid] = { cb }; + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} FSETSTAT` + ); + } + futimes(handle, atime, mtime, cb) { + return this.fsetstat(handle, { + atime: toUnixTimestamp(atime), + mtime: toUnixTimestamp(mtime) + }, cb); + } + utimes(path, atime, mtime, cb) { + return this.setstat(path, { + atime: toUnixTimestamp(atime), + mtime: toUnixTimestamp(mtime) + }, cb); + } + fchown(handle, uid, gid, cb) { + return this.fsetstat(handle, { + uid, + gid + }, cb); + } + chown(path, uid, gid, cb) { + return this.setstat(path, { + uid, + gid + }, cb); + } + fchmod(handle, mode, cb) { + return this.fsetstat(handle, { + mode + }, cb); + } + chmod(path, mode, cb) { + return this.setstat(path, { + mode + }, cb); + } + readlink(path, cb) { + if (this.server) + throw new Error("Client-only method called in server mode"); + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.READLINK; + const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; + writeUInt32BE(buf, reqid, 5); + writeUInt32BE(buf, pathLen, p); + buf.utf8Write(path, p += 4, pathLen); + this._requests[reqid] = { + cb: (err, names) => { + if (typeof cb !== "function") + return; + if (err) + return cb(err); + if (!names || !names.length) + return cb(new Error("Response missing link info")); + cb(void 0, names[0].filename); + } + }; + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} READLINK` + ); + } + symlink(targetPath, linkPath, cb) { + if (this.server) + throw new Error("Client-only method called in server mode"); + const linkLen = Buffer.byteLength(linkPath); + const targetLen = Buffer.byteLength(targetPath); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + linkLen + 4 + targetLen); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.SYMLINK; + const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; + writeUInt32BE(buf, reqid, 5); + if (this._isOpenSSH) { + writeUInt32BE(buf, targetLen, p); + buf.utf8Write(targetPath, p += 4, targetLen); + writeUInt32BE(buf, linkLen, p += targetLen); + buf.utf8Write(linkPath, p += 4, linkLen); + } else { + writeUInt32BE(buf, linkLen, p); + buf.utf8Write(linkPath, p += 4, linkLen); + writeUInt32BE(buf, targetLen, p += linkLen); + buf.utf8Write(targetPath, p += 4, targetLen); + } + this._requests[reqid] = { cb }; + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} SYMLINK` + ); + } + realpath(path, cb) { + if (this.server) + throw new Error("Client-only method called in server mode"); + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.REALPATH; + const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; + writeUInt32BE(buf, reqid, 5); + writeUInt32BE(buf, pathLen, p); + buf.utf8Write(path, p += 4, pathLen); + this._requests[reqid] = { + cb: (err, names) => { + if (typeof cb !== "function") + return; + if (err) + return cb(err); + if (!names || !names.length) + return cb(new Error("Response missing path info")); + cb(void 0, names[0].filename); + } + }; + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} REALPATH` + ); + } + // extended requests + ext_openssh_rename(oldPath, newPath, cb) { + if (this.server) + throw new Error("Client-only method called in server mode"); + const ext = this._extensions["posix-rename@openssh.com"]; + if (!ext || ext !== "1") + throw new Error("Server does not support this extended request"); + const oldLen = Buffer.byteLength(oldPath); + const newLen = Buffer.byteLength(newPath); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 24 + 4 + oldLen + 4 + newLen); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.EXTENDED; + const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; + writeUInt32BE(buf, reqid, 5); + writeUInt32BE(buf, 24, p); + buf.utf8Write("posix-rename@openssh.com", p += 4, 24); + writeUInt32BE(buf, oldLen, p += 24); + buf.utf8Write(oldPath, p += 4, oldLen); + writeUInt32BE(buf, newLen, p += oldLen); + buf.utf8Write(newPath, p += 4, newLen); + this._requests[reqid] = { cb }; + const isBuffered = sendOrBuffer(this, buf); + if (this._debug) { + const which2 = isBuffered ? "Buffered" : "Sending"; + this._debug(`SFTP: Outbound: ${which2} posix-rename@openssh.com`); + } + } + ext_openssh_statvfs(path, cb) { + if (this.server) + throw new Error("Client-only method called in server mode"); + const ext = this._extensions["statvfs@openssh.com"]; + if (!ext || ext !== "2") + throw new Error("Server does not support this extended request"); + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 19 + 4 + pathLen); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.EXTENDED; + const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; + writeUInt32BE(buf, reqid, 5); + writeUInt32BE(buf, 19, p); + buf.utf8Write("statvfs@openssh.com", p += 4, 19); + writeUInt32BE(buf, pathLen, p += 19); + buf.utf8Write(path, p += 4, pathLen); + this._requests[reqid] = { extended: "statvfs@openssh.com", cb }; + const isBuffered = sendOrBuffer(this, buf); + if (this._debug) { + const which2 = isBuffered ? "Buffered" : "Sending"; + this._debug(`SFTP: Outbound: ${which2} statvfs@openssh.com`); + } + } + ext_openssh_fstatvfs(handle, cb) { + if (this.server) + throw new Error("Client-only method called in server mode"); + const ext = this._extensions["fstatvfs@openssh.com"]; + if (!ext || ext !== "2") + throw new Error("Server does not support this extended request"); + if (!Buffer.isBuffer(handle)) + throw new Error("handle is not a Buffer"); + const handleLen = handle.length; + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + handleLen); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.EXTENDED; + const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; + writeUInt32BE(buf, reqid, 5); + writeUInt32BE(buf, 20, p); + buf.utf8Write("fstatvfs@openssh.com", p += 4, 20); + writeUInt32BE(buf, handleLen, p += 20); + buf.set(handle, p += 4); + this._requests[reqid] = { extended: "fstatvfs@openssh.com", cb }; + const isBuffered = sendOrBuffer(this, buf); + if (this._debug) { + const which2 = isBuffered ? "Buffered" : "Sending"; + this._debug(`SFTP: Outbound: ${which2} fstatvfs@openssh.com`); + } + } + ext_openssh_hardlink(oldPath, newPath, cb) { + if (this.server) + throw new Error("Client-only method called in server mode"); + const ext = this._extensions["hardlink@openssh.com"]; + if (ext !== "1") + throw new Error("Server does not support this extended request"); + const oldLen = Buffer.byteLength(oldPath); + const newLen = Buffer.byteLength(newPath); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + oldLen + 4 + newLen); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.EXTENDED; + const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; + writeUInt32BE(buf, reqid, 5); + writeUInt32BE(buf, 20, p); + buf.utf8Write("hardlink@openssh.com", p += 4, 20); + writeUInt32BE(buf, oldLen, p += 20); + buf.utf8Write(oldPath, p += 4, oldLen); + writeUInt32BE(buf, newLen, p += oldLen); + buf.utf8Write(newPath, p += 4, newLen); + this._requests[reqid] = { cb }; + const isBuffered = sendOrBuffer(this, buf); + if (this._debug) { + const which2 = isBuffered ? "Buffered" : "Sending"; + this._debug(`SFTP: Outbound: ${which2} hardlink@openssh.com`); + } + } + ext_openssh_fsync(handle, cb) { + if (this.server) + throw new Error("Client-only method called in server mode"); + const ext = this._extensions["fsync@openssh.com"]; + if (ext !== "1") + throw new Error("Server does not support this extended request"); + if (!Buffer.isBuffer(handle)) + throw new Error("handle is not a Buffer"); + const handleLen = handle.length; + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 17 + 4 + handleLen); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.EXTENDED; + const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; + writeUInt32BE(buf, reqid, 5); + writeUInt32BE(buf, 17, p); + buf.utf8Write("fsync@openssh.com", p += 4, 17); + writeUInt32BE(buf, handleLen, p += 17); + buf.set(handle, p += 4); + this._requests[reqid] = { cb }; + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} fsync@openssh.com` + ); + } + ext_openssh_lsetstat(path, attrs, cb) { + if (this.server) + throw new Error("Client-only method called in server mode"); + const ext = this._extensions["lsetstat@openssh.com"]; + if (ext !== "1") + throw new Error("Server does not support this extended request"); + let flags = 0; + let attrsLen = 0; + if (typeof attrs === "object" && attrs !== null) { + attrs = attrsToBytes(attrs); + flags = attrs.flags; + attrsLen = attrs.nb; + } else if (typeof attrs === "function") { + cb = attrs; + } + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + pathLen + 4 + attrsLen); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.EXTENDED; + const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; + writeUInt32BE(buf, reqid, 5); + writeUInt32BE(buf, 20, p); + buf.utf8Write("lsetstat@openssh.com", p += 4, 20); + writeUInt32BE(buf, pathLen, p += 20); + buf.utf8Write(path, p += 4, pathLen); + writeUInt32BE(buf, flags, p += pathLen); + if (attrsLen) { + p += 4; + if (attrsLen === ATTRS_BUF.length) + buf.set(ATTRS_BUF, p); + else + bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); + p += attrsLen; + } + this._requests[reqid] = { cb }; + const isBuffered = sendOrBuffer(this, buf); + if (this._debug) { + const status = isBuffered ? "Buffered" : "Sending"; + this._debug(`SFTP: Outbound: ${status} lsetstat@openssh.com`); + } + } + ext_openssh_expandPath(path, cb) { + if (this.server) + throw new Error("Client-only method called in server mode"); + const ext = this._extensions["expand-path@openssh.com"]; + if (ext !== "1") + throw new Error("Server does not support this extended request"); + const pathLen = Buffer.byteLength(path); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 23 + 4 + pathLen); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.EXTENDED; + const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; + writeUInt32BE(buf, reqid, 5); + writeUInt32BE(buf, 23, p); + buf.utf8Write("expand-path@openssh.com", p += 4, 23); + writeUInt32BE(buf, pathLen, p += 20); + buf.utf8Write(path, p += 4, pathLen); + this._requests[reqid] = { + cb: (err, names) => { + if (typeof cb !== "function") + return; + if (err) + return cb(err); + if (!names || !names.length) + return cb(new Error("Response missing expanded path")); + cb(void 0, names[0].filename); + } + }; + const isBuffered = sendOrBuffer(this, buf); + if (this._debug) { + const status = isBuffered ? "Buffered" : "Sending"; + this._debug(`SFTP: Outbound: ${status} expand-path@openssh.com`); + } + } + ext_copy_data(srcHandle, srcOffset, len, dstHandle, dstOffset, cb) { + if (this.server) + throw new Error("Client-only method called in server mode"); + const ext = this._extensions["copy-data"]; + if (ext !== "1") + throw new Error("Server does not support this extended request"); + if (!Buffer.isBuffer(srcHandle)) + throw new Error("Source handle is not a Buffer"); + if (!Buffer.isBuffer(dstHandle)) + throw new Error("Destination handle is not a Buffer"); + let p = 0; + const buf = Buffer.allocUnsafe( + 4 + 1 + 4 + 4 + 9 + 4 + srcHandle.length + 8 + 8 + 4 + dstHandle.length + 8 + ); + writeUInt32BE(buf, buf.length - 4, p); + p += 4; + buf[p] = REQUEST.EXTENDED; + ++p; + const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; + writeUInt32BE(buf, reqid, p); + p += 4; + writeUInt32BE(buf, 9, p); + p += 4; + buf.utf8Write("copy-data", p, 9); + p += 9; + writeUInt32BE(buf, srcHandle.length, p); + p += 4; + buf.set(srcHandle, p); + p += srcHandle.length; + for (let i = 7; i >= 0; --i) { + buf[p + i] = srcOffset & 255; + srcOffset /= 256; + } + p += 8; + for (let i = 7; i >= 0; --i) { + buf[p + i] = len & 255; + len /= 256; + } + p += 8; + writeUInt32BE(buf, dstHandle.length, p); + p += 4; + buf.set(dstHandle, p); + p += dstHandle.length; + for (let i = 7; i >= 0; --i) { + buf[p + i] = dstOffset & 255; + dstOffset /= 256; + } + this._requests[reqid] = { cb }; + const isBuffered = sendOrBuffer(this, buf); + if (this._debug) { + const status = isBuffered ? "Buffered" : "Sending"; + this._debug(`SFTP: Outbound: ${status} copy-data`); + } + } + ext_home_dir(username, cb) { + if (this.server) + throw new Error("Client-only method called in server mode"); + const ext = this._extensions["home-directory"]; + if (ext !== "1") + throw new Error("Server does not support this extended request"); + if (typeof username !== "string") + throw new TypeError("username is not a string"); + let p = 0; + const usernameLen = Buffer.byteLength(username); + const buf = Buffer.allocUnsafe( + 4 + 1 + 4 + 4 + 14 + 4 + usernameLen + ); + writeUInt32BE(buf, buf.length - 4, p); + p += 4; + buf[p] = REQUEST.EXTENDED; + ++p; + const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; + writeUInt32BE(buf, reqid, p); + p += 4; + writeUInt32BE(buf, 14, p); + p += 4; + buf.utf8Write("home-directory", p, 14); + p += 14; + writeUInt32BE(buf, usernameLen, p); + p += 4; + buf.utf8Write(username, p, usernameLen); + p += usernameLen; + this._requests[reqid] = { + cb: (err, names) => { + if (typeof cb !== "function") + return; + if (err) + return cb(err); + if (!names || !names.length) + return cb(new Error("Response missing home directory")); + cb(void 0, names[0].filename); + } + }; + const isBuffered = sendOrBuffer(this, buf); + if (this._debug) { + const status = isBuffered ? "Buffered" : "Sending"; + this._debug(`SFTP: Outbound: ${status} home-directory`); + } + } + ext_users_groups(uids, gids, cb) { + if (this.server) + throw new Error("Client-only method called in server mode"); + const ext = this._extensions["users-groups-by-id@openssh.com"]; + if (ext !== "1") + throw new Error("Server does not support this extended request"); + if (!Array.isArray(uids)) + throw new TypeError("uids is not an array"); + for (const val of uids) { + if (!Number.isInteger(val) || val < 0 || val > 2 ** 32 - 1) + throw new Error("uid values must all be 32-bit unsigned integers"); + } + if (!Array.isArray(gids)) + throw new TypeError("gids is not an array"); + for (const val of gids) { + if (!Number.isInteger(val) || val < 0 || val > 2 ** 32 - 1) + throw new Error("gid values must all be 32-bit unsigned integers"); + } + let p = 0; + const buf = Buffer.allocUnsafe( + 4 + 1 + 4 + 4 + 30 + 4 + 4 * uids.length + 4 + 4 * gids.length + ); + writeUInt32BE(buf, buf.length - 4, p); + p += 4; + buf[p] = REQUEST.EXTENDED; + ++p; + const reqid = this._writeReqid = this._writeReqid + 1 & MAX_REQID; + writeUInt32BE(buf, reqid, p); + p += 4; + writeUInt32BE(buf, 30, p); + p += 4; + buf.utf8Write("users-groups-by-id@openssh.com", p, 30); + p += 30; + writeUInt32BE(buf, 4 * uids.length, p); + p += 4; + for (const val of uids) { + writeUInt32BE(buf, val, p); + p += 4; + } + writeUInt32BE(buf, 4 * gids.length, p); + p += 4; + for (const val of gids) { + writeUInt32BE(buf, val, p); + p += 4; + } + this._requests[reqid] = { extended: "users-groups-by-id@openssh.com", cb }; + const isBuffered = sendOrBuffer(this, buf); + if (this._debug) { + const status = isBuffered ? "Buffered" : "Sending"; + this._debug(`SFTP: Outbound: ${status} users-groups-by-id@openssh.com`); + } + } + // =========================================================================== + // Server-specific =========================================================== + // =========================================================================== + handle(reqid, handle) { + if (!this.server) + throw new Error("Server-only method called in client mode"); + if (!Buffer.isBuffer(handle)) + throw new Error("handle is not a Buffer"); + const handleLen = handle.length; + if (handleLen > 256) + throw new Error("handle too large (> 256 bytes)"); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = RESPONSE.HANDLE; + writeUInt32BE(buf, reqid, 5); + writeUInt32BE(buf, handleLen, p); + if (handleLen) + buf.set(handle, p += 4); + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} HANDLE` + ); + } + status(reqid, code, message) { + if (!this.server) + throw new Error("Server-only method called in client mode"); + if (!VALID_STATUS_CODES.has(code)) + throw new Error(`Bad status code: ${code}`); + message || (message = ""); + const msgLen = Buffer.byteLength(message); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 4 + msgLen + 4); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = RESPONSE.STATUS; + writeUInt32BE(buf, reqid, 5); + writeUInt32BE(buf, code, p); + writeUInt32BE(buf, msgLen, p += 4); + p += 4; + if (msgLen) { + buf.utf8Write(message, p, msgLen); + p += msgLen; + } + writeUInt32BE(buf, 0, p); + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} STATUS` + ); + } + data(reqid, data, encoding) { + if (!this.server) + throw new Error("Server-only method called in client mode"); + const isBuffer = Buffer.isBuffer(data); + if (!isBuffer && typeof data !== "string") + throw new Error("data is not a Buffer or string"); + let isUTF8; + if (!isBuffer && !encoding) { + encoding = void 0; + isUTF8 = true; + } + const dataLen = isBuffer ? data.length : Buffer.byteLength(data, encoding); + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + dataLen); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = RESPONSE.DATA; + writeUInt32BE(buf, reqid, 5); + writeUInt32BE(buf, dataLen, p); + if (dataLen) { + if (isBuffer) + buf.set(data, p += 4); + else if (isUTF8) + buf.utf8Write(data, p += 4, dataLen); + else + buf.write(data, p += 4, dataLen, encoding); + } + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} DATA` + ); + } + name(reqid, names) { + if (!this.server) + throw new Error("Server-only method called in client mode"); + if (!Array.isArray(names)) { + if (typeof names !== "object" || names === null) + throw new Error("names is not an object or array"); + names = [names]; + } + const count = names.length; + let namesLen = 0; + let nameAttrs; + const attrs = []; + for (let i = 0; i < count; ++i) { + const name = names[i]; + const filename = !name || !name.filename || typeof name.filename !== "string" ? "" : name.filename; + namesLen += 4 + Buffer.byteLength(filename); + const longname = !name || !name.longname || typeof name.longname !== "string" ? "" : name.longname; + namesLen += 4 + Buffer.byteLength(longname); + if (typeof name.attrs === "object" && name.attrs !== null) { + nameAttrs = attrsToBytes(name.attrs); + namesLen += 4 + nameAttrs.nb; + if (nameAttrs.nb) { + let bytes; + if (nameAttrs.nb === ATTRS_BUF.length) { + bytes = new Uint8Array(ATTRS_BUF); + } else { + bytes = new Uint8Array(nameAttrs.nb); + bufferCopy(ATTRS_BUF, bytes, 0, nameAttrs.nb, 0); + } + nameAttrs.bytes = bytes; + } + attrs.push(nameAttrs); + } else { + namesLen += 4; + attrs.push(null); + } + } + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + namesLen); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = RESPONSE.NAME; + writeUInt32BE(buf, reqid, 5); + writeUInt32BE(buf, count, p); + p += 4; + for (let i = 0; i < count; ++i) { + const name = names[i]; + { + const filename = !name || !name.filename || typeof name.filename !== "string" ? "" : name.filename; + const len = Buffer.byteLength(filename); + writeUInt32BE(buf, len, p); + p += 4; + if (len) { + buf.utf8Write(filename, p, len); + p += len; + } + } + { + const longname = !name || !name.longname || typeof name.longname !== "string" ? "" : name.longname; + const len = Buffer.byteLength(longname); + writeUInt32BE(buf, len, p); + p += 4; + if (len) { + buf.utf8Write(longname, p, len); + p += len; + } + } + const attr = attrs[i]; + if (attr) { + writeUInt32BE(buf, attr.flags, p); + p += 4; + if (attr.flags && attr.bytes) { + buf.set(attr.bytes, p); + p += attr.nb; + } + } else { + writeUInt32BE(buf, 0, p); + p += 4; + } + } + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} NAME` + ); + } + attrs(reqid, attrs) { + if (!this.server) + throw new Error("Server-only method called in client mode"); + if (typeof attrs !== "object" || attrs === null) + throw new Error("attrs is not an object"); + attrs = attrsToBytes(attrs); + const flags = attrs.flags; + const attrsLen = attrs.nb; + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + attrsLen); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = RESPONSE.ATTRS; + writeUInt32BE(buf, reqid, 5); + writeUInt32BE(buf, flags, p); + if (attrsLen) { + p += 4; + if (attrsLen === ATTRS_BUF.length) + buf.set(ATTRS_BUF, p); + else + bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); + p += attrsLen; + } + const isBuffered = sendOrBuffer(this, buf); + this._debug && this._debug( + `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} ATTRS` + ); + } + }; + function tryCreateBuffer(size) { + try { + return Buffer.allocUnsafe(size); + } catch (ex) { + return ex; + } + } + function read_(self2, handle, buf, off, len, position, cb, req_) { + const maxDataLen = self2._maxReadLen; + const overflow = Math.max(len - maxDataLen, 0); + if (overflow) + len = maxDataLen; + const handleLen = handle.length; + let p = 9; + let pos = position; + const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4); + writeUInt32BE(out, out.length - 4, 0); + out[4] = REQUEST.READ; + const reqid = self2._writeReqid = self2._writeReqid + 1 & MAX_REQID; + writeUInt32BE(out, reqid, 5); + writeUInt32BE(out, handleLen, p); + out.set(handle, p += 4); + p += handleLen; + for (let i = 7; i >= 0; --i) { + out[p + i] = pos & 255; + pos /= 256; + } + writeUInt32BE(out, len, p += 8); + if (typeof cb !== "function") + cb = noop3; + const req = req_ || { + nb: 0, + position, + off, + origOff: off, + len: void 0, + overflow: void 0, + cb: (err, data, nb) => { + const len2 = req.len; + const overflow2 = req.overflow; + if (err) { + if (cb._wantEOFError || err.code !== STATUS_CODE.EOF) + return cb(err); + } else if (nb > len2) { + return cb(new Error("Received more data than requested")); + } else if (nb === len2 && overflow2) { + req.nb += nb; + req.position += nb; + req.off += nb; + read_(self2, handle, buf, req.off, overflow2, req.position, cb, req); + return; + } + nb = nb || 0; + if (req.origOff === 0 && buf.length === req.nb) + data = buf; + else + data = bufferSlice(buf, req.origOff, req.origOff + req.nb + nb); + cb(void 0, req.nb + nb, data, req.position); + }, + buffer: void 0 + }; + req.len = len; + req.overflow = overflow; + req.buffer = bufferSlice(buf, off, off + len); + self2._requests[reqid] = req; + const isBuffered = sendOrBuffer(self2, out); + self2._debug && self2._debug( + `SFTP: Outbound: ${isBuffered ? "Buffered" : "Sending"} READ` + ); + } + function fastXfer(src, dst, srcPath, dstPath, opts, cb) { + let concurrency = 64; + let chunkSize = 32768; + let onstep; + let mode; + let fileSize; + if (typeof opts === "function") { + cb = opts; + } else if (typeof opts === "object" && opts !== null) { + if (typeof opts.concurrency === "number" && opts.concurrency > 0 && !isNaN(opts.concurrency)) { + concurrency = opts.concurrency; + } + if (typeof opts.chunkSize === "number" && opts.chunkSize > 0 && !isNaN(opts.chunkSize)) { + chunkSize = opts.chunkSize; + } + if (typeof opts.fileSize === "number" && opts.fileSize > 0 && !isNaN(opts.fileSize)) { + fileSize = opts.fileSize; + } + if (typeof opts.step === "function") + onstep = opts.step; + if (typeof opts.mode === "string" || typeof opts.mode === "number") + mode = modeNum(opts.mode); + } + let fsize; + let pdst = 0; + let total = 0; + let hadError = false; + let srcHandle; + let dstHandle; + let readbuf; + let bufsize = chunkSize * concurrency; + function onerror(err) { + if (hadError) + return; + hadError = true; + let left = 0; + let cbfinal; + if (srcHandle || dstHandle) { + cbfinal = () => { + if (--left === 0) + cb(err); + }; + if (srcHandle && (src === fs4 || src.outgoing.state === "open")) + ++left; + if (dstHandle && (dst === fs4 || dst.outgoing.state === "open")) + ++left; + if (srcHandle && (src === fs4 || src.outgoing.state === "open")) + src.close(srcHandle, cbfinal); + if (dstHandle && (dst === fs4 || dst.outgoing.state === "open")) + dst.close(dstHandle, cbfinal); + } else { + cb(err); + } + } + src.open(srcPath, "r", (err, sourceHandle) => { + if (err) + return onerror(err); + srcHandle = sourceHandle; + if (fileSize === void 0) + src.fstat(srcHandle, tryStat); + else + tryStat(null, { size: fileSize }); + function tryStat(err2, attrs) { + if (err2) { + if (src !== fs4) { + src.stat(srcPath, (err_, attrs_) => { + if (err_) + return onerror(err2); + tryStat(null, attrs_); + }); + return; + } + return onerror(err2); + } + fsize = attrs.size; + dst.open(dstPath, "w", (err3, destHandle) => { + if (err3) + return onerror(err3); + dstHandle = destHandle; + if (fsize <= 0) + return onerror(); + while (bufsize > fsize) { + if (concurrency === 1) { + bufsize = fsize; + break; + } + bufsize -= chunkSize; + --concurrency; + } + readbuf = tryCreateBuffer(bufsize); + if (readbuf instanceof Error) + return onerror(readbuf); + if (mode !== void 0) { + dst.fchmod(dstHandle, mode, function tryAgain(err4) { + if (err4) { + dst.chmod(dstPath, mode, (err_) => tryAgain()); + return; + } + startReads(); + }); + } else { + startReads(); + } + function onread(err4, nb, data, dstpos, datapos, origChunkLen) { + if (err4) + return onerror(err4); + datapos = datapos || 0; + dst.write(dstHandle, readbuf, datapos, nb, dstpos, writeCb); + function writeCb(err5) { + if (err5) + return onerror(err5); + total += nb; + onstep && onstep(total, nb, fsize); + if (nb < origChunkLen) + return singleRead(datapos, dstpos + nb, origChunkLen - nb); + if (total === fsize) { + dst.close(dstHandle, (err6) => { + dstHandle = void 0; + if (err6) + return onerror(err6); + src.close(srcHandle, (err7) => { + srcHandle = void 0; + if (err7) + return onerror(err7); + cb(); + }); + }); + return; + } + if (pdst >= fsize) + return; + const chunk = pdst + chunkSize > fsize ? fsize - pdst : chunkSize; + singleRead(datapos, pdst, chunk); + pdst += chunk; + } + } + function makeCb(psrc, pdst2, chunk) { + return (err4, nb, data) => { + onread(err4, nb, data, pdst2, psrc, chunk); + }; + } + function singleRead(psrc, pdst2, chunk) { + src.read( + srcHandle, + readbuf, + psrc, + chunk, + pdst2, + makeCb(psrc, pdst2, chunk) + ); + } + function startReads() { + let reads = 0; + let psrc = 0; + while (pdst < fsize && reads < concurrency) { + const chunk = pdst + chunkSize > fsize ? fsize - pdst : chunkSize; + singleRead(psrc, pdst, chunk); + psrc += chunk; + pdst += chunk; + ++reads; + } + } + }); + } + }); + } + function writeAll(sftp, handle, buffer, offset, length, position, callback_) { + const callback = typeof callback_ === "function" ? callback_ : void 0; + sftp.write( + handle, + buffer, + offset, + length, + position, + (writeErr, written) => { + if (writeErr) { + return sftp.close(handle, () => { + callback && callback(writeErr); + }); + } + if (written === length) { + sftp.close(handle, callback); + } else { + offset += written; + length -= written; + position += written; + writeAll(sftp, handle, buffer, offset, length, position, callback); + } + } + ); + } + var Stats = class { + constructor(initial) { + this.mode = initial && initial.mode; + this.uid = initial && initial.uid; + this.gid = initial && initial.gid; + this.size = initial && initial.size; + this.atime = initial && initial.atime; + this.mtime = initial && initial.mtime; + this.extended = initial && initial.extended; + } + isDirectory() { + return (this.mode & constants3.S_IFMT) === constants3.S_IFDIR; + } + isFile() { + return (this.mode & constants3.S_IFMT) === constants3.S_IFREG; + } + isBlockDevice() { + return (this.mode & constants3.S_IFMT) === constants3.S_IFBLK; + } + isCharacterDevice() { + return (this.mode & constants3.S_IFMT) === constants3.S_IFCHR; + } + isSymbolicLink() { + return (this.mode & constants3.S_IFMT) === constants3.S_IFLNK; + } + isFIFO() { + return (this.mode & constants3.S_IFMT) === constants3.S_IFIFO; + } + isSocket() { + return (this.mode & constants3.S_IFMT) === constants3.S_IFSOCK; + } + }; + function attrsToBytes(attrs) { + let flags = 0; + let nb = 0; + if (typeof attrs === "object" && attrs !== null) { + if (typeof attrs.size === "number") { + flags |= ATTR.SIZE; + const val = attrs.size; + ATTRS_BUF[nb++] = val / 72057594037927940; + ATTRS_BUF[nb++] = val / 281474976710656; + ATTRS_BUF[nb++] = val / 1099511627776; + ATTRS_BUF[nb++] = val / 4294967296; + ATTRS_BUF[nb++] = val / 16777216; + ATTRS_BUF[nb++] = val / 65536; + ATTRS_BUF[nb++] = val / 256; + ATTRS_BUF[nb++] = val; + } + if (typeof attrs.uid === "number" && typeof attrs.gid === "number") { + flags |= ATTR.UIDGID; + const uid = attrs.uid; + const gid = attrs.gid; + ATTRS_BUF[nb++] = uid >>> 24; + ATTRS_BUF[nb++] = uid >>> 16; + ATTRS_BUF[nb++] = uid >>> 8; + ATTRS_BUF[nb++] = uid; + ATTRS_BUF[nb++] = gid >>> 24; + ATTRS_BUF[nb++] = gid >>> 16; + ATTRS_BUF[nb++] = gid >>> 8; + ATTRS_BUF[nb++] = gid; + } + if (typeof attrs.mode === "number" || typeof attrs.mode === "string") { + const mode = modeNum(attrs.mode); + flags |= ATTR.PERMISSIONS; + ATTRS_BUF[nb++] = mode >>> 24; + ATTRS_BUF[nb++] = mode >>> 16; + ATTRS_BUF[nb++] = mode >>> 8; + ATTRS_BUF[nb++] = mode; + } + if ((typeof attrs.atime === "number" || isDate(attrs.atime)) && (typeof attrs.mtime === "number" || isDate(attrs.mtime))) { + const atime = toUnixTimestamp(attrs.atime); + const mtime = toUnixTimestamp(attrs.mtime); + flags |= ATTR.ACMODTIME; + ATTRS_BUF[nb++] = atime >>> 24; + ATTRS_BUF[nb++] = atime >>> 16; + ATTRS_BUF[nb++] = atime >>> 8; + ATTRS_BUF[nb++] = atime; + ATTRS_BUF[nb++] = mtime >>> 24; + ATTRS_BUF[nb++] = mtime >>> 16; + ATTRS_BUF[nb++] = mtime >>> 8; + ATTRS_BUF[nb++] = mtime; + } + } + return { flags, nb }; + } + function toUnixTimestamp(time) { + if (typeof time === "number" && time === time) + return time; + if (isDate(time)) + return parseInt(time.getTime() / 1e3, 10); + throw new Error(`Cannot parse time: ${time}`); + } + function modeNum(mode) { + if (typeof mode === "number" && mode === mode) + return mode; + if (typeof mode === "string") + return modeNum(parseInt(mode, 8)); + throw new Error(`Cannot parse mode: ${mode}`); + } + var stringFlagMap = { + "r": OPEN_MODE.READ, + "r+": OPEN_MODE.READ | OPEN_MODE.WRITE, + "w": OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE, + "wx": OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, + "xw": OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, + "w+": OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE, + "wx+": OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE | OPEN_MODE.EXCL, + "xw+": OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE | OPEN_MODE.EXCL, + "a": OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE, + "ax": OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, + "xa": OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, + "a+": OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE, + "ax+": OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE | OPEN_MODE.EXCL, + "xa+": OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE | OPEN_MODE.EXCL + }; + function stringToFlags(str) { + const flags = stringFlagMap[str]; + return flags !== void 0 ? flags : null; + } + var flagsToString = (() => { + const stringFlagMapKeys = Object.keys(stringFlagMap); + return (flags) => { + for (let i = 0; i < stringFlagMapKeys.length; ++i) { + const key = stringFlagMapKeys[i]; + if (stringFlagMap[key] === flags) + return key; + } + return null; + }; + })(); + function readAttrs(biOpt) { + const flags = bufferParser.readUInt32BE(); + if (flags === void 0) + return; + const attrs = new Stats(); + if (flags & ATTR.SIZE) { + const size = bufferParser.readUInt64BE(biOpt); + if (size === void 0) + return; + attrs.size = size; + } + if (flags & ATTR.UIDGID) { + const uid = bufferParser.readUInt32BE(); + const gid = bufferParser.readUInt32BE(); + if (gid === void 0) + return; + attrs.uid = uid; + attrs.gid = gid; + } + if (flags & ATTR.PERMISSIONS) { + const mode = bufferParser.readUInt32BE(); + if (mode === void 0) + return; + attrs.mode = mode; + } + if (flags & ATTR.ACMODTIME) { + const atime = bufferParser.readUInt32BE(); + const mtime = bufferParser.readUInt32BE(); + if (mtime === void 0) + return; + attrs.atime = atime; + attrs.mtime = mtime; + } + if (flags & ATTR.EXTENDED) { + const count = bufferParser.readUInt32BE(); + if (count === void 0) + return; + const extended = {}; + for (let i = 0; i < count; ++i) { + const type = bufferParser.readString(true); + const data = bufferParser.readString(); + if (data === void 0) + return; + extended[type] = data; + } + attrs.extended = extended; + } + return attrs; + } + function sendOrBuffer(sftp, payload) { + const ret = tryWritePayload(sftp, payload); + if (ret !== void 0) { + sftp._buffer.push(ret); + return false; + } + return true; + } + function tryWritePayload(sftp, payload) { + const outgoing = sftp.outgoing; + if (outgoing.state !== "open") + return; + if (outgoing.window === 0) { + sftp._waitWindow = true; + sftp._chunkcb = drainBuffer; + return payload; + } + let ret; + const len = payload.length; + let p = 0; + while (len - p > 0 && outgoing.window > 0) { + const actualLen = Math.min(len - p, outgoing.window, outgoing.packetSize); + outgoing.window -= actualLen; + if (outgoing.window === 0) { + sftp._waitWindow = true; + sftp._chunkcb = drainBuffer; + } + if (p === 0 && actualLen === len) { + sftp._protocol.channelData(sftp.outgoing.id, payload); + } else { + sftp._protocol.channelData( + sftp.outgoing.id, + bufferSlice(payload, p, p + actualLen) + ); + } + p += actualLen; + } + if (len - p > 0) { + if (p > 0) + ret = bufferSlice(payload, p, len); + else + ret = payload; + } + return ret; + } + function drainBuffer() { + this._chunkcb = void 0; + const buffer = this._buffer; + let i = 0; + while (i < buffer.length) { + const payload = buffer[i]; + const ret = tryWritePayload(this, payload); + if (ret !== void 0) { + if (ret !== payload) + buffer[i] = ret; + if (i > 0) + this._buffer = buffer.slice(i); + return; + } + ++i; + } + if (i > 0) + this._buffer = []; + } + function doFatalSFTPError(sftp, msg, noDebug) { + const err = new Error(msg); + err.level = "sftp-protocol"; + if (!noDebug && sftp._debug) + sftp._debug(`SFTP: Inbound: ${msg}`); + sftp.emit("error", err); + sftp.destroy(); + cleanupRequests(sftp); + return false; + } + function cleanupRequests(sftp) { + const keys = Object.keys(sftp._requests); + if (keys.length === 0) + return; + const reqs = sftp._requests; + sftp._requests = {}; + const err = new Error("No response from server"); + for (let i = 0; i < keys.length; ++i) { + const req = reqs[keys[i]]; + if (typeof req.cb === "function") + req.cb(err); + } + } + function requestLimits(sftp, cb) { + let p = 9; + const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 18); + writeUInt32BE(buf, buf.length - 4, 0); + buf[4] = REQUEST.EXTENDED; + const reqid = sftp._writeReqid = sftp._writeReqid + 1 & MAX_REQID; + writeUInt32BE(buf, reqid, 5); + writeUInt32BE(buf, 18, p); + buf.utf8Write("limits@openssh.com", p += 4, 18); + sftp._requests[reqid] = { extended: "limits@openssh.com", cb }; + const isBuffered = sendOrBuffer(sftp, buf); + if (sftp._debug) { + const which2 = isBuffered ? "Buffered" : "Sending"; + sftp._debug(`SFTP: Outbound: ${which2} limits@openssh.com`); + } + } + var CLIENT_HANDLERS = { + [RESPONSE.VERSION]: (sftp, payload) => { + if (sftp._version !== -1) + return doFatalSFTPError(sftp, "Duplicate VERSION packet"); + const extensions = {}; + bufferParser.init(payload, 1); + let version = bufferParser.readUInt32BE(); + while (bufferParser.avail()) { + const extName = bufferParser.readString(true); + const extData = bufferParser.readString(true); + if (extData === void 0) { + version = void 0; + break; + } + extensions[extName] = extData; + } + bufferParser.clear(); + if (version === void 0) + return doFatalSFTPError(sftp, "Malformed VERSION packet"); + if (sftp._debug) { + const names = Object.keys(extensions); + if (names.length) { + sftp._debug( + `SFTP: Inbound: Received VERSION (v${version}, exts:${names})` + ); + } else { + sftp._debug(`SFTP: Inbound: Received VERSION (v${version})`); + } + } + sftp._version = version; + sftp._extensions = extensions; + if (extensions["limits@openssh.com"] === "1") { + return requestLimits(sftp, (err, limits) => { + if (!err) { + if (limits.maxPktLen > 0) + sftp._maxOutPktLen = limits.maxPktLen; + if (limits.maxReadLen > 0) + sftp._maxReadLen = limits.maxReadLen; + if (limits.maxWriteLen > 0) + sftp._maxWriteLen = limits.maxWriteLen; + sftp.maxOpenHandles = limits.maxOpenHandles > 0 ? limits.maxOpenHandles : Infinity; + } + sftp.emit("ready"); + }); + } + sftp.emit("ready"); + }, + [RESPONSE.STATUS]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + const errorCode = bufferParser.readUInt32BE(); + const errorMsg = bufferParser.readString(true); + bufferParser.clear(); + if (sftp._debug) { + const jsonMsg = JSON.stringify(errorMsg); + sftp._debug( + `SFTP: Inbound: Received STATUS (id:${reqID}, ${errorCode}, ${jsonMsg})` + ); + } + const req = sftp._requests[reqID]; + delete sftp._requests[reqID]; + if (req && typeof req.cb === "function") { + if (errorCode === STATUS_CODE.OK) { + req.cb(); + return; + } + const err = new Error(errorMsg || STATUS_CODE_STR[errorCode] || "Unknown status"); + err.code = errorCode; + req.cb(err); + } + }, + [RESPONSE.HANDLE]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + const handle = bufferParser.readString(); + bufferParser.clear(); + if (handle === void 0) { + if (reqID !== void 0) + delete sftp._requests[reqID]; + return doFatalSFTPError(sftp, "Malformed HANDLE packet"); + } + sftp._debug && sftp._debug(`SFTP: Inbound: Received HANDLE (id:${reqID})`); + const req = sftp._requests[reqID]; + delete sftp._requests[reqID]; + if (req && typeof req.cb === "function") + req.cb(void 0, handle); + }, + [RESPONSE.DATA]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + let req; + if (reqID !== void 0) { + req = sftp._requests[reqID]; + delete sftp._requests[reqID]; + } + if (req && typeof req.cb === "function") { + if (req.buffer) { + const nb = bufferParser.readString(req.buffer); + bufferParser.clear(); + if (nb !== void 0) { + sftp._debug && sftp._debug( + `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})` + ); + req.cb(void 0, req.buffer, nb); + return; + } + } else { + const data = bufferParser.readString(); + bufferParser.clear(); + if (data !== void 0) { + sftp._debug && sftp._debug( + `SFTP: Inbound: Received DATA (id:${reqID}, ${data.length})` + ); + req.cb(void 0, data); + return; + } + } + } else { + const nb = bufferParser.skipString(); + bufferParser.clear(); + if (nb !== void 0) { + sftp._debug && sftp._debug( + `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})` + ); + return; + } + } + return doFatalSFTPError(sftp, "Malformed DATA packet"); + }, + [RESPONSE.NAME]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + let req; + if (reqID !== void 0) { + req = sftp._requests[reqID]; + delete sftp._requests[reqID]; + } + const count = bufferParser.readUInt32BE(); + if (count !== void 0) { + let names = []; + for (let i = 0; i < count; ++i) { + const filename = bufferParser.readString(true); + const longname = bufferParser.readString(true); + const attrs = readAttrs(sftp._biOpt); + if (attrs === void 0) { + names = void 0; + break; + } + names.push({ filename, longname, attrs }); + } + if (names !== void 0) { + sftp._debug && sftp._debug( + `SFTP: Inbound: Received NAME (id:${reqID}, ${names.length})` + ); + bufferParser.clear(); + if (req && typeof req.cb === "function") + req.cb(void 0, names); + return; + } + } + bufferParser.clear(); + return doFatalSFTPError(sftp, "Malformed NAME packet"); + }, + [RESPONSE.ATTRS]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + let req; + if (reqID !== void 0) { + req = sftp._requests[reqID]; + delete sftp._requests[reqID]; + } + const attrs = readAttrs(sftp._biOpt); + bufferParser.clear(); + if (attrs !== void 0) { + sftp._debug && sftp._debug(`SFTP: Inbound: Received ATTRS (id:${reqID})`); + if (req && typeof req.cb === "function") + req.cb(void 0, attrs); + return; + } + return doFatalSFTPError(sftp, "Malformed ATTRS packet"); + }, + [RESPONSE.EXTENDED]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + if (reqID !== void 0) { + const req = sftp._requests[reqID]; + if (req) { + delete sftp._requests[reqID]; + switch (req.extended) { + case "statvfs@openssh.com": + case "fstatvfs@openssh.com": { + const biOpt = sftp._biOpt; + const stats = { + f_bsize: bufferParser.readUInt64BE(biOpt), + f_frsize: bufferParser.readUInt64BE(biOpt), + f_blocks: bufferParser.readUInt64BE(biOpt), + f_bfree: bufferParser.readUInt64BE(biOpt), + f_bavail: bufferParser.readUInt64BE(biOpt), + f_files: bufferParser.readUInt64BE(biOpt), + f_ffree: bufferParser.readUInt64BE(biOpt), + f_favail: bufferParser.readUInt64BE(biOpt), + f_sid: bufferParser.readUInt64BE(biOpt), + f_flag: bufferParser.readUInt64BE(biOpt), + f_namemax: bufferParser.readUInt64BE(biOpt) + }; + if (stats.f_namemax === void 0) + break; + if (sftp._debug) { + sftp._debug( + `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ${req.extended})` + ); + } + bufferParser.clear(); + if (typeof req.cb === "function") + req.cb(void 0, stats); + return; + } + case "limits@openssh.com": { + const limits = { + maxPktLen: bufferParser.readUInt64BE(), + maxReadLen: bufferParser.readUInt64BE(), + maxWriteLen: bufferParser.readUInt64BE(), + maxOpenHandles: bufferParser.readUInt64BE() + }; + if (limits.maxOpenHandles === void 0) + break; + if (sftp._debug) { + sftp._debug( + `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ${req.extended})` + ); + } + bufferParser.clear(); + if (typeof req.cb === "function") + req.cb(void 0, limits); + return; + } + case "users-groups-by-id@openssh.com": { + const usernameCount = bufferParser.readUInt32BE(); + if (usernameCount === void 0) + break; + const usernames = new Array(usernameCount); + for (let i = 0; i < usernames.length; ++i) + usernames[i] = bufferParser.readString(true); + const groupnameCount = bufferParser.readUInt32BE(); + if (groupnameCount === void 0) + break; + const groupnames = new Array(groupnameCount); + for (let i = 0; i < groupnames.length; ++i) + groupnames[i] = bufferParser.readString(true); + if (groupnames.length > 0 && groupnames[groupnames.length - 1] === void 0) { + break; + } + if (sftp._debug) { + sftp._debug( + `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ${req.extended})` + ); + } + bufferParser.clear(); + if (typeof req.cb === "function") + req.cb(void 0, usernames, groupnames); + return; + } + default: + sftp._debug && sftp._debug( + `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)` + ); + bufferParser.clear(); + if (typeof req.cb === "function") + req.cb(); + return; + } + } else { + sftp._debug && sftp._debug( + `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)` + ); + bufferParser.clear(); + return; + } + } + bufferParser.clear(); + return doFatalSFTPError(sftp, "Malformed EXTENDED_REPLY packet"); + } + }; + var SERVER_HANDLERS = { + [REQUEST.INIT]: (sftp, payload) => { + if (sftp._version !== -1) + return doFatalSFTPError(sftp, "Duplicate INIT packet"); + const extensions = {}; + bufferParser.init(payload, 1); + let version = bufferParser.readUInt32BE(); + while (bufferParser.avail()) { + const extName = bufferParser.readString(true); + const extData = bufferParser.readString(true); + if (extData === void 0) { + version = void 0; + break; + } + extensions[extName] = extData; + } + bufferParser.clear(); + if (version === void 0) + return doFatalSFTPError(sftp, "Malformed INIT packet"); + if (sftp._debug) { + const names = Object.keys(extensions); + if (names.length) { + sftp._debug( + `SFTP: Inbound: Received INIT (v${version}, exts:${names})` + ); + } else { + sftp._debug(`SFTP: Inbound: Received INIT (v${version})`); + } + } + sendOrBuffer(sftp, SERVER_VERSION_BUFFER); + sftp._version = version; + sftp._extensions = extensions; + sftp.emit("ready"); + }, + [REQUEST.OPEN]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + const filename = bufferParser.readString(true); + const pflags = bufferParser.readUInt32BE(); + const attrs = readAttrs(sftp._biOpt); + bufferParser.clear(); + if (attrs === void 0) + return doFatalSFTPError(sftp, "Malformed OPEN packet"); + sftp._debug && sftp._debug(`SFTP: Inbound: Received OPEN (id:${reqID})`); + if (!sftp.emit("OPEN", reqID, filename, pflags, attrs)) { + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.CLOSE]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + const handle = bufferParser.readString(); + bufferParser.clear(); + if (handle === void 0 || handle.length > 256) + return doFatalSFTPError(sftp, "Malformed CLOSE packet"); + sftp._debug && sftp._debug(`SFTP: Inbound: Received CLOSE (id:${reqID})`); + if (!sftp.emit("CLOSE", reqID, handle)) { + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.READ]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + const handle = bufferParser.readString(); + const offset = bufferParser.readUInt64BE(sftp._biOpt); + const len = bufferParser.readUInt32BE(); + bufferParser.clear(); + if (len === void 0 || handle.length > 256) + return doFatalSFTPError(sftp, "Malformed READ packet"); + sftp._debug && sftp._debug(`SFTP: Inbound: Received READ (id:${reqID})`); + if (!sftp.emit("READ", reqID, handle, offset, len)) { + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.WRITE]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + const handle = bufferParser.readString(); + const offset = bufferParser.readUInt64BE(sftp._biOpt); + const data = bufferParser.readString(); + bufferParser.clear(); + if (data === void 0 || handle.length > 256) + return doFatalSFTPError(sftp, "Malformed WRITE packet"); + sftp._debug && sftp._debug(`SFTP: Inbound: Received WRITE (id:${reqID})`); + if (!sftp.emit("WRITE", reqID, handle, offset, data)) { + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.LSTAT]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + const path = bufferParser.readString(true); + bufferParser.clear(); + if (path === void 0) + return doFatalSFTPError(sftp, "Malformed LSTAT packet"); + sftp._debug && sftp._debug(`SFTP: Inbound: Received LSTAT (id:${reqID})`); + if (!sftp.emit("LSTAT", reqID, path)) { + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.FSTAT]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + const handle = bufferParser.readString(); + bufferParser.clear(); + if (handle === void 0 || handle.length > 256) + return doFatalSFTPError(sftp, "Malformed FSTAT packet"); + sftp._debug && sftp._debug(`SFTP: Inbound: Received FSTAT (id:${reqID})`); + if (!sftp.emit("FSTAT", reqID, handle)) { + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.SETSTAT]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + const path = bufferParser.readString(true); + const attrs = readAttrs(sftp._biOpt); + bufferParser.clear(); + if (attrs === void 0) + return doFatalSFTPError(sftp, "Malformed SETSTAT packet"); + sftp._debug && sftp._debug(`SFTP: Inbound: Received SETSTAT (id:${reqID})`); + if (!sftp.emit("SETSTAT", reqID, path, attrs)) { + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.FSETSTAT]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + const handle = bufferParser.readString(); + const attrs = readAttrs(sftp._biOpt); + bufferParser.clear(); + if (attrs === void 0 || handle.length > 256) + return doFatalSFTPError(sftp, "Malformed FSETSTAT packet"); + sftp._debug && sftp._debug( + `SFTP: Inbound: Received FSETSTAT (id:${reqID})` + ); + if (!sftp.emit("FSETSTAT", reqID, handle, attrs)) { + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.OPENDIR]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + const path = bufferParser.readString(true); + bufferParser.clear(); + if (path === void 0) + return doFatalSFTPError(sftp, "Malformed OPENDIR packet"); + sftp._debug && sftp._debug(`SFTP: Inbound: Received OPENDIR (id:${reqID})`); + if (!sftp.emit("OPENDIR", reqID, path)) { + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.READDIR]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + const handle = bufferParser.readString(); + bufferParser.clear(); + if (handle === void 0 || handle.length > 256) + return doFatalSFTPError(sftp, "Malformed READDIR packet"); + sftp._debug && sftp._debug(`SFTP: Inbound: Received READDIR (id:${reqID})`); + if (!sftp.emit("READDIR", reqID, handle)) { + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.REMOVE]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + const path = bufferParser.readString(true); + bufferParser.clear(); + if (path === void 0) + return doFatalSFTPError(sftp, "Malformed REMOVE packet"); + sftp._debug && sftp._debug(`SFTP: Inbound: Received REMOVE (id:${reqID})`); + if (!sftp.emit("REMOVE", reqID, path)) { + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.MKDIR]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + const path = bufferParser.readString(true); + const attrs = readAttrs(sftp._biOpt); + bufferParser.clear(); + if (attrs === void 0) + return doFatalSFTPError(sftp, "Malformed MKDIR packet"); + sftp._debug && sftp._debug(`SFTP: Inbound: Received MKDIR (id:${reqID})`); + if (!sftp.emit("MKDIR", reqID, path, attrs)) { + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.RMDIR]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + const path = bufferParser.readString(true); + bufferParser.clear(); + if (path === void 0) + return doFatalSFTPError(sftp, "Malformed RMDIR packet"); + sftp._debug && sftp._debug(`SFTP: Inbound: Received RMDIR (id:${reqID})`); + if (!sftp.emit("RMDIR", reqID, path)) { + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.REALPATH]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + const path = bufferParser.readString(true); + bufferParser.clear(); + if (path === void 0) + return doFatalSFTPError(sftp, "Malformed REALPATH packet"); + sftp._debug && sftp._debug( + `SFTP: Inbound: Received REALPATH (id:${reqID})` + ); + if (!sftp.emit("REALPATH", reqID, path)) { + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.STAT]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + const path = bufferParser.readString(true); + bufferParser.clear(); + if (path === void 0) + return doFatalSFTPError(sftp, "Malformed STAT packet"); + sftp._debug && sftp._debug(`SFTP: Inbound: Received STAT (id:${reqID})`); + if (!sftp.emit("STAT", reqID, path)) { + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.RENAME]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + const oldPath = bufferParser.readString(true); + const newPath = bufferParser.readString(true); + bufferParser.clear(); + if (newPath === void 0) + return doFatalSFTPError(sftp, "Malformed RENAME packet"); + sftp._debug && sftp._debug(`SFTP: Inbound: Received RENAME (id:${reqID})`); + if (!sftp.emit("RENAME", reqID, oldPath, newPath)) { + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.READLINK]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + const path = bufferParser.readString(true); + bufferParser.clear(); + if (path === void 0) + return doFatalSFTPError(sftp, "Malformed READLINK packet"); + sftp._debug && sftp._debug( + `SFTP: Inbound: Received READLINK (id:${reqID})` + ); + if (!sftp.emit("READLINK", reqID, path)) { + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.SYMLINK]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + const linkPath = bufferParser.readString(true); + const targetPath = bufferParser.readString(true); + bufferParser.clear(); + if (targetPath === void 0) + return doFatalSFTPError(sftp, "Malformed SYMLINK packet"); + sftp._debug && sftp._debug(`SFTP: Inbound: Received SYMLINK (id:${reqID})`); + let handled; + if (sftp._isOpenSSH) { + handled = sftp.emit("SYMLINK", reqID, targetPath, linkPath); + } else { + handled = sftp.emit("SYMLINK", reqID, linkPath, targetPath); + } + if (!handled) { + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + }, + [REQUEST.EXTENDED]: (sftp, payload) => { + bufferParser.init(payload, 1); + const reqID = bufferParser.readUInt32BE(); + const extName = bufferParser.readString(true); + if (extName === void 0) { + bufferParser.clear(); + return doFatalSFTPError(sftp, "Malformed EXTENDED packet"); + } + let extData; + if (bufferParser.avail()) + extData = bufferParser.readRaw(); + bufferParser.clear(); + sftp._debug && sftp._debug( + `SFTP: Inbound: Received EXTENDED (id:${reqID})` + ); + if (!sftp.emit("EXTENDED", reqID, extName, extData)) { + sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + } + } + }; + var { + ERR_INVALID_ARG_TYPE, + ERR_OUT_OF_RANGE, + validateNumber + } = require_node_fs_compat(); + var kMinPoolSpace = 128; + var pool; + var poolFragments = []; + function allocNewPool(poolSize) { + if (poolFragments.length > 0) + pool = poolFragments.pop(); + else + pool = Buffer.allocUnsafe(poolSize); + pool.used = 0; + } + function checkPosition(pos, name) { + if (!Number.isSafeInteger(pos)) { + validateNumber(pos, name); + if (!Number.isInteger(pos)) + throw new ERR_OUT_OF_RANGE(name, "an integer", pos); + throw new ERR_OUT_OF_RANGE(name, ">= 0 and <= 2 ** 53 - 1", pos); + } + if (pos < 0) + throw new ERR_OUT_OF_RANGE(name, ">= 0 and <= 2 ** 53 - 1", pos); + } + function roundUpToMultipleOf8(n) { + return n + 7 & ~7; + } + function ReadStream(sftp, path, options) { + if (options === void 0) + options = {}; + else if (typeof options === "string") + options = { encoding: options }; + else if (options === null || typeof options !== "object") + throw new TypeError('"options" argument must be a string or an object'); + else + options = Object.create(options); + if (options.highWaterMark === void 0) + options.highWaterMark = 64 * 1024; + options.emitClose = false; + options.autoDestroy = false; + ReadableStream2.call(this, options); + this.path = path; + this.flags = options.flags === void 0 ? "r" : options.flags; + this.mode = options.mode === void 0 ? 438 : options.mode; + this.start = options.start; + this.end = options.end; + this.autoClose = options.autoClose === void 0 ? true : options.autoClose; + this.pos = 0; + this.bytesRead = 0; + this.isClosed = false; + this.handle = options.handle === void 0 ? null : options.handle; + this.sftp = sftp; + this._opening = false; + if (this.start !== void 0) { + checkPosition(this.start, "start"); + this.pos = this.start; + } + if (this.end === void 0) { + this.end = Infinity; + } else if (this.end !== Infinity) { + checkPosition(this.end, "end"); + if (this.start !== void 0 && this.start > this.end) { + throw new ERR_OUT_OF_RANGE( + "start", + `<= "end" (here: ${this.end})`, + this.start + ); + } + } + this.on("end", function() { + if (this.autoClose) + this.destroy(); + }); + if (!Buffer.isBuffer(this.handle)) + this.open(); + } + inherits(ReadStream, ReadableStream2); + ReadStream.prototype.open = function() { + if (this._opening) + return; + this._opening = true; + this.sftp.open(this.path, this.flags, this.mode, (er, handle) => { + this._opening = false; + if (er) { + this.emit("error", er); + if (this.autoClose) + this.destroy(); + return; + } + this.handle = handle; + this.emit("open", handle); + this.emit("ready"); + this.read(); + }); + }; + ReadStream.prototype._read = function(n) { + if (!Buffer.isBuffer(this.handle)) + return this.once("open", () => this._read(n)); + if (this.destroyed) + return; + if (!pool || pool.length - pool.used < kMinPoolSpace) { + allocNewPool(this.readableHighWaterMark || this._readableState.highWaterMark); + } + const thisPool = pool; + let toRead = Math.min(pool.length - pool.used, n); + const start = pool.used; + if (this.end !== void 0) + toRead = Math.min(this.end - this.pos + 1, toRead); + if (toRead <= 0) + return this.push(null); + this.sftp.read( + this.handle, + pool, + pool.used, + toRead, + this.pos, + (er, bytesRead) => { + if (er) { + this.emit("error", er); + if (this.autoClose) + this.destroy(); + return; + } + let b = null; + if (start + toRead === thisPool.used && thisPool === pool) { + thisPool.used = roundUpToMultipleOf8(thisPool.used + bytesRead - toRead); + } else { + const alignedEnd = start + toRead & ~7; + const alignedStart = roundUpToMultipleOf8(start + bytesRead); + if (alignedEnd - alignedStart >= kMinPoolSpace) + poolFragments.push(thisPool.slice(alignedStart, alignedEnd)); + } + if (bytesRead > 0) { + this.bytesRead += bytesRead; + b = thisPool.slice(start, start + bytesRead); + } + this.pos += bytesRead; + this.push(b); + } + ); + pool.used = roundUpToMultipleOf8(pool.used + toRead); + }; + ReadStream.prototype._destroy = function(err, cb) { + if (this._opening && !Buffer.isBuffer(this.handle)) { + this.once("open", closeStream.bind(null, this, cb, err)); + return; + } + closeStream(this, cb, err); + this.handle = null; + this._opening = false; + }; + function closeStream(stream2, cb, err) { + if (!stream2.handle) + return onclose(); + stream2.sftp.close(stream2.handle, onclose); + function onclose(er) { + er = er || err; + cb(er); + stream2.isClosed = true; + if (!er) + stream2.emit("close"); + } + } + ReadStream.prototype.close = function(cb) { + this.destroy(null, cb); + }; + Object.defineProperty(ReadStream.prototype, "pending", { + get() { + return this.handle === null; + }, + configurable: true + }); + function WriteStream(sftp, path, options) { + if (options === void 0) + options = {}; + else if (typeof options === "string") + options = { encoding: options }; + else if (options === null || typeof options !== "object") + throw new TypeError('"options" argument must be a string or an object'); + else + options = Object.create(options); + options.emitClose = false; + options.autoDestroy = false; + WritableStream.call(this, options); + this.path = path; + this.flags = options.flags === void 0 ? "w" : options.flags; + this.mode = options.mode === void 0 ? 438 : options.mode; + this.start = options.start; + this.autoClose = options.autoClose === void 0 ? true : options.autoClose; + this.pos = 0; + this.bytesWritten = 0; + this.isClosed = false; + this.handle = options.handle === void 0 ? null : options.handle; + this.sftp = sftp; + this._opening = false; + if (this.start !== void 0) { + checkPosition(this.start, "start"); + this.pos = this.start; + } + if (options.encoding) + this.setDefaultEncoding(options.encoding); + this.on("finish", function() { + if (this._writableState.finalCalled) + return; + if (this.autoClose) + this.destroy(); + }); + if (!Buffer.isBuffer(this.handle)) + this.open(); + } + inherits(WriteStream, WritableStream); + WriteStream.prototype._final = function(cb) { + if (this.autoClose) + this.destroy(); + cb(); + }; + WriteStream.prototype.open = function() { + if (this._opening) + return; + this._opening = true; + this.sftp.open(this.path, this.flags, this.mode, (er, handle) => { + this._opening = false; + if (er) { + this.emit("error", er); + if (this.autoClose) + this.destroy(); + return; + } + this.handle = handle; + const tryAgain = (err) => { + if (err) { + this.sftp.chmod(this.path, this.mode, (err_) => tryAgain()); + return; + } + if (this.flags[0] === "a") { + const tryStat = (err2, st) => { + if (err2) { + this.sftp.stat(this.path, (err_, st_) => { + if (err_) { + this.destroy(); + this.emit("error", err2); + return; + } + tryStat(null, st_); + }); + return; + } + this.pos = st.size; + this.emit("open", handle); + this.emit("ready"); + }; + this.sftp.fstat(handle, tryStat); + return; + } + this.emit("open", handle); + this.emit("ready"); + }; + this.sftp.fchmod(handle, this.mode, tryAgain); + }); + }; + WriteStream.prototype._write = function(data, encoding, cb) { + if (!Buffer.isBuffer(data)) { + const err = new ERR_INVALID_ARG_TYPE("data", "Buffer", data); + return this.emit("error", err); + } + if (!Buffer.isBuffer(this.handle)) { + return this.once("open", function() { + this._write(data, encoding, cb); + }); + } + this.sftp.write( + this.handle, + data, + 0, + data.length, + this.pos, + (er, bytes) => { + if (er) { + if (this.autoClose) + this.destroy(); + return cb(er); + } + this.bytesWritten += bytes; + cb(); + } + ); + this.pos += data.length; + }; + WriteStream.prototype._writev = function(data, cb) { + if (!Buffer.isBuffer(this.handle)) { + return this.once("open", function() { + this._writev(data, cb); + }); + } + const sftp = this.sftp; + const handle = this.handle; + let writesLeft = data.length; + const onwrite = (er, bytes) => { + if (er) { + this.destroy(); + return cb(er); + } + this.bytesWritten += bytes; + if (--writesLeft === 0) + cb(); + }; + for (let i = 0; i < data.length; ++i) { + const chunk = data[i].chunk; + sftp.write(handle, chunk, 0, chunk.length, this.pos, onwrite); + this.pos += chunk.length; + } + }; + if (typeof WritableStream.prototype.destroy !== "function") + WriteStream.prototype.destroy = ReadStream.prototype.destroy; + WriteStream.prototype._destroy = ReadStream.prototype._destroy; + WriteStream.prototype.close = function(cb) { + if (cb) { + if (this.isClosed) { + process.nextTick(cb); + return; + } + this.on("close", cb); + } + if (!this.autoClose) + this.on("finish", this.destroy.bind(this)); + this.end(); + }; + WriteStream.prototype.destroySoon = WriteStream.prototype.end; + Object.defineProperty(WriteStream.prototype, "pending", { + get() { + return this.handle === null; + }, + configurable: true + }); + module2.exports = { + flagsToString, + OPEN_MODE, + SFTP, + Stats, + STATUS_CODE, + stringToFlags + }; + } +}); + +// node_modules/ssh2/lib/Channel.js +var require_Channel = __commonJS({ + "node_modules/ssh2/lib/Channel.js"(exports2, module2) { + "use strict"; + var { + Duplex: DuplexStream, + Readable: ReadableStream2, + Writable: WritableStream + } = require("stream"); + var { + CHANNEL_EXTENDED_DATATYPE: { STDERR } + } = require_constants6(); + var { bufferSlice } = require_utils3(); + var PACKET_SIZE = 32 * 1024; + var MAX_WINDOW = 2 * 1024 * 1024; + var WINDOW_THRESHOLD = MAX_WINDOW / 2; + var ClientStderr = class extends ReadableStream2 { + constructor(channel, streamOpts) { + super(streamOpts); + this._channel = channel; + } + _read(n) { + if (this._channel._waitChanDrain) { + this._channel._waitChanDrain = false; + if (this._channel.incoming.window <= WINDOW_THRESHOLD) + windowAdjust(this._channel); + } + } + }; + var ServerStderr = class extends WritableStream { + constructor(channel) { + super({ highWaterMark: MAX_WINDOW }); + this._channel = channel; + } + _write(data, encoding, cb) { + const channel = this._channel; + const protocol = channel._client._protocol; + const outgoing = channel.outgoing; + const packetSize = outgoing.packetSize; + const id = outgoing.id; + let window2 = outgoing.window; + const len = data.length; + let p = 0; + if (outgoing.state !== "open") + return; + while (len - p > 0 && window2 > 0) { + let sliceLen = len - p; + if (sliceLen > window2) + sliceLen = window2; + if (sliceLen > packetSize) + sliceLen = packetSize; + if (p === 0 && sliceLen === len) + protocol.channelExtData(id, data, STDERR); + else + protocol.channelExtData(id, bufferSlice(data, p, p + sliceLen), STDERR); + p += sliceLen; + window2 -= sliceLen; + } + outgoing.window = window2; + if (len - p > 0) { + if (window2 === 0) + channel._waitWindow = true; + if (p > 0) + channel._chunkErr = bufferSlice(data, p, len); + else + channel._chunkErr = data; + channel._chunkcbErr = cb; + return; + } + cb(); + } + }; + var Channel = class extends DuplexStream { + constructor(client, info2, opts) { + const streamOpts = { + highWaterMark: MAX_WINDOW, + allowHalfOpen: !opts || opts && opts.allowHalfOpen !== false, + emitClose: false + }; + super(streamOpts); + this.allowHalfOpen = streamOpts.allowHalfOpen; + const server = !!(opts && opts.server); + this.server = server; + this.type = info2.type; + this.subtype = void 0; + this.incoming = info2.incoming; + this.outgoing = info2.outgoing; + this._callbacks = []; + this._client = client; + this._hasX11 = false; + this._exit = { + code: void 0, + signal: void 0, + dump: void 0, + desc: void 0 + }; + this.stdin = this.stdout = this; + if (server) + this.stderr = new ServerStderr(this); + else + this.stderr = new ClientStderr(this, streamOpts); + this._waitWindow = false; + this._waitChanDrain = false; + this._chunk = void 0; + this._chunkcb = void 0; + this._chunkErr = void 0; + this._chunkcbErr = void 0; + this.on("finish", onFinish).on("prefinish", onFinish); + this.on("end", onEnd).on("close", onEnd); + } + _read(n) { + if (this._waitChanDrain) { + this._waitChanDrain = false; + if (this.incoming.window <= WINDOW_THRESHOLD) + windowAdjust(this); + } + } + _write(data, encoding, cb) { + const protocol = this._client._protocol; + const outgoing = this.outgoing; + const packetSize = outgoing.packetSize; + const id = outgoing.id; + let window2 = outgoing.window; + const len = data.length; + let p = 0; + if (outgoing.state !== "open") + return; + while (len - p > 0 && window2 > 0) { + let sliceLen = len - p; + if (sliceLen > window2) + sliceLen = window2; + if (sliceLen > packetSize) + sliceLen = packetSize; + if (p === 0 && sliceLen === len) + protocol.channelData(id, data); + else + protocol.channelData(id, bufferSlice(data, p, p + sliceLen)); + p += sliceLen; + window2 -= sliceLen; + } + outgoing.window = window2; + if (len - p > 0) { + if (window2 === 0) + this._waitWindow = true; + if (p > 0) + this._chunk = bufferSlice(data, p, len); + else + this._chunk = data; + this._chunkcb = cb; + return; + } + cb(); + } + eof() { + if (this.outgoing.state === "open") { + this.outgoing.state = "eof"; + this._client._protocol.channelEOF(this.outgoing.id); + } + } + close() { + if (this.outgoing.state === "open" || this.outgoing.state === "eof") { + this.outgoing.state = "closing"; + this._client._protocol.channelClose(this.outgoing.id); + } + } + destroy() { + this.end(); + this.close(); + return this; + } + // Session type-specific methods ============================================= + setWindow(rows, cols, height, width) { + if (this.server) + throw new Error("Client-only method called in server mode"); + if (this.type === "session" && (this.subtype === "shell" || this.subtype === "exec") && this.writable && this.outgoing.state === "open") { + this._client._protocol.windowChange( + this.outgoing.id, + rows, + cols, + height, + width + ); + } + } + signal(signalName) { + if (this.server) + throw new Error("Client-only method called in server mode"); + if (this.type === "session" && this.writable && this.outgoing.state === "open") { + this._client._protocol.signal(this.outgoing.id, signalName); + } + } + exit(statusOrSignal, coreDumped, msg) { + if (!this.server) + throw new Error("Server-only method called in client mode"); + if (this.type === "session" && this.writable && this.outgoing.state === "open") { + if (typeof statusOrSignal === "number") { + this._client._protocol.exitStatus(this.outgoing.id, statusOrSignal); + } else { + this._client._protocol.exitSignal( + this.outgoing.id, + statusOrSignal, + coreDumped, + msg + ); + } + } + } + }; + function onFinish() { + this.eof(); + if (this.server || !this.allowHalfOpen) + this.close(); + this.writable = false; + } + function onEnd() { + this.readable = false; + } + function windowAdjust(self2) { + if (self2.outgoing.state === "closed") + return; + const amt = MAX_WINDOW - self2.incoming.window; + if (amt <= 0) + return; + self2.incoming.window += amt; + self2._client._protocol.channelWindowAdjust(self2.outgoing.id, amt); + } + module2.exports = { + Channel, + MAX_WINDOW, + PACKET_SIZE, + windowAdjust, + WINDOW_THRESHOLD + }; + } +}); + +// node_modules/ssh2/lib/utils.js +var require_utils4 = __commonJS({ + "node_modules/ssh2/lib/utils.js"(exports2, module2) { + "use strict"; + var { SFTP } = require_SFTP(); + var MAX_CHANNEL = 2 ** 32 - 1; + function onChannelOpenFailure(self2, recipient, info2, cb) { + self2._chanMgr.remove(recipient); + if (typeof cb !== "function") + return; + let err; + if (info2 instanceof Error) { + err = info2; + } else if (typeof info2 === "object" && info2 !== null) { + err = new Error(`(SSH) Channel open failure: ${info2.description}`); + err.reason = info2.reason; + } else { + err = new Error( + "(SSH) Channel open failure: server closed channel unexpectedly" + ); + err.reason = ""; + } + cb(err); + } + function onCHANNEL_CLOSE(self2, recipient, channel, err, dead) { + if (typeof channel === "function") { + onChannelOpenFailure(self2, recipient, err, channel); + return; + } + if (typeof channel !== "object" || channel === null) + return; + if (channel.incoming && channel.incoming.state === "closed") + return; + self2._chanMgr.remove(recipient); + if (channel.server && channel.constructor.name === "Session") + return; + channel.incoming.state = "closed"; + if (channel.readable) + channel.push(null); + if (channel.server) { + if (channel.stderr.writable) + channel.stderr.end(); + } else if (channel.stderr.readable) { + channel.stderr.push(null); + } + if (channel.constructor !== SFTP && (channel.outgoing.state === "open" || channel.outgoing.state === "eof") && !dead) { + channel.close(); + } + if (channel.outgoing.state === "closing") + channel.outgoing.state = "closed"; + const readState = channel._readableState; + const writeState = channel._writableState; + if (writeState && !writeState.ending && !writeState.finished && !dead) + channel.end(); + const chanCallbacks = channel._callbacks; + channel._callbacks = []; + for (let i = 0; i < chanCallbacks.length; ++i) + chanCallbacks[i](true); + if (channel.server) { + if (!channel.readable || channel.destroyed || readState && readState.endEmitted) { + channel.emit("close"); + } else { + channel.once("end", () => channel.emit("close")); + } + } else { + let doClose; + switch (channel.type) { + case "direct-streamlocal@openssh.com": + case "direct-tcpip": + doClose = () => channel.emit("close"); + break; + default: { + const exit = channel._exit; + doClose = () => { + if (exit.code === null) + channel.emit("close", exit.code, exit.signal, exit.dump, exit.desc); + else + channel.emit("close", exit.code); + }; + } + } + if (!channel.readable || channel.destroyed || readState && readState.endEmitted) { + doClose(); + } else { + channel.once("end", doClose); + } + const errReadState = channel.stderr._readableState; + if (!channel.stderr.readable || channel.stderr.destroyed || errReadState && errReadState.endEmitted) { + channel.stderr.emit("close"); + } else { + channel.stderr.once("end", () => channel.stderr.emit("close")); + } + } + } + var ChannelManager = class { + constructor(client) { + this._client = client; + this._channels = {}; + this._cur = -1; + this._count = 0; + } + add(val) { + let id; + if (this._cur < MAX_CHANNEL) { + id = ++this._cur; + } else if (this._count === 0) { + this._cur = 0; + id = 0; + } else { + const channels = this._channels; + for (let i = 0; i < MAX_CHANNEL; ++i) { + if (channels[i] === void 0) { + id = i; + break; + } + } + } + if (id === void 0) + return -1; + this._channels[id] = val || true; + ++this._count; + return id; + } + update(id, val) { + if (typeof id !== "number" || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) + throw new Error(`Invalid channel id: ${id}`); + if (val && this._channels[id]) + this._channels[id] = val; + } + get(id) { + if (typeof id !== "number" || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) + throw new Error(`Invalid channel id: ${id}`); + return this._channels[id]; + } + remove(id) { + if (typeof id !== "number" || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) + throw new Error(`Invalid channel id: ${id}`); + if (this._channels[id]) { + delete this._channels[id]; + if (this._count) + --this._count; + } + } + cleanup(err) { + const channels = this._channels; + this._channels = {}; + this._cur = -1; + this._count = 0; + const chanIDs = Object.keys(channels); + const client = this._client; + for (let i = 0; i < chanIDs.length; ++i) { + const id = +chanIDs[i]; + const channel = channels[id]; + onCHANNEL_CLOSE(client, id, channel._channel || channel, err, true); + } + } + }; + var isRegExp = /* @__PURE__ */ (() => { + const toString = Object.prototype.toString; + return (val) => toString.call(val) === "[object RegExp]"; + })(); + function generateAlgorithmList(algoList, defaultList, supportedList) { + if (Array.isArray(algoList) && algoList.length > 0) { + for (let i = 0; i < algoList.length; ++i) { + if (supportedList.indexOf(algoList[i]) === -1) + throw new Error(`Unsupported algorithm: ${algoList[i]}`); + } + return algoList; + } + if (typeof algoList === "object" && algoList !== null) { + const keys = Object.keys(algoList); + let list = defaultList; + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + let val = algoList[key]; + switch (key) { + case "append": + if (!Array.isArray(val)) + val = [val]; + if (Array.isArray(val)) { + for (let j = 0; j < val.length; ++j) { + const append = val[j]; + if (typeof append === "string") { + if (!append || list.indexOf(append) !== -1) + continue; + if (supportedList.indexOf(append) === -1) + throw new Error(`Unsupported algorithm: ${append}`); + if (list === defaultList) + list = list.slice(); + list.push(append); + } else if (isRegExp(append)) { + for (let k = 0; k < supportedList.length; ++k) { + const algo = supportedList[k]; + if (append.test(algo)) { + if (list.indexOf(algo) !== -1) + continue; + if (list === defaultList) + list = list.slice(); + list.push(algo); + } + } + } + } + } + break; + case "prepend": + if (!Array.isArray(val)) + val = [val]; + if (Array.isArray(val)) { + for (let j = val.length; j >= 0; --j) { + const prepend = val[j]; + if (typeof prepend === "string") { + if (!prepend || list.indexOf(prepend) !== -1) + continue; + if (supportedList.indexOf(prepend) === -1) + throw new Error(`Unsupported algorithm: ${prepend}`); + if (list === defaultList) + list = list.slice(); + list.unshift(prepend); + } else if (isRegExp(prepend)) { + for (let k = supportedList.length; k >= 0; --k) { + const algo = supportedList[k]; + if (prepend.test(algo)) { + if (list.indexOf(algo) !== -1) + continue; + if (list === defaultList) + list = list.slice(); + list.unshift(algo); + } + } + } + } + } + break; + case "remove": + if (!Array.isArray(val)) + val = [val]; + if (Array.isArray(val)) { + for (let j = 0; j < val.length; ++j) { + const search = val[j]; + if (typeof search === "string") { + if (!search) + continue; + const idx = list.indexOf(search); + if (idx === -1) + continue; + if (list === defaultList) + list = list.slice(); + list.splice(idx, 1); + } else if (isRegExp(search)) { + for (let k = 0; k < list.length; ++k) { + if (search.test(list[k])) { + if (list === defaultList) + list = list.slice(); + list.splice(k, 1); + --k; + } + } + } + } + } + break; + } + } + return list; + } + return defaultList; + } + module2.exports = { + ChannelManager, + generateAlgorithmList, + onChannelOpenFailure, + onCHANNEL_CLOSE, + isWritable: (stream2) => { + return stream2 && stream2.writable && stream2._readableState && stream2._readableState.ended === false; + } + }; + } +}); + +// node_modules/ssh2/lib/client.js +var require_client2 = __commonJS({ + "node_modules/ssh2/lib/client.js"(exports2, module2) { + "use strict"; + var { + createHash, + getHashes, + randomFillSync + } = require("crypto"); + var { Socket } = require("net"); + var { lookup: dnsLookup } = require("dns"); + var EventEmitter = require("events"); + var HASHES = getHashes(); + var { + COMPAT, + CHANNEL_EXTENDED_DATATYPE: { STDERR }, + CHANNEL_OPEN_FAILURE, + DEFAULT_CIPHER, + DEFAULT_COMPRESSION, + DEFAULT_KEX, + DEFAULT_MAC, + DEFAULT_SERVER_HOST_KEY, + DISCONNECT_REASON, + DISCONNECT_REASON_BY_VALUE, + SUPPORTED_CIPHER, + SUPPORTED_COMPRESSION, + SUPPORTED_KEX, + SUPPORTED_MAC, + SUPPORTED_SERVER_HOST_KEY + } = require_constants6(); + var { init: cryptoInit } = require_crypto(); + var Protocol = require_Protocol(); + var { parseKey } = require_keyParser(); + var { SFTP } = require_SFTP(); + var { + bufferCopy, + makeBufferParser, + makeError, + readUInt32BE, + sigSSHToASN1, + writeUInt32BE + } = require_utils3(); + var { AgentContext, createAgent, isAgent } = require_agent2(); + var { + Channel, + MAX_WINDOW, + PACKET_SIZE, + windowAdjust, + WINDOW_THRESHOLD + } = require_Channel(); + var { + ChannelManager, + generateAlgorithmList, + isWritable, + onChannelOpenFailure, + onCHANNEL_CLOSE + } = require_utils4(); + var bufferParser = makeBufferParser(); + var sigParser = makeBufferParser(); + var RE_OPENSSH = /^OpenSSH_(?:(?![0-4])\d)|(?:\d{2,})/; + var noop3 = (err) => { + }; + var Client = class extends EventEmitter { + constructor() { + super(); + this.config = { + host: void 0, + port: void 0, + localAddress: void 0, + localPort: void 0, + forceIPv4: void 0, + forceIPv6: void 0, + keepaliveCountMax: void 0, + keepaliveInterval: void 0, + readyTimeout: void 0, + ident: void 0, + username: void 0, + password: void 0, + privateKey: void 0, + tryKeyboard: void 0, + agent: void 0, + allowAgentFwd: void 0, + authHandler: void 0, + hostHashAlgo: void 0, + hostHashCb: void 0, + strictVendor: void 0, + debug: void 0 + }; + this._agent = void 0; + this._readyTimeout = void 0; + this._chanMgr = void 0; + this._callbacks = void 0; + this._forwarding = void 0; + this._forwardingUnix = void 0; + this._acceptX11 = void 0; + this._agentFwdEnabled = void 0; + this._remoteVer = void 0; + this._protocol = void 0; + this._sock = void 0; + this._resetKA = void 0; + } + connect(cfg) { + if (this._sock && isWritable(this._sock)) { + this.once("close", () => { + this.connect(cfg); + }); + this.end(); + return this; + } + this.config.host = cfg.hostname || cfg.host || "localhost"; + this.config.port = cfg.port || 22; + this.config.localAddress = typeof cfg.localAddress === "string" ? cfg.localAddress : void 0; + this.config.localPort = typeof cfg.localPort === "string" || typeof cfg.localPort === "number" ? cfg.localPort : void 0; + this.config.forceIPv4 = cfg.forceIPv4 || false; + this.config.forceIPv6 = cfg.forceIPv6 || false; + this.config.keepaliveCountMax = typeof cfg.keepaliveCountMax === "number" && cfg.keepaliveCountMax >= 0 ? cfg.keepaliveCountMax : 3; + this.config.keepaliveInterval = typeof cfg.keepaliveInterval === "number" && cfg.keepaliveInterval > 0 ? cfg.keepaliveInterval : 0; + this.config.readyTimeout = typeof cfg.readyTimeout === "number" && cfg.readyTimeout >= 0 ? cfg.readyTimeout : 2e4; + this.config.ident = typeof cfg.ident === "string" || Buffer.isBuffer(cfg.ident) ? cfg.ident : void 0; + const algorithms = { + kex: void 0, + serverHostKey: void 0, + cs: { + cipher: void 0, + mac: void 0, + compress: void 0, + lang: [] + }, + sc: void 0 + }; + let allOfferDefaults = true; + if (typeof cfg.algorithms === "object" && cfg.algorithms !== null) { + algorithms.kex = generateAlgorithmList( + cfg.algorithms.kex, + DEFAULT_KEX, + SUPPORTED_KEX + ); + if (algorithms.kex !== DEFAULT_KEX) + allOfferDefaults = false; + algorithms.serverHostKey = generateAlgorithmList( + cfg.algorithms.serverHostKey, + DEFAULT_SERVER_HOST_KEY, + SUPPORTED_SERVER_HOST_KEY + ); + if (algorithms.serverHostKey !== DEFAULT_SERVER_HOST_KEY) + allOfferDefaults = false; + algorithms.cs.cipher = generateAlgorithmList( + cfg.algorithms.cipher, + DEFAULT_CIPHER, + SUPPORTED_CIPHER + ); + if (algorithms.cs.cipher !== DEFAULT_CIPHER) + allOfferDefaults = false; + algorithms.cs.mac = generateAlgorithmList( + cfg.algorithms.hmac, + DEFAULT_MAC, + SUPPORTED_MAC + ); + if (algorithms.cs.mac !== DEFAULT_MAC) + allOfferDefaults = false; + algorithms.cs.compress = generateAlgorithmList( + cfg.algorithms.compress, + DEFAULT_COMPRESSION, + SUPPORTED_COMPRESSION + ); + if (algorithms.cs.compress !== DEFAULT_COMPRESSION) + allOfferDefaults = false; + if (!allOfferDefaults) + algorithms.sc = algorithms.cs; + } + if (typeof cfg.username === "string") + this.config.username = cfg.username; + else if (typeof cfg.user === "string") + this.config.username = cfg.user; + else + throw new Error("Invalid username"); + this.config.password = typeof cfg.password === "string" ? cfg.password : void 0; + this.config.privateKey = typeof cfg.privateKey === "string" || Buffer.isBuffer(cfg.privateKey) ? cfg.privateKey : void 0; + this.config.localHostname = typeof cfg.localHostname === "string" ? cfg.localHostname : void 0; + this.config.localUsername = typeof cfg.localUsername === "string" ? cfg.localUsername : void 0; + this.config.tryKeyboard = cfg.tryKeyboard === true; + if (typeof cfg.agent === "string" && cfg.agent.length) + this.config.agent = createAgent(cfg.agent); + else if (isAgent(cfg.agent)) + this.config.agent = cfg.agent; + else + this.config.agent = void 0; + this.config.allowAgentFwd = cfg.agentForward === true && this.config.agent !== void 0; + let authHandler = this.config.authHandler = typeof cfg.authHandler === "function" || Array.isArray(cfg.authHandler) ? cfg.authHandler : void 0; + this.config.strictVendor = typeof cfg.strictVendor === "boolean" ? cfg.strictVendor : true; + const debug2 = this.config.debug = typeof cfg.debug === "function" ? cfg.debug : void 0; + if (cfg.agentForward === true && !this.config.allowAgentFwd) { + throw new Error( + "You must set a valid agent path to allow agent forwarding" + ); + } + let callbacks = this._callbacks = []; + this._chanMgr = new ChannelManager(this); + this._forwarding = {}; + this._forwardingUnix = {}; + this._acceptX11 = 0; + this._agentFwdEnabled = false; + this._agent = this.config.agent ? this.config.agent : void 0; + this._remoteVer = void 0; + let privateKey; + if (this.config.privateKey) { + privateKey = parseKey(this.config.privateKey, cfg.passphrase); + if (privateKey instanceof Error) + throw new Error(`Cannot parse privateKey: ${privateKey.message}`); + if (Array.isArray(privateKey)) { + privateKey = privateKey[0]; + } + if (privateKey.getPrivatePEM() === null) { + throw new Error( + "privateKey value does not contain a (valid) private key" + ); + } + } + let hostVerifier; + if (typeof cfg.hostVerifier === "function") { + const hashCb = cfg.hostVerifier; + let hashAlgo; + if (HASHES.indexOf(cfg.hostHash) !== -1) { + hashAlgo = cfg.hostHash; + } + hostVerifier = (key, verify) => { + if (hashAlgo) + key = createHash(hashAlgo).update(key).digest("hex"); + const ret = hashCb(key, verify); + if (ret !== void 0) + verify(ret); + }; + } + const sock = this._sock = cfg.sock || new Socket(); + let ready = false; + let sawHeader = false; + if (this._protocol) + this._protocol.cleanup(); + const DEBUG_HANDLER = !debug2 ? void 0 : (p, display, msg) => { + debug2(`Debug output from server: ${JSON.stringify(msg)}`); + }; + let serverSigAlgs; + const proto = this._protocol = new Protocol({ + ident: this.config.ident, + offer: allOfferDefaults ? void 0 : algorithms, + onWrite: (data) => { + if (isWritable(sock)) + sock.write(data); + }, + onError: (err) => { + if (err.level === "handshake") + clearTimeout(this._readyTimeout); + if (!proto._destruct) + sock.removeAllListeners("data"); + this.emit("error", err); + try { + sock.end(); + } catch { + } + }, + onHeader: (header) => { + sawHeader = true; + this._remoteVer = header.versions.software; + if (header.greeting) + this.emit("greeting", header.greeting); + }, + onHandshakeComplete: (negotiated) => { + this.emit("handshake", negotiated); + if (!ready) { + ready = true; + proto.service("ssh-userauth"); + } + }, + debug: debug2, + hostVerifier, + messageHandlers: { + DEBUG: DEBUG_HANDLER, + DISCONNECT: (p, reason, desc) => { + if (reason !== DISCONNECT_REASON.BY_APPLICATION) { + if (!desc) { + desc = DISCONNECT_REASON_BY_VALUE[reason]; + if (desc === void 0) + desc = `Unexpected disconnection reason: ${reason}`; + } + const err = new Error(desc); + err.code = reason; + this.emit("error", err); + } + sock.end(); + }, + SERVICE_ACCEPT: (p, name) => { + if (name === "ssh-userauth") + tryNextAuth(); + }, + EXT_INFO: (p, exts) => { + if (serverSigAlgs === void 0) { + for (const ext of exts) { + if (ext.name === "server-sig-algs") { + serverSigAlgs = ext.algs; + return; + } + } + serverSigAlgs = null; + } + }, + USERAUTH_BANNER: (p, msg) => { + this.emit("banner", msg); + }, + USERAUTH_SUCCESS: (p) => { + resetKA(); + clearTimeout(this._readyTimeout); + this.emit("ready"); + }, + USERAUTH_FAILURE: (p, authMethods, partialSuccess) => { + if (curAuth.keyAlgos) { + const oldKeyAlgo = curAuth.keyAlgos[0][0]; + if (debug2) + debug2(`Client: ${curAuth.type} (${oldKeyAlgo}) auth failed`); + curAuth.keyAlgos.shift(); + if (curAuth.keyAlgos.length) { + const [keyAlgo, hashAlgo] = curAuth.keyAlgos[0]; + switch (curAuth.type) { + case "agent": + proto.authPK( + curAuth.username, + curAuth.agentCtx.currentKey(), + keyAlgo + ); + return; + case "publickey": + proto.authPK(curAuth.username, curAuth.key, keyAlgo); + return; + case "hostbased": + proto.authHostbased( + curAuth.username, + curAuth.key, + curAuth.localHostname, + curAuth.localUsername, + keyAlgo, + (buf, cb) => { + const signature = curAuth.key.sign(buf, hashAlgo); + if (signature instanceof Error) { + signature.message = `Error while signing with key: ${signature.message}`; + signature.level = "client-authentication"; + this.emit("error", signature); + return tryNextAuth(); + } + cb(signature); + } + ); + return; + } + } else { + curAuth.keyAlgos = void 0; + } + } + if (curAuth.type === "agent") { + const pos = curAuth.agentCtx.pos(); + debug2 && debug2(`Client: Agent key #${pos + 1} failed`); + return tryNextAgentKey(); + } + debug2 && debug2(`Client: ${curAuth.type} auth failed`); + curPartial = partialSuccess; + curAuthsLeft = authMethods; + tryNextAuth(); + }, + USERAUTH_PASSWD_CHANGEREQ: (p, prompt) => { + if (curAuth.type === "password") { + this.emit("change password", prompt, (newPassword) => { + proto.authPassword( + this.config.username, + this.config.password, + newPassword + ); + }); + } + }, + USERAUTH_PK_OK: (p) => { + let keyAlgo; + let hashAlgo; + if (curAuth.keyAlgos) + [keyAlgo, hashAlgo] = curAuth.keyAlgos[0]; + if (curAuth.type === "agent") { + const key = curAuth.agentCtx.currentKey(); + proto.authPK(curAuth.username, key, keyAlgo, (buf, cb) => { + const opts = { hash: hashAlgo }; + curAuth.agentCtx.sign(key, buf, opts, (err, signed) => { + if (err) { + err.level = "agent"; + this.emit("error", err); + } else { + return cb(signed); + } + tryNextAgentKey(); + }); + }); + } else if (curAuth.type === "publickey") { + proto.authPK(curAuth.username, curAuth.key, keyAlgo, (buf, cb) => { + const signature = curAuth.key.sign(buf, hashAlgo); + if (signature instanceof Error) { + signature.message = `Error signing data with key: ${signature.message}`; + signature.level = "client-authentication"; + this.emit("error", signature); + return tryNextAuth(); + } + cb(signature); + }); + } + }, + USERAUTH_INFO_REQUEST: (p, name, instructions, prompts) => { + if (curAuth.type === "keyboard-interactive") { + const nprompts = Array.isArray(prompts) ? prompts.length : 0; + if (nprompts === 0) { + debug2 && debug2( + "Client: Sending automatic USERAUTH_INFO_RESPONSE" + ); + proto.authInfoRes(); + return; + } + curAuth.prompt( + name, + instructions, + "", + prompts, + (answers) => { + proto.authInfoRes(answers); + } + ); + } + }, + REQUEST_SUCCESS: (p, data) => { + if (callbacks.length) + callbacks.shift()(false, data); + }, + REQUEST_FAILURE: (p) => { + if (callbacks.length) + callbacks.shift()(true); + }, + GLOBAL_REQUEST: (p, name, wantReply, data) => { + switch (name) { + case "hostkeys-00@openssh.com": + hostKeysProve(this, data, (err, keys) => { + if (err) + return; + this.emit("hostkeys", keys); + }); + if (wantReply) + proto.requestSuccess(); + break; + default: + if (wantReply) + proto.requestFailure(); + } + }, + CHANNEL_OPEN: (p, info2) => { + onCHANNEL_OPEN(this, info2); + }, + CHANNEL_OPEN_CONFIRMATION: (p, info2) => { + const channel = this._chanMgr.get(info2.recipient); + if (typeof channel !== "function") + return; + const isSFTP = channel.type === "sftp"; + const type = isSFTP ? "session" : channel.type; + const chanInfo = { + type, + incoming: { + id: info2.recipient, + window: MAX_WINDOW, + packetSize: PACKET_SIZE, + state: "open" + }, + outgoing: { + id: info2.sender, + window: info2.window, + packetSize: info2.packetSize, + state: "open" + } + }; + const instance = isSFTP ? new SFTP(this, chanInfo, { debug: debug2 }) : new Channel(this, chanInfo); + this._chanMgr.update(info2.recipient, instance); + channel(void 0, instance); + }, + CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => { + const channel = this._chanMgr.get(recipient); + if (typeof channel !== "function") + return; + const info2 = { reason, description }; + onChannelOpenFailure(this, recipient, info2, channel); + }, + CHANNEL_DATA: (p, recipient, data) => { + const channel = this._chanMgr.get(recipient); + if (typeof channel !== "object" || channel === null) + return; + if (channel.incoming.window === 0) + return; + channel.incoming.window -= data.length; + if (channel.push(data) === false) { + channel._waitChanDrain = true; + return; + } + if (channel.incoming.window <= WINDOW_THRESHOLD) + windowAdjust(channel); + }, + CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => { + if (type !== STDERR) + return; + const channel = this._chanMgr.get(recipient); + if (typeof channel !== "object" || channel === null) + return; + if (channel.incoming.window === 0) + return; + channel.incoming.window -= data.length; + if (!channel.stderr.push(data)) { + channel._waitChanDrain = true; + return; + } + if (channel.incoming.window <= WINDOW_THRESHOLD) + windowAdjust(channel); + }, + CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => { + const channel = this._chanMgr.get(recipient); + if (typeof channel !== "object" || channel === null) + return; + channel.outgoing.window += amount; + if (channel._waitWindow) { + channel._waitWindow = false; + if (channel._chunk) { + channel._write(channel._chunk, null, channel._chunkcb); + } else if (channel._chunkcb) { + channel._chunkcb(); + } else if (channel._chunkErr) { + channel.stderr._write( + channel._chunkErr, + null, + channel._chunkcbErr + ); + } else if (channel._chunkcbErr) { + channel._chunkcbErr(); + } + } + }, + CHANNEL_SUCCESS: (p, recipient) => { + const channel = this._chanMgr.get(recipient); + if (typeof channel !== "object" || channel === null) + return; + this._resetKA(); + if (channel._callbacks.length) + channel._callbacks.shift()(false); + }, + CHANNEL_FAILURE: (p, recipient) => { + const channel = this._chanMgr.get(recipient); + if (typeof channel !== "object" || channel === null) + return; + this._resetKA(); + if (channel._callbacks.length) + channel._callbacks.shift()(true); + }, + CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => { + const channel = this._chanMgr.get(recipient); + if (typeof channel !== "object" || channel === null) + return; + const exit = channel._exit; + if (exit.code !== void 0) + return; + switch (type) { + case "exit-status": + channel.emit("exit", exit.code = data); + return; + case "exit-signal": + channel.emit( + "exit", + exit.code = null, + exit.signal = `SIG${data.signal}`, + exit.dump = data.coreDumped, + exit.desc = data.errorMessage + ); + return; + } + if (wantReply) + p.channelFailure(channel.outgoing.id); + }, + CHANNEL_EOF: (p, recipient) => { + const channel = this._chanMgr.get(recipient); + if (typeof channel !== "object" || channel === null) + return; + if (channel.incoming.state !== "open") + return; + channel.incoming.state = "eof"; + if (channel.readable) + channel.push(null); + if (channel.stderr.readable) + channel.stderr.push(null); + }, + CHANNEL_CLOSE: (p, recipient) => { + onCHANNEL_CLOSE(this, recipient, this._chanMgr.get(recipient)); + } + } + }); + sock.pause(); + const kainterval = this.config.keepaliveInterval; + const kacountmax = this.config.keepaliveCountMax; + let kacount = 0; + let katimer; + const sendKA = () => { + if (++kacount > kacountmax) { + clearInterval(katimer); + if (sock.readable) { + const err = new Error("Keepalive timeout"); + err.level = "client-timeout"; + this.emit("error", err); + sock.destroy(); + } + return; + } + if (isWritable(sock)) { + callbacks.push(resetKA); + proto.ping(); + } else { + clearInterval(katimer); + } + }; + function resetKA() { + if (kainterval > 0) { + kacount = 0; + clearInterval(katimer); + if (isWritable(sock)) + katimer = setInterval(sendKA, kainterval); + } + } + this._resetKA = resetKA; + const onDone = /* @__PURE__ */ (() => { + let called = false; + return () => { + if (called) + return; + called = true; + if (wasConnected && !sawHeader) { + const err = makeError("Connection lost before handshake", "protocol", true); + this.emit("error", err); + } + }; + })(); + const onConnect = /* @__PURE__ */ (() => { + let called = false; + return () => { + if (called) + return; + called = true; + wasConnected = true; + debug2 && debug2("Socket connected"); + this.emit("connect"); + cryptoInit.then(() => { + proto.start(); + sock.on("data", (data) => { + try { + proto.parse(data, 0, data.length); + } catch (ex) { + this.emit("error", ex); + try { + if (isWritable(sock)) + sock.end(); + } catch { + } + } + }); + if (sock.stderr && typeof sock.stderr.resume === "function") + sock.stderr.resume(); + sock.resume(); + }).catch((err) => { + this.emit("error", err); + try { + if (isWritable(sock)) + sock.end(); + } catch { + } + }); + }; + })(); + let wasConnected = false; + sock.on("connect", onConnect).on("timeout", () => { + this.emit("timeout"); + }).on("error", (err) => { + debug2 && debug2(`Socket error: ${err.message}`); + clearTimeout(this._readyTimeout); + err.level = "client-socket"; + this.emit("error", err); + }).on("end", () => { + debug2 && debug2("Socket ended"); + onDone(); + proto.cleanup(); + clearTimeout(this._readyTimeout); + clearInterval(katimer); + this.emit("end"); + }).on("close", () => { + debug2 && debug2("Socket closed"); + onDone(); + proto.cleanup(); + clearTimeout(this._readyTimeout); + clearInterval(katimer); + this.emit("close"); + const callbacks_ = callbacks; + callbacks = this._callbacks = []; + const err = new Error("No response from server"); + for (let i = 0; i < callbacks_.length; ++i) + callbacks_[i](err); + this._chanMgr.cleanup(err); + }); + let curAuth; + let curPartial = null; + let curAuthsLeft = null; + const authsAllowed = ["none"]; + if (this.config.password !== void 0) + authsAllowed.push("password"); + if (privateKey !== void 0) + authsAllowed.push("publickey"); + if (this._agent !== void 0) + authsAllowed.push("agent"); + if (this.config.tryKeyboard) + authsAllowed.push("keyboard-interactive"); + if (privateKey !== void 0 && this.config.localHostname !== void 0 && this.config.localUsername !== void 0) { + authsAllowed.push("hostbased"); + } + if (Array.isArray(authHandler)) + authHandler = makeSimpleAuthHandler(authHandler); + else if (typeof authHandler !== "function") + authHandler = makeSimpleAuthHandler(authsAllowed); + let hasSentAuth = false; + const doNextAuth = (nextAuth) => { + if (hasSentAuth) + return; + hasSentAuth = true; + if (nextAuth === false) { + const err = new Error("All configured authentication methods failed"); + err.level = "client-authentication"; + this.emit("error", err); + this.end(); + return; + } + if (typeof nextAuth === "string") { + const type = nextAuth; + if (authsAllowed.indexOf(type) === -1) + return skipAuth(`Authentication method not allowed: ${type}`); + const username = this.config.username; + switch (type) { + case "password": + nextAuth = { type, username, password: this.config.password }; + break; + case "publickey": + nextAuth = { type, username, key: privateKey }; + break; + case "hostbased": + nextAuth = { + type, + username, + key: privateKey, + localHostname: this.config.localHostname, + localUsername: this.config.localUsername + }; + break; + case "agent": + nextAuth = { + type, + username, + agentCtx: new AgentContext(this._agent) + }; + break; + case "keyboard-interactive": + nextAuth = { + type, + username, + prompt: (...args) => this.emit("keyboard-interactive", ...args) + }; + break; + case "none": + nextAuth = { type, username }; + break; + default: + return skipAuth( + `Skipping unsupported authentication method: ${nextAuth}` + ); + } + } else if (typeof nextAuth !== "object" || nextAuth === null) { + return skipAuth( + `Skipping invalid authentication attempt: ${nextAuth}` + ); + } else { + const username = nextAuth.username; + if (typeof username !== "string") { + return skipAuth( + `Skipping invalid authentication attempt: ${nextAuth}` + ); + } + const type = nextAuth.type; + switch (type) { + case "password": { + const { password } = nextAuth; + if (typeof password !== "string" && !Buffer.isBuffer(password)) + return skipAuth("Skipping invalid password auth attempt"); + nextAuth = { type, username, password }; + break; + } + case "publickey": { + const key = parseKey(nextAuth.key, nextAuth.passphrase); + if (key instanceof Error) + return skipAuth("Skipping invalid key auth attempt"); + if (!key.isPrivateKey()) + return skipAuth("Skipping non-private key"); + nextAuth = { type, username, key }; + break; + } + case "hostbased": { + const { localHostname, localUsername } = nextAuth; + const key = parseKey(nextAuth.key, nextAuth.passphrase); + if (key instanceof Error || typeof localHostname !== "string" || typeof localUsername !== "string") { + return skipAuth("Skipping invalid hostbased auth attempt"); + } + if (!key.isPrivateKey()) + return skipAuth("Skipping non-private key"); + nextAuth = { type, username, key, localHostname, localUsername }; + break; + } + case "agent": { + let agent = nextAuth.agent; + if (typeof agent === "string" && agent.length) { + agent = createAgent(agent); + } else if (!isAgent(agent)) { + return skipAuth( + `Skipping invalid agent: ${nextAuth.agent}` + ); + } + nextAuth = { type, username, agentCtx: new AgentContext(agent) }; + break; + } + case "keyboard-interactive": { + const { prompt } = nextAuth; + if (typeof prompt !== "function") { + return skipAuth( + "Skipping invalid keyboard-interactive auth attempt" + ); + } + nextAuth = { type, username, prompt }; + break; + } + case "none": + nextAuth = { type, username }; + break; + default: + return skipAuth( + `Skipping unsupported authentication method: ${nextAuth}` + ); + } + } + curAuth = nextAuth; + try { + const username = curAuth.username; + switch (curAuth.type) { + case "password": + proto.authPassword(username, curAuth.password); + break; + case "publickey": { + let keyAlgo; + curAuth.keyAlgos = getKeyAlgos(this, curAuth.key, serverSigAlgs); + if (curAuth.keyAlgos) { + if (curAuth.keyAlgos.length) { + keyAlgo = curAuth.keyAlgos[0][0]; + } else { + return skipAuth( + "Skipping key authentication (no mutual hash algorithm)" + ); + } + } + proto.authPK(username, curAuth.key, keyAlgo); + break; + } + case "hostbased": { + let keyAlgo; + let hashAlgo; + curAuth.keyAlgos = getKeyAlgos(this, curAuth.key, serverSigAlgs); + if (curAuth.keyAlgos) { + if (curAuth.keyAlgos.length) { + [keyAlgo, hashAlgo] = curAuth.keyAlgos[0]; + } else { + return skipAuth( + "Skipping hostbased authentication (no mutual hash algorithm)" + ); + } + } + proto.authHostbased( + username, + curAuth.key, + curAuth.localHostname, + curAuth.localUsername, + keyAlgo, + (buf, cb) => { + const signature = curAuth.key.sign(buf, hashAlgo); + if (signature instanceof Error) { + signature.message = `Error while signing with key: ${signature.message}`; + signature.level = "client-authentication"; + this.emit("error", signature); + return tryNextAuth(); + } + cb(signature); + } + ); + break; + } + case "agent": + curAuth.agentCtx.init((err) => { + if (err) { + err.level = "agent"; + this.emit("error", err); + return tryNextAuth(); + } + tryNextAgentKey(); + }); + break; + case "keyboard-interactive": + proto.authKeyboard(username); + break; + case "none": + proto.authNone(username); + break; + } + } finally { + hasSentAuth = false; + } + }; + function skipAuth(msg) { + debug2 && debug2(msg); + process.nextTick(tryNextAuth); + } + function tryNextAuth() { + hasSentAuth = false; + const auth2 = authHandler(curAuthsLeft, curPartial, doNextAuth); + if (hasSentAuth || auth2 === void 0) + return; + doNextAuth(auth2); + } + const tryNextAgentKey = () => { + if (curAuth.type === "agent") { + const key = curAuth.agentCtx.nextKey(); + if (key === false) { + debug2 && debug2("Agent: No more keys left to try"); + debug2 && debug2("Client: agent auth failed"); + tryNextAuth(); + } else { + const pos = curAuth.agentCtx.pos(); + let keyAlgo; + curAuth.keyAlgos = getKeyAlgos(this, key, serverSigAlgs); + if (curAuth.keyAlgos) { + if (curAuth.keyAlgos.length) { + keyAlgo = curAuth.keyAlgos[0][0]; + } else { + debug2 && debug2( + `Agent: Skipping key #${pos + 1} (no mutual hash algorithm)` + ); + tryNextAgentKey(); + return; + } + } + debug2 && debug2(`Agent: Trying key #${pos + 1}`); + proto.authPK(curAuth.username, key, keyAlgo); + } + } + }; + const startTimeout = () => { + if (this.config.readyTimeout > 0) { + this._readyTimeout = setTimeout(() => { + const err = new Error("Timed out while waiting for handshake"); + err.level = "client-timeout"; + this.emit("error", err); + sock.destroy(); + }, this.config.readyTimeout); + } + }; + if (!cfg.sock) { + let host = this.config.host; + const forceIPv4 = this.config.forceIPv4; + const forceIPv6 = this.config.forceIPv6; + debug2 && debug2(`Client: Trying ${host} on port ${this.config.port} ...`); + const doConnect = () => { + startTimeout(); + sock.connect({ + host, + port: this.config.port, + localAddress: this.config.localAddress, + localPort: this.config.localPort + }); + sock.setMaxListeners(0); + sock.setTimeout(typeof cfg.timeout === "number" ? cfg.timeout : 0); + }; + if (!forceIPv4 && !forceIPv6 || forceIPv4 && forceIPv6) { + doConnect(); + } else { + dnsLookup(host, forceIPv4 ? 4 : 6, (err, address, family) => { + if (err) { + const type = forceIPv4 ? "IPv4" : "IPv6"; + const error2 = new Error( + `Error while looking up ${type} address for '${host}': ${err}` + ); + clearTimeout(this._readyTimeout); + error2.level = "client-dns"; + this.emit("error", error2); + this.emit("close"); + return; + } + host = address; + doConnect(); + }); + } + } else { + startTimeout(); + if (typeof sock.connecting === "boolean") { + if (!sock.connecting) { + onConnect(); + } + } else { + onConnect(); + } + } + return this; + } + end() { + if (this._sock && isWritable(this._sock)) { + this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION); + this._sock.end(); + } + return this; + } + destroy() { + this._sock && isWritable(this._sock) && this._sock.destroy(); + return this; + } + exec(cmd, opts, cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error("Not connected"); + if (typeof opts === "function") { + cb = opts; + opts = {}; + } + const extraOpts = { allowHalfOpen: opts.allowHalfOpen !== false }; + openChannel(this, "session", extraOpts, (err, chan) => { + if (err) { + cb(err); + return; + } + const todo = []; + function reqCb(err2) { + if (err2) { + chan.close(); + cb(err2); + return; + } + if (todo.length) + todo.shift()(); + } + if (this.config.allowAgentFwd === true || opts && opts.agentForward === true && this._agent !== void 0) { + todo.push(() => reqAgentFwd(chan, reqCb)); + } + if (typeof opts === "object" && opts !== null) { + if (typeof opts.env === "object" && opts.env !== null) + reqEnv(chan, opts.env); + if (typeof opts.pty === "object" && opts.pty !== null || opts.pty === true) { + todo.push(() => reqPty(chan, opts.pty, reqCb)); + } + if (typeof opts.x11 === "object" && opts.x11 !== null || opts.x11 === "number" || opts.x11 === true) { + todo.push(() => reqX11(chan, opts.x11, reqCb)); + } + } + todo.push(() => reqExec(chan, cmd, opts, cb)); + todo.shift()(); + }); + return this; + } + shell(wndopts, opts, cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error("Not connected"); + if (typeof wndopts === "function") { + cb = wndopts; + wndopts = opts = void 0; + } else if (typeof opts === "function") { + cb = opts; + opts = void 0; + } + if (wndopts && (wndopts.x11 !== void 0 || wndopts.env !== void 0)) { + opts = wndopts; + wndopts = void 0; + } + openChannel(this, "session", (err, chan) => { + if (err) { + cb(err); + return; + } + const todo = []; + function reqCb(err2) { + if (err2) { + chan.close(); + cb(err2); + return; + } + if (todo.length) + todo.shift()(); + } + if (this.config.allowAgentFwd === true || opts && opts.agentForward === true && this._agent !== void 0) { + todo.push(() => reqAgentFwd(chan, reqCb)); + } + if (wndopts !== false) + todo.push(() => reqPty(chan, wndopts, reqCb)); + if (typeof opts === "object" && opts !== null) { + if (typeof opts.env === "object" && opts.env !== null) + reqEnv(chan, opts.env); + if (typeof opts.x11 === "object" && opts.x11 !== null || opts.x11 === "number" || opts.x11 === true) { + todo.push(() => reqX11(chan, opts.x11, reqCb)); + } + } + todo.push(() => reqShell(chan, cb)); + todo.shift()(); + }); + return this; + } + subsys(name, cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error("Not connected"); + openChannel(this, "session", (err, chan) => { + if (err) { + cb(err); + return; + } + reqSubsystem(chan, name, (err2, stream2) => { + if (err2) { + cb(err2); + return; + } + cb(void 0, stream2); + }); + }); + return this; + } + forwardIn(bindAddr, bindPort, cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error("Not connected"); + const wantReply = typeof cb === "function"; + if (wantReply) { + this._callbacks.push((had_err, data) => { + if (had_err) { + cb(had_err !== true ? had_err : new Error(`Unable to bind to ${bindAddr}:${bindPort}`)); + return; + } + let realPort = bindPort; + if (bindPort === 0 && data && data.length >= 4) { + realPort = readUInt32BE(data, 0); + if (!(this._protocol._compatFlags & COMPAT.DYN_RPORT_BUG)) + bindPort = realPort; + } + this._forwarding[`${bindAddr}:${bindPort}`] = realPort; + cb(void 0, realPort); + }); + } + this._protocol.tcpipForward(bindAddr, bindPort, wantReply); + return this; + } + unforwardIn(bindAddr, bindPort, cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error("Not connected"); + const wantReply = typeof cb === "function"; + if (wantReply) { + this._callbacks.push((had_err) => { + if (had_err) { + cb(had_err !== true ? had_err : new Error(`Unable to unbind from ${bindAddr}:${bindPort}`)); + return; + } + delete this._forwarding[`${bindAddr}:${bindPort}`]; + cb(); + }); + } + this._protocol.cancelTcpipForward(bindAddr, bindPort, wantReply); + return this; + } + forwardOut(srcIP, srcPort, dstIP, dstPort, cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error("Not connected"); + const cfg = { + srcIP, + srcPort, + dstIP, + dstPort + }; + if (typeof cb !== "function") + cb = noop3; + openChannel(this, "direct-tcpip", cfg, cb); + return this; + } + openssh_noMoreSessions(cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error("Not connected"); + const wantReply = typeof cb === "function"; + if (!this.config.strictVendor || this.config.strictVendor && RE_OPENSSH.test(this._remoteVer)) { + if (wantReply) { + this._callbacks.push((had_err) => { + if (had_err) { + cb(had_err !== true ? had_err : new Error("Unable to disable future sessions")); + return; + } + cb(); + }); + } + this._protocol.openssh_noMoreSessions(wantReply); + return this; + } + if (!wantReply) + return this; + process.nextTick( + cb, + new Error( + "strictVendor enabled and server is not OpenSSH or compatible version" + ) + ); + return this; + } + openssh_forwardInStreamLocal(socketPath, cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error("Not connected"); + const wantReply = typeof cb === "function"; + if (!this.config.strictVendor || this.config.strictVendor && RE_OPENSSH.test(this._remoteVer)) { + if (wantReply) { + this._callbacks.push((had_err) => { + if (had_err) { + cb(had_err !== true ? had_err : new Error(`Unable to bind to ${socketPath}`)); + return; + } + this._forwardingUnix[socketPath] = true; + cb(); + }); + } + this._protocol.openssh_streamLocalForward(socketPath, wantReply); + return this; + } + if (!wantReply) + return this; + process.nextTick( + cb, + new Error( + "strictVendor enabled and server is not OpenSSH or compatible version" + ) + ); + return this; + } + openssh_unforwardInStreamLocal(socketPath, cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error("Not connected"); + const wantReply = typeof cb === "function"; + if (!this.config.strictVendor || this.config.strictVendor && RE_OPENSSH.test(this._remoteVer)) { + if (wantReply) { + this._callbacks.push((had_err) => { + if (had_err) { + cb(had_err !== true ? had_err : new Error(`Unable to unbind from ${socketPath}`)); + return; + } + delete this._forwardingUnix[socketPath]; + cb(); + }); + } + this._protocol.openssh_cancelStreamLocalForward(socketPath, wantReply); + return this; + } + if (!wantReply) + return this; + process.nextTick( + cb, + new Error( + "strictVendor enabled and server is not OpenSSH or compatible version" + ) + ); + return this; + } + openssh_forwardOutStreamLocal(socketPath, cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error("Not connected"); + if (typeof cb !== "function") + cb = noop3; + if (!this.config.strictVendor || this.config.strictVendor && RE_OPENSSH.test(this._remoteVer)) { + openChannel(this, "direct-streamlocal@openssh.com", { socketPath }, cb); + return this; + } + process.nextTick( + cb, + new Error( + "strictVendor enabled and server is not OpenSSH or compatible version" + ) + ); + return this; + } + sftp(env, cb) { + if (!this._sock || !isWritable(this._sock)) + throw new Error("Not connected"); + if (typeof env === "function") { + cb = env; + env = void 0; + } + openChannel(this, "sftp", (err, sftp) => { + if (err) { + cb(err); + return; + } + const reqSubsystemCb = (err2, sftp_) => { + if (err2) { + cb(err2); + return; + } + function removeListeners() { + sftp.removeListener("ready", onReady); + sftp.removeListener("error", onError); + sftp.removeListener("exit", onExit); + sftp.removeListener("close", onExit); + } + function onReady() { + removeListeners(); + cb(void 0, sftp); + } + function onError(err3) { + removeListeners(); + cb(err3); + } + function onExit(code, signal) { + removeListeners(); + let msg; + if (typeof code === "number") + msg = `Received exit code ${code} while establishing SFTP session`; + else if (signal !== void 0) + msg = `Received signal ${signal} while establishing SFTP session`; + else + msg = "Received unexpected SFTP session termination"; + const err3 = new Error(msg); + err3.code = code; + err3.signal = signal; + cb(err3); + } + sftp.on("ready", onReady).on("error", onError).on("exit", onExit).on("close", onExit); + sftp._init(); + }; + if (typeof env === "object" && env !== null) { + reqEnv(sftp, env, (err2) => { + if (err2) { + cb(err2); + return; + } + reqSubsystem(sftp, "sftp", reqSubsystemCb); + }); + } else { + reqSubsystem(sftp, "sftp", reqSubsystemCb); + } + }); + return this; + } + setNoDelay(noDelay) { + if (this._sock && typeof this._sock.setNoDelay === "function") + this._sock.setNoDelay(noDelay); + return this; + } + }; + function openChannel(self2, type, opts, cb) { + const initWindow = MAX_WINDOW; + const maxPacket = PACKET_SIZE; + if (typeof opts === "function") { + cb = opts; + opts = {}; + } + const wrapper = (err, stream2) => { + cb(err, stream2); + }; + wrapper.type = type; + const localChan = self2._chanMgr.add(wrapper); + if (localChan === -1) { + cb(new Error("No free channels available")); + return; + } + switch (type) { + case "session": + case "sftp": + self2._protocol.session(localChan, initWindow, maxPacket); + break; + case "direct-tcpip": + self2._protocol.directTcpip(localChan, initWindow, maxPacket, opts); + break; + case "direct-streamlocal@openssh.com": + self2._protocol.openssh_directStreamLocal( + localChan, + initWindow, + maxPacket, + opts + ); + break; + default: + throw new Error(`Unsupported channel type: ${type}`); + } + } + function reqX11(chan, screen, cb) { + const cfg = { + single: false, + protocol: "MIT-MAGIC-COOKIE-1", + cookie: void 0, + screen: 0 + }; + if (typeof screen === "function") { + cb = screen; + } else if (typeof screen === "object" && screen !== null) { + if (typeof screen.single === "boolean") + cfg.single = screen.single; + if (typeof screen.screen === "number") + cfg.screen = screen.screen; + if (typeof screen.protocol === "string") + cfg.protocol = screen.protocol; + if (typeof screen.cookie === "string") + cfg.cookie = screen.cookie; + else if (Buffer.isBuffer(screen.cookie)) + cfg.cookie = screen.cookie.hexSlice(0, screen.cookie.length); + } + if (cfg.cookie === void 0) + cfg.cookie = randomCookie(); + const wantReply = typeof cb === "function"; + if (chan.outgoing.state !== "open") { + if (wantReply) + cb(new Error("Channel is not open")); + return; + } + if (wantReply) { + chan._callbacks.push((had_err) => { + if (had_err) { + cb(had_err !== true ? had_err : new Error("Unable to request X11")); + return; + } + chan._hasX11 = true; + ++chan._client._acceptX11; + chan.once("close", () => { + if (chan._client._acceptX11) + --chan._client._acceptX11; + }); + cb(); + }); + } + chan._client._protocol.x11Forward(chan.outgoing.id, cfg, wantReply); + } + function reqPty(chan, opts, cb) { + let rows = 24; + let cols = 80; + let width = 640; + let height = 480; + let term = "vt100"; + let modes = null; + if (typeof opts === "function") { + cb = opts; + } else if (typeof opts === "object" && opts !== null) { + if (typeof opts.rows === "number") + rows = opts.rows; + if (typeof opts.cols === "number") + cols = opts.cols; + if (typeof opts.width === "number") + width = opts.width; + if (typeof opts.height === "number") + height = opts.height; + if (typeof opts.term === "string") + term = opts.term; + if (typeof opts.modes === "object") + modes = opts.modes; + } + const wantReply = typeof cb === "function"; + if (chan.outgoing.state !== "open") { + if (wantReply) + cb(new Error("Channel is not open")); + return; + } + if (wantReply) { + chan._callbacks.push((had_err) => { + if (had_err) { + cb(had_err !== true ? had_err : new Error("Unable to request a pseudo-terminal")); + return; + } + cb(); + }); + } + chan._client._protocol.pty( + chan.outgoing.id, + rows, + cols, + height, + width, + term, + modes, + wantReply + ); + } + function reqAgentFwd(chan, cb) { + const wantReply = typeof cb === "function"; + if (chan.outgoing.state !== "open") { + wantReply && cb(new Error("Channel is not open")); + return; + } + if (chan._client._agentFwdEnabled) { + wantReply && cb(false); + return; + } + chan._client._agentFwdEnabled = true; + chan._callbacks.push((had_err) => { + if (had_err) { + chan._client._agentFwdEnabled = false; + if (wantReply) { + cb(had_err !== true ? had_err : new Error("Unable to request agent forwarding")); + } + return; + } + if (wantReply) + cb(); + }); + chan._client._protocol.openssh_agentForward(chan.outgoing.id, true); + } + function reqShell(chan, cb) { + if (chan.outgoing.state !== "open") { + cb(new Error("Channel is not open")); + return; + } + chan._callbacks.push((had_err) => { + if (had_err) { + cb(had_err !== true ? had_err : new Error("Unable to open shell")); + return; + } + chan.subtype = "shell"; + cb(void 0, chan); + }); + chan._client._protocol.shell(chan.outgoing.id, true); + } + function reqExec(chan, cmd, opts, cb) { + if (chan.outgoing.state !== "open") { + cb(new Error("Channel is not open")); + return; + } + chan._callbacks.push((had_err) => { + if (had_err) { + cb(had_err !== true ? had_err : new Error("Unable to exec")); + return; + } + chan.subtype = "exec"; + chan.allowHalfOpen = opts.allowHalfOpen !== false; + cb(void 0, chan); + }); + chan._client._protocol.exec(chan.outgoing.id, cmd, true); + } + function reqEnv(chan, env, cb) { + const wantReply = typeof cb === "function"; + if (chan.outgoing.state !== "open") { + if (wantReply) + cb(new Error("Channel is not open")); + return; + } + if (wantReply) { + chan._callbacks.push((had_err) => { + if (had_err) { + cb(had_err !== true ? had_err : new Error("Unable to set environment")); + return; + } + cb(); + }); + } + const keys = Object.keys(env || {}); + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + const val = env[key]; + chan._client._protocol.env(chan.outgoing.id, key, val, wantReply); + } + } + function reqSubsystem(chan, name, cb) { + if (chan.outgoing.state !== "open") { + cb(new Error("Channel is not open")); + return; + } + chan._callbacks.push((had_err) => { + if (had_err) { + cb(had_err !== true ? had_err : new Error(`Unable to start subsystem: ${name}`)); + return; + } + chan.subtype = "subsystem"; + cb(void 0, chan); + }); + chan._client._protocol.subsystem(chan.outgoing.id, name, true); + } + function onCHANNEL_OPEN(self2, info2) { + let localChan = -1; + let reason; + const accept = () => { + const chanInfo = { + type: info2.type, + incoming: { + id: localChan, + window: MAX_WINDOW, + packetSize: PACKET_SIZE, + state: "open" + }, + outgoing: { + id: info2.sender, + window: info2.window, + packetSize: info2.packetSize, + state: "open" + } + }; + const stream2 = new Channel(self2, chanInfo); + self2._chanMgr.update(localChan, stream2); + self2._protocol.channelOpenConfirm( + info2.sender, + localChan, + MAX_WINDOW, + PACKET_SIZE + ); + return stream2; + }; + const reject = () => { + if (reason === void 0) { + if (localChan === -1) + reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; + else + reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED; + } + if (localChan !== -1) + self2._chanMgr.remove(localChan); + self2._protocol.channelOpenFail(info2.sender, reason, ""); + }; + const reserveChannel = () => { + localChan = self2._chanMgr.add(); + if (localChan === -1) { + reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; + if (self2.config.debug) { + self2.config.debug( + "Client: Automatic rejection of incoming channel open: no channels available" + ); + } + } + return localChan !== -1; + }; + const data = info2.data; + switch (info2.type) { + case "forwarded-tcpip": { + const val = self2._forwarding[`${data.destIP}:${data.destPort}`]; + if (val !== void 0 && reserveChannel()) { + if (data.destPort === 0) + data.destPort = val; + self2.emit("tcp connection", data, accept, reject); + return; + } + break; + } + case "forwarded-streamlocal@openssh.com": + if (self2._forwardingUnix[data.socketPath] !== void 0 && reserveChannel()) { + self2.emit("unix connection", data, accept, reject); + return; + } + break; + case "auth-agent@openssh.com": + if (self2._agentFwdEnabled && typeof self2._agent.getStream === "function" && reserveChannel()) { + self2._agent.getStream((err, stream2) => { + if (err) + return reject(); + const upstream = accept(); + upstream.pipe(stream2).pipe(upstream); + }); + return; + } + break; + case "x11": + if (self2._acceptX11 !== 0 && reserveChannel()) { + self2.emit("x11", data, accept, reject); + return; + } + break; + default: + reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE; + if (self2.config.debug) { + self2.config.debug( + `Client: Automatic rejection of unsupported incoming channel open type: ${info2.type}` + ); + } + } + if (reason === void 0) { + reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; + if (self2.config.debug) { + self2.config.debug( + "Client: Automatic rejection of unexpected incoming channel open for: " + info2.type + ); + } + } + reject(); + } + var randomCookie = (() => { + const buffer = Buffer.allocUnsafe(16); + return () => { + randomFillSync(buffer, 0, 16); + return buffer.hexSlice(0, 16); + }; + })(); + function makeSimpleAuthHandler(authList) { + if (!Array.isArray(authList)) + throw new Error("authList must be an array"); + let a = 0; + return (authsLeft, partialSuccess, cb) => { + if (a === authList.length) + return false; + return authList[a++]; + }; + } + function hostKeysProve(client, keys_, cb) { + if (!client._sock || !isWritable(client._sock)) + return; + if (typeof cb !== "function") + cb = noop3; + if (!Array.isArray(keys_)) + throw new TypeError("Invalid keys argument type"); + const keys = []; + for (const key of keys_) { + const parsed = parseKey(key); + if (parsed instanceof Error) + throw parsed; + keys.push(parsed); + } + if (!client.config.strictVendor || client.config.strictVendor && RE_OPENSSH.test(client._remoteVer)) { + client._callbacks.push((had_err, data) => { + if (had_err) { + cb(had_err !== true ? had_err : new Error("Server failed to prove supplied keys")); + return; + } + const ret = []; + let keyIdx = 0; + bufferParser.init(data, 0); + while (bufferParser.avail()) { + if (keyIdx === keys.length) + break; + const key = keys[keyIdx++]; + const keyPublic = key.getPublicSSH(); + const sigEntry = bufferParser.readString(); + sigParser.init(sigEntry, 0); + const type = sigParser.readString(true); + let value = sigParser.readString(); + let algo; + if (type !== key.type) { + if (key.type === "ssh-rsa") { + switch (type) { + case "rsa-sha2-256": + algo = "sha256"; + break; + case "rsa-sha2-512": + algo = "sha512"; + break; + default: + continue; + } + } else { + continue; + } + } + const sessionID = client._protocol._kex.sessionID; + const verifyData = Buffer.allocUnsafe( + 4 + 29 + 4 + sessionID.length + 4 + keyPublic.length + ); + let p = 0; + writeUInt32BE(verifyData, 29, p); + verifyData.utf8Write("hostkeys-prove-00@openssh.com", p += 4, 29); + writeUInt32BE(verifyData, sessionID.length, p += 29); + bufferCopy(sessionID, verifyData, 0, sessionID.length, p += 4); + writeUInt32BE(verifyData, keyPublic.length, p += sessionID.length); + bufferCopy(keyPublic, verifyData, 0, keyPublic.length, p += 4); + if (!(value = sigSSHToASN1(value, type))) + continue; + if (key.verify(verifyData, value, algo) === true) + ret.push(key); + } + sigParser.clear(); + bufferParser.clear(); + cb(null, ret); + }); + client._protocol.openssh_hostKeysProve(keys); + return; + } + process.nextTick( + cb, + new Error( + "strictVendor enabled and server is not OpenSSH or compatible version" + ) + ); + } + function getKeyAlgos(client, key, serverSigAlgs) { + switch (key.type) { + case "ssh-rsa": + if (client._protocol._compatFlags & COMPAT.IMPLY_RSA_SHA2_SIGALGS) { + if (!Array.isArray(serverSigAlgs)) + serverSigAlgs = ["rsa-sha2-256", "rsa-sha2-512"]; + else + serverSigAlgs = ["rsa-sha2-256", "rsa-sha2-512", ...serverSigAlgs]; + } + if (Array.isArray(serverSigAlgs)) { + if (serverSigAlgs.indexOf("rsa-sha2-256") !== -1) + return [["rsa-sha2-256", "sha256"]]; + if (serverSigAlgs.indexOf("rsa-sha2-512") !== -1) + return [["rsa-sha2-512", "sha512"]]; + if (serverSigAlgs.indexOf("ssh-rsa") === -1) + return []; + } + return [["ssh-rsa", "sha1"]]; + } + } + module2.exports = Client; + } +}); + +// node_modules/ssh2/lib/http-agents.js +var require_http_agents = __commonJS({ + "node_modules/ssh2/lib/http-agents.js"(exports2) { + "use strict"; + var { Agent: HttpAgent } = require("http"); + var { Agent: HttpsAgent } = require("https"); + var { connect: tlsConnect } = require("tls"); + var Client; + for (const ctor of [HttpAgent, HttpsAgent]) { + class SSHAgent extends ctor { + constructor(connectCfg, agentOptions) { + super(agentOptions); + this._connectCfg = connectCfg; + this._defaultSrcIP = agentOptions && agentOptions.srcIP || "localhost"; + } + createConnection(options, cb) { + const srcIP = options && options.localAddress || this._defaultSrcIP; + const srcPort = options && options.localPort || 0; + const dstIP = options.host; + const dstPort = options.port; + if (Client === void 0) + Client = require_client2(); + const client = new Client(); + let triedForward = false; + client.on("ready", () => { + client.forwardOut(srcIP, srcPort, dstIP, dstPort, (err, stream2) => { + triedForward = true; + if (err) { + client.end(); + return cb(err); + } + stream2.once("close", () => client.end()); + cb(null, decorateStream(stream2, ctor, options)); + }); + }).on("error", cb).on("close", () => { + if (!triedForward) + cb(new Error("Unexpected connection close")); + }).connect(this._connectCfg); + } + } + exports2[ctor === HttpAgent ? "SSHTTPAgent" : "SSHTTPSAgent"] = SSHAgent; + } + function noop3() { + } + function decorateStream(stream2, ctor, options) { + if (ctor === HttpAgent) { + stream2.setKeepAlive = noop3; + stream2.setNoDelay = noop3; + stream2.setTimeout = noop3; + stream2.ref = noop3; + stream2.unref = noop3; + stream2.destroySoon = stream2.destroy; + return stream2; + } + options.socket = stream2; + const wrapped = tlsConnect(options); + const onClose = /* @__PURE__ */ (() => { + let called = false; + return () => { + if (called) + return; + called = true; + if (stream2.isPaused()) + stream2.resume(); + }; + })(); + wrapped.on("end", onClose).on("close", onClose); + return wrapped; + } + } +}); + +// node_modules/ssh2/lib/server.js +var require_server = __commonJS({ + "node_modules/ssh2/lib/server.js"(exports2, module2) { + "use strict"; + var { Server: netServer } = require("net"); + var EventEmitter = require("events"); + var { listenerCount } = EventEmitter; + var { + CHANNEL_OPEN_FAILURE, + DEFAULT_CIPHER, + DEFAULT_COMPRESSION, + DEFAULT_KEX, + DEFAULT_MAC, + DEFAULT_SERVER_HOST_KEY, + DISCONNECT_REASON, + DISCONNECT_REASON_BY_VALUE, + SUPPORTED_CIPHER, + SUPPORTED_COMPRESSION, + SUPPORTED_KEX, + SUPPORTED_MAC, + SUPPORTED_SERVER_HOST_KEY + } = require_constants6(); + var { init: cryptoInit } = require_crypto(); + var { KexInit } = require_kex(); + var { parseKey } = require_keyParser(); + var Protocol = require_Protocol(); + var { SFTP } = require_SFTP(); + var { writeUInt32BE } = require_utils3(); + var { + Channel, + MAX_WINDOW, + PACKET_SIZE, + windowAdjust, + WINDOW_THRESHOLD + } = require_Channel(); + var { + ChannelManager, + generateAlgorithmList, + isWritable, + onChannelOpenFailure, + onCHANNEL_CLOSE + } = require_utils4(); + var MAX_PENDING_AUTHS = 10; + var AuthContext = class extends EventEmitter { + constructor(protocol, username, service, method, cb) { + super(); + this.username = this.user = username; + this.service = service; + this.method = method; + this._initialResponse = false; + this._finalResponse = false; + this._multistep = false; + this._cbfinal = (allowed, methodsLeft, isPartial) => { + if (!this._finalResponse) { + this._finalResponse = true; + cb(this, allowed, methodsLeft, isPartial); + } + }; + this._protocol = protocol; + } + accept() { + this._cleanup && this._cleanup(); + this._initialResponse = true; + this._cbfinal(true); + } + reject(methodsLeft, isPartial) { + this._cleanup && this._cleanup(); + this._initialResponse = true; + this._cbfinal(false, methodsLeft, isPartial); + } + }; + var KeyboardAuthContext = class extends AuthContext { + constructor(protocol, username, service, method, submethods, cb) { + super(protocol, username, service, method, cb); + this._multistep = true; + this._cb = void 0; + this._onInfoResponse = (responses) => { + const callback = this._cb; + if (callback) { + this._cb = void 0; + callback(responses); + } + }; + this.submethods = submethods; + this.on("abort", () => { + this._cb && this._cb(new Error("Authentication request aborted")); + }); + } + prompt(prompts, title, instructions, cb) { + if (!Array.isArray(prompts)) + prompts = [prompts]; + if (typeof title === "function") { + cb = title; + title = instructions = void 0; + } else if (typeof instructions === "function") { + cb = instructions; + instructions = void 0; + } else if (typeof cb !== "function") { + cb = void 0; + } + for (let i = 0; i < prompts.length; ++i) { + if (typeof prompts[i] === "string") { + prompts[i] = { + prompt: prompts[i], + echo: true + }; + } + } + this._cb = cb; + this._initialResponse = true; + this._protocol.authInfoReq(title, instructions, prompts); + } + }; + var PKAuthContext = class extends AuthContext { + constructor(protocol, username, service, method, pkInfo, cb) { + super(protocol, username, service, method, cb); + this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key }; + this.hashAlgo = pkInfo.hashAlgo; + this.signature = pkInfo.signature; + this.blob = pkInfo.blob; + } + accept() { + if (!this.signature) { + this._initialResponse = true; + this._protocol.authPKOK(this.key.algo, this.key.data); + } else { + AuthContext.prototype.accept.call(this); + } + } + }; + var HostbasedAuthContext = class extends AuthContext { + constructor(protocol, username, service, method, pkInfo, cb) { + super(protocol, username, service, method, cb); + this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key }; + this.hashAlgo = pkInfo.hashAlgo; + this.signature = pkInfo.signature; + this.blob = pkInfo.blob; + this.localHostname = pkInfo.localHostname; + this.localUsername = pkInfo.localUsername; + } + }; + var PwdAuthContext = class extends AuthContext { + constructor(protocol, username, service, method, password, cb) { + super(protocol, username, service, method, cb); + this.password = password; + this._changeCb = void 0; + } + requestChange(prompt, cb) { + if (this._changeCb) + throw new Error("Change request already in progress"); + if (typeof prompt !== "string") + throw new Error("prompt argument must be a string"); + if (typeof cb !== "function") + throw new Error("Callback argument must be a function"); + this._changeCb = cb; + this._protocol.authPasswdChg(prompt); + } + }; + var Session = class extends EventEmitter { + constructor(client, info2, localChan) { + super(); + this.type = "session"; + this.subtype = void 0; + this.server = true; + this._ending = false; + this._channel = void 0; + this._chanInfo = { + type: "session", + incoming: { + id: localChan, + window: MAX_WINDOW, + packetSize: PACKET_SIZE, + state: "open" + }, + outgoing: { + id: info2.sender, + window: info2.window, + packetSize: info2.packetSize, + state: "open" + } + }; + } + }; + var Server = class extends EventEmitter { + constructor(cfg, listener) { + super(); + if (typeof cfg !== "object" || cfg === null) + throw new Error("Missing configuration object"); + const hostKeys = /* @__PURE__ */ Object.create(null); + const hostKeyAlgoOrder = []; + const hostKeys_ = cfg.hostKeys; + if (!Array.isArray(hostKeys_)) + throw new Error("hostKeys must be an array"); + const cfgAlgos = typeof cfg.algorithms === "object" && cfg.algorithms !== null ? cfg.algorithms : {}; + const hostKeyAlgos = generateAlgorithmList( + cfgAlgos.serverHostKey, + DEFAULT_SERVER_HOST_KEY, + SUPPORTED_SERVER_HOST_KEY + ); + for (let i = 0; i < hostKeys_.length; ++i) { + let privateKey; + if (Buffer.isBuffer(hostKeys_[i]) || typeof hostKeys_[i] === "string") + privateKey = parseKey(hostKeys_[i]); + else + privateKey = parseKey(hostKeys_[i].key, hostKeys_[i].passphrase); + if (privateKey instanceof Error) + throw new Error(`Cannot parse privateKey: ${privateKey.message}`); + if (Array.isArray(privateKey)) { + privateKey = privateKey[0]; + } + if (privateKey.getPrivatePEM() === null) + throw new Error("privateKey value contains an invalid private key"); + if (hostKeyAlgoOrder.includes(privateKey.type)) + continue; + if (privateKey.type === "ssh-rsa") { + let sha1Pos = hostKeyAlgos.indexOf("ssh-rsa"); + const sha256Pos = hostKeyAlgos.indexOf("rsa-sha2-256"); + const sha512Pos = hostKeyAlgos.indexOf("rsa-sha2-512"); + if (sha1Pos === -1) { + sha1Pos = Infinity; + } + [sha1Pos, sha256Pos, sha512Pos].sort(compareNumbers).forEach((pos) => { + if (pos === -1) + return; + let type; + switch (pos) { + case sha1Pos: + type = "ssh-rsa"; + break; + case sha256Pos: + type = "rsa-sha2-256"; + break; + case sha512Pos: + type = "rsa-sha2-512"; + break; + default: + return; + } + hostKeys[type] = privateKey; + hostKeyAlgoOrder.push(type); + }); + } else { + hostKeys[privateKey.type] = privateKey; + hostKeyAlgoOrder.push(privateKey.type); + } + } + const algorithms = { + kex: generateAlgorithmList( + cfgAlgos.kex, + DEFAULT_KEX, + SUPPORTED_KEX + ).concat(["kex-strict-s-v00@openssh.com"]), + serverHostKey: hostKeyAlgoOrder, + cs: { + cipher: generateAlgorithmList( + cfgAlgos.cipher, + DEFAULT_CIPHER, + SUPPORTED_CIPHER + ), + mac: generateAlgorithmList(cfgAlgos.hmac, DEFAULT_MAC, SUPPORTED_MAC), + compress: generateAlgorithmList( + cfgAlgos.compress, + DEFAULT_COMPRESSION, + SUPPORTED_COMPRESSION + ), + lang: [] + }, + sc: void 0 + }; + algorithms.sc = algorithms.cs; + if (typeof listener === "function") + this.on("connection", listener); + const origDebug = typeof cfg.debug === "function" ? cfg.debug : void 0; + const ident = cfg.ident ? Buffer.from(cfg.ident) : void 0; + const offer = new KexInit(algorithms); + this._srv = new netServer((socket) => { + if (this._connections >= this.maxConnections) { + socket.destroy(); + return; + } + ++this._connections; + socket.once("close", () => { + --this._connections; + }); + let debug2; + if (origDebug) { + const debugPrefix = `[${process.hrtime().join(".")}] `; + debug2 = (msg) => { + origDebug(`${debugPrefix}${msg}`); + }; + } + new Client(socket, hostKeys, ident, offer, debug2, this, cfg); + }).on("error", (err) => { + this.emit("error", err); + }).on("listening", () => { + this.emit("listening"); + }).on("close", () => { + this.emit("close"); + }); + this._connections = 0; + this.maxConnections = Infinity; + } + injectSocket(socket) { + this._srv.emit("connection", socket); + } + listen(...args) { + this._srv.listen(...args); + return this; + } + address() { + return this._srv.address(); + } + getConnections(cb) { + this._srv.getConnections(cb); + return this; + } + close(cb) { + this._srv.close(cb); + return this; + } + ref() { + this._srv.ref(); + return this; + } + unref() { + this._srv.unref(); + return this; + } + }; + Server.KEEPALIVE_CLIENT_INTERVAL = 15e3; + Server.KEEPALIVE_CLIENT_COUNT_MAX = 3; + var Client = class extends EventEmitter { + constructor(socket, hostKeys, ident, offer, debug2, server, srvCfg) { + super(); + let exchanges = 0; + let acceptedAuthSvc = false; + let pendingAuths = []; + let authCtx; + let kaTimer; + let onPacket; + const unsentGlobalRequestsReplies = []; + this._sock = socket; + this._chanMgr = new ChannelManager(this); + this._debug = debug2; + this.noMoreSessions = false; + this.authenticated = false; + function onClientPreHeaderError(err) { + } + this.on("error", onClientPreHeaderError); + const DEBUG_HANDLER = !debug2 ? void 0 : (p, display, msg) => { + debug2(`Debug output from client: ${JSON.stringify(msg)}`); + }; + const kaIntvl = typeof srvCfg.keepaliveInterval === "number" && isFinite(srvCfg.keepaliveInterval) && srvCfg.keepaliveInterval > 0 ? srvCfg.keepaliveInterval : typeof Server.KEEPALIVE_CLIENT_INTERVAL === "number" && isFinite(Server.KEEPALIVE_CLIENT_INTERVAL) && Server.KEEPALIVE_CLIENT_INTERVAL > 0 ? Server.KEEPALIVE_CLIENT_INTERVAL : -1; + const kaCountMax = typeof srvCfg.keepaliveCountMax === "number" && isFinite(srvCfg.keepaliveCountMax) && srvCfg.keepaliveCountMax >= 0 ? srvCfg.keepaliveCountMax : typeof Server.KEEPALIVE_CLIENT_COUNT_MAX === "number" && isFinite(Server.KEEPALIVE_CLIENT_COUNT_MAX) && Server.KEEPALIVE_CLIENT_COUNT_MAX >= 0 ? Server.KEEPALIVE_CLIENT_COUNT_MAX : -1; + let kaCurCount = 0; + if (kaIntvl !== -1 && kaCountMax !== -1) { + this.once("ready", () => { + const onClose = () => { + clearInterval(kaTimer); + }; + this.on("close", onClose).on("end", onClose); + kaTimer = setInterval(() => { + if (++kaCurCount > kaCountMax) { + clearInterval(kaTimer); + const err = new Error("Keepalive timeout"); + err.level = "client-timeout"; + this.emit("error", err); + this.end(); + } else { + proto.ping(); + } + }, kaIntvl); + }); + onPacket = () => { + kaTimer && kaTimer.refresh(); + kaCurCount = 0; + }; + } + const proto = this._protocol = new Protocol({ + server: true, + hostKeys, + ident, + offer, + onPacket, + greeting: srvCfg.greeting, + banner: srvCfg.banner, + onWrite: (data) => { + if (isWritable(socket)) + socket.write(data); + }, + onError: (err) => { + if (!proto._destruct) + socket.removeAllListeners("data"); + this.emit("error", err); + try { + socket.end(); + } catch { + } + }, + onHeader: (header) => { + this.removeListener("error", onClientPreHeaderError); + const info2 = { + ip: socket.remoteAddress, + family: socket.remoteFamily, + port: socket.remotePort, + header + }; + if (!server.emit("connection", this, info2)) { + proto.disconnect(DISCONNECT_REASON.BY_APPLICATION); + socket.end(); + return; + } + if (header.greeting) + this.emit("greeting", header.greeting); + }, + onHandshakeComplete: (negotiated) => { + if (++exchanges > 1) + this.emit("rekey"); + this.emit("handshake", negotiated); + }, + debug: debug2, + messageHandlers: { + DEBUG: DEBUG_HANDLER, + DISCONNECT: (p, reason, desc) => { + if (reason !== DISCONNECT_REASON.BY_APPLICATION) { + if (!desc) { + desc = DISCONNECT_REASON_BY_VALUE[reason]; + if (desc === void 0) + desc = `Unexpected disconnection reason: ${reason}`; + } + const err = new Error(desc); + err.code = reason; + this.emit("error", err); + } + socket.end(); + }, + CHANNEL_OPEN: (p, info2) => { + if (info2.type === "session" && this.noMoreSessions || !this.authenticated) { + const reasonCode = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; + return proto.channelOpenFail(info2.sender, reasonCode); + } + let localChan = -1; + let reason; + let replied = false; + let accept; + const reject = () => { + if (replied) + return; + replied = true; + if (reason === void 0) { + if (localChan === -1) + reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; + else + reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED; + } + if (localChan !== -1) + this._chanMgr.remove(localChan); + proto.channelOpenFail(info2.sender, reason, ""); + }; + const reserveChannel = () => { + localChan = this._chanMgr.add(); + if (localChan === -1) { + reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; + if (debug2) { + debug2("Automatic rejection of incoming channel open: no channels available"); + } + } + return localChan !== -1; + }; + const data = info2.data; + switch (info2.type) { + case "session": + if (listenerCount(this, "session") && reserveChannel()) { + accept = () => { + if (replied) + return; + replied = true; + const instance = new Session(this, info2, localChan); + this._chanMgr.update(localChan, instance); + proto.channelOpenConfirm( + info2.sender, + localChan, + MAX_WINDOW, + PACKET_SIZE + ); + return instance; + }; + this.emit("session", accept, reject); + return; + } + break; + case "direct-tcpip": + if (listenerCount(this, "tcpip") && reserveChannel()) { + accept = () => { + if (replied) + return; + replied = true; + const chanInfo = { + type: void 0, + incoming: { + id: localChan, + window: MAX_WINDOW, + packetSize: PACKET_SIZE, + state: "open" + }, + outgoing: { + id: info2.sender, + window: info2.window, + packetSize: info2.packetSize, + state: "open" + } + }; + const stream2 = new Channel(this, chanInfo, { server: true }); + this._chanMgr.update(localChan, stream2); + proto.channelOpenConfirm( + info2.sender, + localChan, + MAX_WINDOW, + PACKET_SIZE + ); + return stream2; + }; + this.emit("tcpip", accept, reject, data); + return; + } + break; + case "direct-streamlocal@openssh.com": + if (listenerCount(this, "openssh.streamlocal") && reserveChannel()) { + accept = () => { + if (replied) + return; + replied = true; + const chanInfo = { + type: void 0, + incoming: { + id: localChan, + window: MAX_WINDOW, + packetSize: PACKET_SIZE, + state: "open" + }, + outgoing: { + id: info2.sender, + window: info2.window, + packetSize: info2.packetSize, + state: "open" + } + }; + const stream2 = new Channel(this, chanInfo, { server: true }); + this._chanMgr.update(localChan, stream2); + proto.channelOpenConfirm( + info2.sender, + localChan, + MAX_WINDOW, + PACKET_SIZE + ); + return stream2; + }; + this.emit("openssh.streamlocal", accept, reject, data); + return; + } + break; + default: + reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE; + if (debug2) { + debug2(`Automatic rejection of unsupported incoming channel open type: ${info2.type}`); + } + } + if (reason === void 0) { + reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; + if (debug2) { + debug2(`Automatic rejection of unexpected incoming channel open for: ${info2.type}`); + } + } + reject(); + }, + CHANNEL_OPEN_CONFIRMATION: (p, info2) => { + const channel = this._chanMgr.get(info2.recipient); + if (typeof channel !== "function") + return; + const chanInfo = { + type: channel.type, + incoming: { + id: info2.recipient, + window: MAX_WINDOW, + packetSize: PACKET_SIZE, + state: "open" + }, + outgoing: { + id: info2.sender, + window: info2.window, + packetSize: info2.packetSize, + state: "open" + } + }; + const instance = new Channel(this, chanInfo, { server: true }); + this._chanMgr.update(info2.recipient, instance); + channel(void 0, instance); + }, + CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => { + const channel = this._chanMgr.get(recipient); + if (typeof channel !== "function") + return; + const info2 = { reason, description }; + onChannelOpenFailure(this, recipient, info2, channel); + }, + CHANNEL_DATA: (p, recipient, data) => { + let channel = this._chanMgr.get(recipient); + if (typeof channel !== "object" || channel === null) + return; + if (channel.constructor === Session) { + channel = channel._channel; + if (!channel) + return; + } + if (channel.incoming.window === 0) + return; + channel.incoming.window -= data.length; + if (channel.push(data) === false) { + channel._waitChanDrain = true; + return; + } + if (channel.incoming.window <= WINDOW_THRESHOLD) + windowAdjust(channel); + }, + CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => { + }, + CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => { + let channel = this._chanMgr.get(recipient); + if (typeof channel !== "object" || channel === null) + return; + if (channel.constructor === Session) { + channel = channel._channel; + if (!channel) + return; + } + channel.outgoing.window += amount; + if (channel._waitWindow) { + channel._waitWindow = false; + if (channel._chunk) { + channel._write(channel._chunk, null, channel._chunkcb); + } else if (channel._chunkcb) { + channel._chunkcb(); + } else if (channel._chunkErr) { + channel.stderr._write( + channel._chunkErr, + null, + channel._chunkcbErr + ); + } else if (channel._chunkcbErr) { + channel._chunkcbErr(); + } + } + }, + CHANNEL_SUCCESS: (p, recipient) => { + let channel = this._chanMgr.get(recipient); + if (typeof channel !== "object" || channel === null) + return; + if (channel.constructor === Session) { + channel = channel._channel; + if (!channel) + return; + } + if (channel._callbacks.length) + channel._callbacks.shift()(false); + }, + CHANNEL_FAILURE: (p, recipient) => { + let channel = this._chanMgr.get(recipient); + if (typeof channel !== "object" || channel === null) + return; + if (channel.constructor === Session) { + channel = channel._channel; + if (!channel) + return; + } + if (channel._callbacks.length) + channel._callbacks.shift()(true); + }, + CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => { + const session = this._chanMgr.get(recipient); + if (typeof session !== "object" || session === null) + return; + let replied = false; + let accept; + let reject; + if (session.constructor !== Session) { + if (wantReply) + proto.channelFailure(session.outgoing.id); + return; + } + if (wantReply) { + if (type !== "shell" && type !== "exec" && type !== "subsystem") { + accept = () => { + if (replied || session._ending || session._channel) + return; + replied = true; + proto.channelSuccess(session._chanInfo.outgoing.id); + }; + } + reject = () => { + if (replied || session._ending || session._channel) + return; + replied = true; + proto.channelFailure(session._chanInfo.outgoing.id); + }; + } + if (session._ending) { + reject && reject(); + return; + } + switch (type) { + // "pre-real session start" requests + case "env": + if (listenerCount(session, "env")) { + session.emit("env", accept, reject, { + key: data.name, + val: data.value + }); + return; + } + break; + case "pty-req": + if (listenerCount(session, "pty")) { + session.emit("pty", accept, reject, data); + return; + } + break; + case "window-change": + if (listenerCount(session, "window-change")) + session.emit("window-change", accept, reject, data); + else + reject && reject(); + break; + case "x11-req": + if (listenerCount(session, "x11")) { + session.emit("x11", accept, reject, data); + return; + } + break; + // "post-real session start" requests + case "signal": + if (listenerCount(session, "signal")) { + session.emit("signal", accept, reject, { + name: data + }); + return; + } + break; + // XXX: is `auth-agent-req@openssh.com` really "post-real session + // start"? + case "auth-agent-req@openssh.com": + if (listenerCount(session, "auth-agent")) { + session.emit("auth-agent", accept, reject); + return; + } + break; + // "real session start" requests + case "shell": + if (listenerCount(session, "shell")) { + accept = () => { + if (replied || session._ending || session._channel) + return; + replied = true; + if (wantReply) + proto.channelSuccess(session._chanInfo.outgoing.id); + const channel = new Channel( + this, + session._chanInfo, + { server: true } + ); + channel.subtype = session.subtype = type; + session._channel = channel; + return channel; + }; + session.emit("shell", accept, reject); + return; + } + break; + case "exec": + if (listenerCount(session, "exec")) { + accept = () => { + if (replied || session._ending || session._channel) + return; + replied = true; + if (wantReply) + proto.channelSuccess(session._chanInfo.outgoing.id); + const channel = new Channel( + this, + session._chanInfo, + { server: true } + ); + channel.subtype = session.subtype = type; + session._channel = channel; + return channel; + }; + session.emit("exec", accept, reject, { + command: data + }); + return; + } + break; + case "subsystem": { + let useSFTP = data === "sftp"; + accept = () => { + if (replied || session._ending || session._channel) + return; + replied = true; + if (wantReply) + proto.channelSuccess(session._chanInfo.outgoing.id); + let instance; + if (useSFTP) { + instance = new SFTP(this, session._chanInfo, { + server: true, + debug: debug2 + }); + } else { + instance = new Channel( + this, + session._chanInfo, + { server: true } + ); + instance.subtype = session.subtype = `${type}:${data}`; + } + session._channel = instance; + return instance; + }; + if (data === "sftp") { + if (listenerCount(session, "sftp")) { + session.emit("sftp", accept, reject); + return; + } + useSFTP = false; + } + if (listenerCount(session, "subsystem")) { + session.emit("subsystem", accept, reject, { + name: data + }); + return; + } + break; + } + } + debug2 && debug2( + `Automatic rejection of incoming channel request: ${type}` + ); + reject && reject(); + }, + CHANNEL_EOF: (p, recipient) => { + let channel = this._chanMgr.get(recipient); + if (typeof channel !== "object" || channel === null) + return; + if (channel.constructor === Session) { + if (!channel._ending) { + channel._ending = true; + channel.emit("eof"); + channel.emit("end"); + } + channel = channel._channel; + if (!channel) + return; + } + if (channel.incoming.state !== "open") + return; + channel.incoming.state = "eof"; + if (channel.readable) + channel.push(null); + }, + CHANNEL_CLOSE: (p, recipient) => { + let channel = this._chanMgr.get(recipient); + if (typeof channel !== "object" || channel === null) + return; + if (channel.constructor === Session) { + channel._ending = true; + channel.emit("close"); + channel = channel._channel; + if (!channel) + return; + } + onCHANNEL_CLOSE(this, recipient, channel); + }, + // Begin service/auth-related ========================================== + SERVICE_REQUEST: (p, service) => { + if (exchanges === 0 || acceptedAuthSvc || this.authenticated || service !== "ssh-userauth") { + proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE); + socket.end(); + return; + } + acceptedAuthSvc = true; + proto.serviceAccept(service); + }, + USERAUTH_REQUEST: (p, username, service, method, methodData) => { + if (exchanges === 0 || this.authenticated || authCtx && (authCtx.username !== username || authCtx.service !== service) || method !== "password" && method !== "publickey" && method !== "hostbased" && method !== "keyboard-interactive" && method !== "none" || pendingAuths.length === MAX_PENDING_AUTHS) { + proto.disconnect(DISCONNECT_REASON.PROTOCOL_ERROR); + socket.end(); + return; + } else if (service !== "ssh-connection") { + proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE); + socket.end(); + return; + } + let ctx; + switch (method) { + case "keyboard-interactive": + ctx = new KeyboardAuthContext( + proto, + username, + service, + method, + methodData, + onAuthDecide + ); + break; + case "publickey": + ctx = new PKAuthContext( + proto, + username, + service, + method, + methodData, + onAuthDecide + ); + break; + case "hostbased": + ctx = new HostbasedAuthContext( + proto, + username, + service, + method, + methodData, + onAuthDecide + ); + break; + case "password": + if (authCtx && authCtx instanceof PwdAuthContext && authCtx._changeCb) { + const cb = authCtx._changeCb; + authCtx._changeCb = void 0; + cb(methodData.newPassword); + return; + } + ctx = new PwdAuthContext( + proto, + username, + service, + method, + methodData, + onAuthDecide + ); + break; + case "none": + ctx = new AuthContext( + proto, + username, + service, + method, + onAuthDecide + ); + break; + } + if (authCtx) { + if (!authCtx._initialResponse) { + return pendingAuths.push(ctx); + } else if (authCtx._multistep && !authCtx._finalResponse) { + authCtx._cleanup && authCtx._cleanup(); + authCtx.emit("abort"); + } + } + authCtx = ctx; + if (listenerCount(this, "authentication")) + this.emit("authentication", authCtx); + else + authCtx.reject(); + }, + USERAUTH_INFO_RESPONSE: (p, responses) => { + if (authCtx && authCtx instanceof KeyboardAuthContext) + authCtx._onInfoResponse(responses); + }, + // End service/auth-related ============================================ + GLOBAL_REQUEST: (p, name, wantReply, data) => { + const reply = { + type: null, + buf: null + }; + function setReply(type, buf) { + reply.type = type; + reply.buf = buf; + sendReplies(); + } + if (wantReply) + unsentGlobalRequestsReplies.push(reply); + if ((name === "tcpip-forward" || name === "cancel-tcpip-forward" || name === "no-more-sessions@openssh.com" || name === "streamlocal-forward@openssh.com" || name === "cancel-streamlocal-forward@openssh.com") && listenerCount(this, "request") && this.authenticated) { + let accept; + let reject; + if (wantReply) { + let replied = false; + accept = (chosenPort) => { + if (replied) + return; + replied = true; + let bufPort; + if (name === "tcpip-forward" && data.bindPort === 0 && typeof chosenPort === "number") { + bufPort = Buffer.allocUnsafe(4); + writeUInt32BE(bufPort, chosenPort, 0); + } + setReply("SUCCESS", bufPort); + }; + reject = () => { + if (replied) + return; + replied = true; + setReply("FAILURE"); + }; + } + if (name === "no-more-sessions@openssh.com") { + this.noMoreSessions = true; + accept && accept(); + return; + } + this.emit("request", accept, reject, name, data); + } else if (wantReply) { + setReply("FAILURE"); + } + } + } + }); + socket.pause(); + cryptoInit.then(() => { + proto.start(); + socket.on("data", (data) => { + try { + proto.parse(data, 0, data.length); + } catch (ex) { + this.emit("error", ex); + try { + if (isWritable(socket)) + socket.end(); + } catch { + } + } + }); + socket.resume(); + }).catch((err) => { + this.emit("error", err); + try { + if (isWritable(socket)) + socket.end(); + } catch { + } + }); + socket.on("error", (err) => { + err.level = "socket"; + this.emit("error", err); + }).once("end", () => { + debug2 && debug2("Socket ended"); + proto.cleanup(); + this.emit("end"); + }).once("close", () => { + debug2 && debug2("Socket closed"); + proto.cleanup(); + this.emit("close"); + const err = new Error("No response from server"); + this._chanMgr.cleanup(err); + }); + const onAuthDecide = (ctx, allowed, methodsLeft, isPartial) => { + if (authCtx === ctx && !this.authenticated) { + if (allowed) { + authCtx = void 0; + this.authenticated = true; + proto.authSuccess(); + pendingAuths = []; + this.emit("ready"); + } else { + proto.authFailure(methodsLeft, isPartial); + if (pendingAuths.length) { + authCtx = pendingAuths.pop(); + if (listenerCount(this, "authentication")) + this.emit("authentication", authCtx); + else + authCtx.reject(); + } + } + } + }; + function sendReplies() { + while (unsentGlobalRequestsReplies.length > 0 && unsentGlobalRequestsReplies[0].type) { + const reply = unsentGlobalRequestsReplies.shift(); + if (reply.type === "SUCCESS") + proto.requestSuccess(reply.buf); + if (reply.type === "FAILURE") + proto.requestFailure(); + } + } + } + end() { + if (this._sock && isWritable(this._sock)) { + this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION); + this._sock.end(); + } + return this; + } + x11(originAddr, originPort, cb) { + const opts = { originAddr, originPort }; + openChannel(this, "x11", opts, cb); + return this; + } + forwardOut(boundAddr, boundPort, remoteAddr, remotePort, cb) { + const opts = { boundAddr, boundPort, remoteAddr, remotePort }; + openChannel(this, "forwarded-tcpip", opts, cb); + return this; + } + openssh_forwardOutStreamLocal(socketPath, cb) { + const opts = { socketPath }; + openChannel(this, "forwarded-streamlocal@openssh.com", opts, cb); + return this; + } + rekey(cb) { + let error2; + try { + this._protocol.rekey(); + } catch (ex) { + error2 = ex; + } + if (typeof cb === "function") { + if (error2) + process.nextTick(cb, error2); + else + this.once("rekey", cb); + } + } + setNoDelay(noDelay) { + if (this._sock && typeof this._sock.setNoDelay === "function") + this._sock.setNoDelay(noDelay); + return this; + } + }; + function openChannel(self2, type, opts, cb) { + const initWindow = MAX_WINDOW; + const maxPacket = PACKET_SIZE; + if (typeof opts === "function") { + cb = opts; + opts = {}; + } + const wrapper = (err, stream2) => { + cb(err, stream2); + }; + wrapper.type = type; + const localChan = self2._chanMgr.add(wrapper); + if (localChan === -1) { + cb(new Error("No free channels available")); + return; + } + switch (type) { + case "forwarded-tcpip": + self2._protocol.forwardedTcpip(localChan, initWindow, maxPacket, opts); + break; + case "x11": + self2._protocol.x11(localChan, initWindow, maxPacket, opts); + break; + case "forwarded-streamlocal@openssh.com": + self2._protocol.openssh_forwardedStreamLocal( + localChan, + initWindow, + maxPacket, + opts + ); + break; + default: + throw new Error(`Unsupported channel type: ${type}`); + } + } + function compareNumbers(a, b) { + return a - b; + } + module2.exports = Server; + module2.exports.IncomingClient = Client; + } +}); + +// node_modules/ssh2/lib/keygen.js +var require_keygen = __commonJS({ + "node_modules/ssh2/lib/keygen.js"(exports2, module2) { + "use strict"; + var { + createCipheriv, + generateKeyPair: generateKeyPair_, + generateKeyPairSync: generateKeyPairSync_, + getCurves, + randomBytes + } = require("crypto"); + var { Ber } = require_lib2(); + var bcrypt_pbkdf = require_bcrypt_pbkdf().pbkdf; + var { CIPHER_INFO } = require_crypto(); + var SALT_LEN = 16; + var DEFAULT_ROUNDS = 16; + var curves = getCurves(); + var ciphers = new Map(Object.entries(CIPHER_INFO)); + function makeArgs(type, opts) { + if (typeof type !== "string") + throw new TypeError("Key type must be a string"); + const publicKeyEncoding = { type: "spki", format: "der" }; + const privateKeyEncoding = { type: "pkcs8", format: "der" }; + switch (type.toLowerCase()) { + case "rsa": { + if (typeof opts !== "object" || opts === null) + throw new TypeError("Missing options object for RSA key"); + const modulusLength = opts.bits; + if (!Number.isInteger(modulusLength)) + throw new TypeError("RSA bits must be an integer"); + if (modulusLength <= 0 || modulusLength > 16384) + throw new RangeError("RSA bits must be non-zero and <= 16384"); + return ["rsa", { modulusLength, publicKeyEncoding, privateKeyEncoding }]; + } + case "ecdsa": { + if (typeof opts !== "object" || opts === null) + throw new TypeError("Missing options object for ECDSA key"); + if (!Number.isInteger(opts.bits)) + throw new TypeError("ECDSA bits must be an integer"); + let namedCurve; + switch (opts.bits) { + case 256: + namedCurve = "prime256v1"; + break; + case 384: + namedCurve = "secp384r1"; + break; + case 521: + namedCurve = "secp521r1"; + break; + default: + throw new Error("ECDSA bits must be 256, 384, or 521"); + } + if (!curves.includes(namedCurve)) + throw new Error("Unsupported ECDSA bits value"); + return ["ec", { namedCurve, publicKeyEncoding, privateKeyEncoding }]; + } + case "ed25519": + return ["ed25519", { publicKeyEncoding, privateKeyEncoding }]; + default: + throw new Error(`Unsupported key type: ${type}`); + } + } + function parseDERs(keyType, pub, priv) { + switch (keyType) { + case "rsa": { + let reader = new Ber.Reader(priv); + reader.readSequence(); + if (reader.readInt() !== 0) + throw new Error("Unsupported version in RSA private key"); + reader.readSequence(); + if (reader.readOID() !== "1.2.840.113549.1.1.1") + throw new Error("Bad RSA private OID"); + if (reader.readByte() !== Ber.Null) + throw new Error("Malformed RSA private key (expected null)"); + if (reader.readByte() !== 0) { + throw new Error( + "Malformed RSA private key (expected zero-length null)" + ); + } + reader = new Ber.Reader(reader.readString(Ber.OctetString, true)); + reader.readSequence(); + if (reader.readInt() !== 0) + throw new Error("Unsupported version in RSA private key"); + const n = reader.readString(Ber.Integer, true); + const e = reader.readString(Ber.Integer, true); + const d = reader.readString(Ber.Integer, true); + const p = reader.readString(Ber.Integer, true); + const q = reader.readString(Ber.Integer, true); + reader.readString(Ber.Integer, true); + reader.readString(Ber.Integer, true); + const iqmp = reader.readString(Ber.Integer, true); + const keyName = Buffer.from("ssh-rsa"); + const privBuf = Buffer.allocUnsafe( + 4 + keyName.length + 4 + n.length + 4 + e.length + 4 + d.length + 4 + iqmp.length + 4 + p.length + 4 + q.length + ); + let pos = 0; + privBuf.writeUInt32BE(keyName.length, pos += 0); + privBuf.set(keyName, pos += 4); + privBuf.writeUInt32BE(n.length, pos += keyName.length); + privBuf.set(n, pos += 4); + privBuf.writeUInt32BE(e.length, pos += n.length); + privBuf.set(e, pos += 4); + privBuf.writeUInt32BE(d.length, pos += e.length); + privBuf.set(d, pos += 4); + privBuf.writeUInt32BE(iqmp.length, pos += d.length); + privBuf.set(iqmp, pos += 4); + privBuf.writeUInt32BE(p.length, pos += iqmp.length); + privBuf.set(p, pos += 4); + privBuf.writeUInt32BE(q.length, pos += p.length); + privBuf.set(q, pos += 4); + const pubBuf = Buffer.allocUnsafe( + 4 + keyName.length + 4 + e.length + 4 + n.length + ); + pos = 0; + pubBuf.writeUInt32BE(keyName.length, pos += 0); + pubBuf.set(keyName, pos += 4); + pubBuf.writeUInt32BE(e.length, pos += keyName.length); + pubBuf.set(e, pos += 4); + pubBuf.writeUInt32BE(n.length, pos += e.length); + pubBuf.set(n, pos += 4); + return { sshName: keyName.toString(), priv: privBuf, pub: pubBuf }; + } + case "ec": { + let reader = new Ber.Reader(pub); + reader.readSequence(); + reader.readSequence(); + if (reader.readOID() !== "1.2.840.10045.2.1") + throw new Error("Bad ECDSA public OID"); + reader.readOID(); + let pubBin = reader.readString(Ber.BitString, true); + { + let i = 0; + for (; i < pubBin.length && pubBin[i] === 0; ++i) ; + if (i > 0) + pubBin = pubBin.slice(i); + } + reader = new Ber.Reader(priv); + reader.readSequence(); + if (reader.readInt() !== 0) + throw new Error("Unsupported version in ECDSA private key"); + reader.readSequence(); + if (reader.readOID() !== "1.2.840.10045.2.1") + throw new Error("Bad ECDSA private OID"); + const curveOID = reader.readOID(); + let sshCurveName; + switch (curveOID) { + case "1.2.840.10045.3.1.7": + sshCurveName = "nistp256"; + break; + case "1.3.132.0.34": + sshCurveName = "nistp384"; + break; + case "1.3.132.0.35": + sshCurveName = "nistp521"; + break; + default: + throw new Error("Unsupported curve in ECDSA private key"); + } + reader = new Ber.Reader(reader.readString(Ber.OctetString, true)); + reader.readSequence(); + if (reader.readInt() !== 1) + throw new Error("Unsupported version in ECDSA private key"); + const privBin = Buffer.concat([ + Buffer.from([0]), + reader.readString(Ber.OctetString, true) + ]); + const keyName = Buffer.from(`ecdsa-sha2-${sshCurveName}`); + sshCurveName = Buffer.from(sshCurveName); + const privBuf = Buffer.allocUnsafe( + 4 + keyName.length + 4 + sshCurveName.length + 4 + pubBin.length + 4 + privBin.length + ); + let pos = 0; + privBuf.writeUInt32BE(keyName.length, pos += 0); + privBuf.set(keyName, pos += 4); + privBuf.writeUInt32BE(sshCurveName.length, pos += keyName.length); + privBuf.set(sshCurveName, pos += 4); + privBuf.writeUInt32BE(pubBin.length, pos += sshCurveName.length); + privBuf.set(pubBin, pos += 4); + privBuf.writeUInt32BE(privBin.length, pos += pubBin.length); + privBuf.set(privBin, pos += 4); + const pubBuf = Buffer.allocUnsafe( + 4 + keyName.length + 4 + sshCurveName.length + 4 + pubBin.length + ); + pos = 0; + pubBuf.writeUInt32BE(keyName.length, pos += 0); + pubBuf.set(keyName, pos += 4); + pubBuf.writeUInt32BE(sshCurveName.length, pos += keyName.length); + pubBuf.set(sshCurveName, pos += 4); + pubBuf.writeUInt32BE(pubBin.length, pos += sshCurveName.length); + pubBuf.set(pubBin, pos += 4); + return { sshName: keyName.toString(), priv: privBuf, pub: pubBuf }; + } + case "ed25519": { + let reader = new Ber.Reader(pub); + reader.readSequence(); + reader.readSequence(); + if (reader.readOID() !== "1.3.101.112") + throw new Error("Bad ED25519 public OID"); + let pubBin = reader.readString(Ber.BitString, true); + { + let i = 0; + for (; i < pubBin.length && pubBin[i] === 0; ++i) ; + if (i > 0) + pubBin = pubBin.slice(i); + } + reader = new Ber.Reader(priv); + reader.readSequence(); + if (reader.readInt() !== 0) + throw new Error("Unsupported version in ED25519 private key"); + reader.readSequence(); + if (reader.readOID() !== "1.3.101.112") + throw new Error("Bad ED25519 private OID"); + reader = new Ber.Reader(reader.readString(Ber.OctetString, true)); + const privBin = reader.readString(Ber.OctetString, true); + const keyName = Buffer.from("ssh-ed25519"); + const privBuf = Buffer.allocUnsafe( + 4 + keyName.length + 4 + pubBin.length + 4 + (privBin.length + pubBin.length) + ); + let pos = 0; + privBuf.writeUInt32BE(keyName.length, pos += 0); + privBuf.set(keyName, pos += 4); + privBuf.writeUInt32BE(pubBin.length, pos += keyName.length); + privBuf.set(pubBin, pos += 4); + privBuf.writeUInt32BE( + privBin.length + pubBin.length, + pos += pubBin.length + ); + privBuf.set(privBin, pos += 4); + privBuf.set(pubBin, pos += privBin.length); + const pubBuf = Buffer.allocUnsafe( + 4 + keyName.length + 4 + pubBin.length + ); + pos = 0; + pubBuf.writeUInt32BE(keyName.length, pos += 0); + pubBuf.set(keyName, pos += 4); + pubBuf.writeUInt32BE(pubBin.length, pos += keyName.length); + pubBuf.set(pubBin, pos += 4); + return { sshName: keyName.toString(), priv: privBuf, pub: pubBuf }; + } + } + } + function convertKeys(keyType, pub, priv, opts) { + let format = "new"; + let encrypted; + let comment = ""; + if (typeof opts === "object" && opts !== null) { + if (typeof opts.comment === "string" && opts.comment) + comment = opts.comment; + if (typeof opts.format === "string" && opts.format) + format = opts.format; + if (opts.passphrase) { + let passphrase; + if (typeof opts.passphrase === "string") + passphrase = Buffer.from(opts.passphrase); + else if (Buffer.isBuffer(opts.passphrase)) + passphrase = opts.passphrase; + else + throw new Error("Invalid passphrase"); + if (opts.cipher === void 0) + throw new Error("Missing cipher name"); + const cipher = ciphers.get(opts.cipher); + if (cipher === void 0) + throw new Error("Invalid cipher name"); + if (format === "new") { + let rounds = DEFAULT_ROUNDS; + if (opts.rounds !== void 0) { + if (!Number.isInteger(opts.rounds)) + throw new TypeError("rounds must be an integer"); + if (opts.rounds > 0) + rounds = opts.rounds; + } + const gen = Buffer.allocUnsafe(cipher.keyLen + cipher.ivLen); + const salt = randomBytes(SALT_LEN); + const r = bcrypt_pbkdf( + passphrase, + passphrase.length, + salt, + salt.length, + gen, + gen.length, + rounds + ); + if (r !== 0) + return new Error("Failed to generate information to encrypt key"); + const kdfOptions = Buffer.allocUnsafe(4 + salt.length + 4); + { + let pos = 0; + kdfOptions.writeUInt32BE(salt.length, pos += 0); + kdfOptions.set(salt, pos += 4); + kdfOptions.writeUInt32BE(rounds, pos += salt.length); + } + encrypted = { + cipher, + cipherName: opts.cipher, + kdfName: "bcrypt", + kdfOptions, + key: gen.slice(0, cipher.keyLen), + iv: gen.slice(cipher.keyLen) + }; + } + } + } + switch (format) { + case "new": { + let privateB64 = "-----BEGIN OPENSSH PRIVATE KEY-----\n"; + let publicB64; + const cipherName = Buffer.from(encrypted ? encrypted.cipherName : "none"); + const kdfName = Buffer.from(encrypted ? encrypted.kdfName : "none"); + const kdfOptions = encrypted ? encrypted.kdfOptions : Buffer.alloc(0); + const blockLen = encrypted ? encrypted.cipher.blockLen : 8; + const parsed = parseDERs(keyType, pub, priv); + const checkInt = randomBytes(4); + const commentBin = Buffer.from(comment); + const privBlobLen = 4 + 4 + parsed.priv.length + 4 + commentBin.length; + let padding = []; + for (let i = 1; (privBlobLen + padding.length) % blockLen; ++i) + padding.push(i & 255); + padding = Buffer.from(padding); + let privBlob = Buffer.allocUnsafe(privBlobLen + padding.length); + let extra; + { + let pos = 0; + privBlob.set(checkInt, pos += 0); + privBlob.set(checkInt, pos += 4); + privBlob.set(parsed.priv, pos += 4); + privBlob.writeUInt32BE(commentBin.length, pos += parsed.priv.length); + privBlob.set(commentBin, pos += 4); + privBlob.set(padding, pos += commentBin.length); + } + if (encrypted) { + const options = { authTagLength: encrypted.cipher.authLen }; + const cipher = createCipheriv( + encrypted.cipher.sslName, + encrypted.key, + encrypted.iv, + options + ); + cipher.setAutoPadding(false); + privBlob = Buffer.concat([cipher.update(privBlob), cipher.final()]); + if (encrypted.cipher.authLen > 0) + extra = cipher.getAuthTag(); + else + extra = Buffer.alloc(0); + encrypted.key.fill(0); + encrypted.iv.fill(0); + } else { + extra = Buffer.alloc(0); + } + const magicBytes = Buffer.from("openssh-key-v1\0"); + const privBin = Buffer.allocUnsafe( + magicBytes.length + 4 + cipherName.length + 4 + kdfName.length + 4 + kdfOptions.length + 4 + 4 + parsed.pub.length + 4 + privBlob.length + extra.length + ); + { + let pos = 0; + privBin.set(magicBytes, pos += 0); + privBin.writeUInt32BE(cipherName.length, pos += magicBytes.length); + privBin.set(cipherName, pos += 4); + privBin.writeUInt32BE(kdfName.length, pos += cipherName.length); + privBin.set(kdfName, pos += 4); + privBin.writeUInt32BE(kdfOptions.length, pos += kdfName.length); + privBin.set(kdfOptions, pos += 4); + privBin.writeUInt32BE(1, pos += kdfOptions.length); + privBin.writeUInt32BE(parsed.pub.length, pos += 4); + privBin.set(parsed.pub, pos += 4); + privBin.writeUInt32BE(privBlob.length, pos += parsed.pub.length); + privBin.set(privBlob, pos += 4); + privBin.set(extra, pos += privBlob.length); + } + { + const b64 = privBin.base64Slice(0, privBin.length); + let formatted = b64.replace(/.{64}/g, "$&\n"); + if (b64.length & 63) + formatted += "\n"; + privateB64 += formatted; + } + { + const b64 = parsed.pub.base64Slice(0, parsed.pub.length); + publicB64 = `${parsed.sshName} ${b64}${comment ? ` ${comment}` : ""}`; + } + privateB64 += "-----END OPENSSH PRIVATE KEY-----\n"; + return { + private: privateB64, + public: publicB64 + }; + } + default: + throw new Error("Invalid output key format"); + } + } + function noop3() { + } + module2.exports = { + generateKeyPair: (keyType, opts, cb) => { + if (typeof opts === "function") { + cb = opts; + opts = void 0; + } + if (typeof cb !== "function") + cb = noop3; + const args = makeArgs(keyType, opts); + generateKeyPair_(...args, (err, pub, priv) => { + if (err) + return cb(err); + let ret; + try { + ret = convertKeys(args[0], pub, priv, opts); + } catch (ex) { + return cb(ex); + } + cb(null, ret); + }); + }, + generateKeyPairSync: (keyType, opts) => { + const args = makeArgs(keyType, opts); + const { publicKey: pub, privateKey: priv } = generateKeyPairSync_(...args); + return convertKeys(args[0], pub, priv, opts); + } + }; + } +}); + +// node_modules/ssh2/lib/index.js +var require_lib4 = __commonJS({ + "node_modules/ssh2/lib/index.js"(exports2, module2) { + "use strict"; + var { + AgentProtocol, + BaseAgent, + createAgent, + CygwinAgent, + OpenSSHAgent, + PageantAgent + } = require_agent2(); + var { + SSHTTPAgent: HTTPAgent, + SSHTTPSAgent: HTTPSAgent + } = require_http_agents(); + var { parseKey } = require_keyParser(); + var { + flagsToString, + OPEN_MODE, + STATUS_CODE, + stringToFlags + } = require_SFTP(); + module2.exports = { + AgentProtocol, + BaseAgent, + createAgent, + Client: require_client2(), + CygwinAgent, + HTTPAgent, + HTTPSAgent, + OpenSSHAgent, + PageantAgent, + Server: require_server(), + utils: { + parseKey, + ...require_keygen(), + sftp: { + flagsToString, + OPEN_MODE, + STATUS_CODE, + stringToFlags + } + } + }; + } +}); + +// node_modules/docker-modem/lib/ssh.js +var require_ssh = __commonJS({ + "node_modules/docker-modem/lib/ssh.js"(exports2, module2) { + var Client = require_lib4().Client; + var http2 = require("http"); + module2.exports = function(opt) { + var conn = new Client(); + var agent = new http2.Agent(); + agent.createConnection = function(options, fn) { + try { + conn.once("ready", function() { + conn.exec("docker system dial-stdio", function(err, stream2) { + if (err) { + handleError(err, fn); + } + fn(null, stream2); + stream2.addListener("error", (err2) => { + handleError(err2, fn); + }); + stream2.once("close", () => { + conn.end(); + agent.destroy(); + }); + }); + }).on("error", (err) => { + handleError(err, fn); + }).connect(opt); + conn.once("end", () => agent.destroy()); + } catch (err) { + handleError(err); + } + }; + function handleError(err, cb) { + conn.end(); + agent.destroy(); + if (cb) { + cb(err); + } else { + throw err; + } + } + return agent; + }; + } +}); + +// 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/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); + if (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 = arguments[i] != null ? arguments[i] : {}; + if (i % 2) { + ownKeys(Object(source), true).forEach(function(key) { + _defineProperty(target, key, source[key]); + }); + } else if (Object.getOwnPropertyDescriptors) { + Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + } else { + ownKeys(Object(source)).forEach(function(key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + } + return target; + } + function _defineProperty(obj, key, value) { + 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, descriptor.key, descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } + 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 join(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 concat(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({}, options, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + return BufferList; + })(); + } +}); + +// 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(stream2, err) { + var rState = stream2._readableState; + var wState = stream2._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream2.destroy(err); + else stream2.emit("error", err); + } + module2.exports = { + destroy, + undestroy, + errorOrDestroy + }; + } +}); + +// node_modules/readable-stream/errors.js +var require_errors3 = __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 endsWith(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 (endsWith(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_state = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/state.js"(exports2, module2) { + "use strict"; + var ERR_INVALID_OPT_VALUE = require_errors3().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 inherits(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 inherits(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 { + util = require("util"); + if (typeof util.inherits !== "function") throw ""; + module2.exports = util.inherits; + } catch (e) { + module2.exports = require_inherits_browser(); + } + var util; + } +}); + +// 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/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 = Writable2; + function CorkedRequest(state) { + var _this = this; + this.next = null; + this.entry = null; + this.finish = function() { + onCorkedFinish(_this, state); + }; + } + var Duplex; + Writable2.WritableState = WritableState; + var internalUtil = { + deprecate: require_node() + }; + var Stream = require_stream(); + var Buffer2 = require("buffer").Buffer; + var OurUint8Array = global.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_errors3().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()(Writable2, Stream); + function nop() { + } + function WritableState(options, stream2, isDuplex) { + Duplex = Duplex || require_stream_duplex(); + options = options || {}; + if (typeof isDuplex !== "boolean") isDuplex = stream2 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(er) { + onwrite(stream2, er); + }; + 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(Writable2, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable2) return false; + return object && object._writableState instanceof WritableState; + } + }); + } else { + realHasInstance = function realHasInstance2(object) { + return object instanceof this; + }; + } + function Writable2(options) { + Duplex = Duplex || require_stream_duplex(); + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable2, this)) return new Writable2(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); + } + Writable2.prototype.pipe = function() { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); + }; + function writeAfterEnd(stream2, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); + errorOrDestroy(stream2, er); + process.nextTick(cb, er); + } + function validChunk(stream2, state, chunk, cb) { + var er; + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== "string" && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer"], chunk); + } + if (er) { + errorOrDestroy(stream2, er); + process.nextTick(cb, er); + return false; + } + return true; + } + Writable2.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; + }; + Writable2.prototype.cork = function() { + this._writableState.corked++; + }; + Writable2.prototype.uncork = function() { + var state = this._writableState; + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; + Writable2.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(Writable2.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(Writable2.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(stream2, 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(stream2, state, false, len, chunk, encoding, cb); + } + return ret; + } + function doWrite(stream2, 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) stream2._writev(chunk, state.onwrite); + else stream2._write(chunk, encoding, state.onwrite); + state.sync = false; + } + function onwriteError(stream2, state, sync, er, cb) { + --state.pendingcb; + if (sync) { + process.nextTick(cb, er); + process.nextTick(finishMaybe, stream2, state); + stream2._writableState.errorEmitted = true; + errorOrDestroy(stream2, er); + } else { + cb(er); + stream2._writableState.errorEmitted = true; + errorOrDestroy(stream2, er); + finishMaybe(stream2, state); + } + } + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + function onwrite(stream2, er) { + var state = stream2._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== "function") throw new ERR_MULTIPLE_CALLBACK(); + onwriteStateUpdate(state); + if (er) onwriteError(stream2, state, sync, er, cb); + else { + var finished = needFinish(state) || stream2.destroyed; + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream2, state); + } + if (sync) { + process.nextTick(afterWrite, stream2, state, finished, cb); + } else { + afterWrite(stream2, state, finished, cb); + } + } + } + function afterWrite(stream2, state, finished, cb) { + if (!finished) onwriteDrain(stream2, state); + state.pendingcb--; + cb(); + finishMaybe(stream2, state); + } + function onwriteDrain(stream2, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream2.emit("drain"); + } + } + function clearBuffer(stream2, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + if (stream2._writev && entry && entry.next) { + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + doWrite(stream2, state, true, state.length, buffer, "", 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(stream2, 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; + } + Writable2.prototype._write = function(chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED("_write()")); + }; + Writable2.prototype._writev = null; + Writable2.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(Writable2.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(stream2, state) { + stream2._final(function(err) { + state.pendingcb--; + if (err) { + errorOrDestroy(stream2, err); + } + state.prefinished = true; + stream2.emit("prefinish"); + finishMaybe(stream2, state); + }); + } + function prefinish(stream2, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream2._final === "function" && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + process.nextTick(callFinal, stream2, state); + } else { + state.prefinished = true; + stream2.emit("prefinish"); + } + } + } + function finishMaybe(stream2, state) { + var need = needFinish(state); + if (need) { + prefinish(stream2, state); + if (state.pendingcb === 0) { + state.finished = true; + stream2.emit("finish"); + if (state.autoDestroy) { + var rState = stream2._readableState; + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream2.destroy(); + } + } + } + } + return need; + } + function endWritable(stream2, state, cb) { + state.ending = true; + finishMaybe(stream2, state); + if (cb) { + if (state.finished) process.nextTick(cb); + else stream2.once("finish", cb); + } + state.ended = true; + stream2.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(Writable2.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; + } + }); + Writable2.prototype.destroy = destroyImpl.destroy; + Writable2.prototype._undestroy = destroyImpl.undestroy; + Writable2.prototype._destroy = function(err, cb) { + cb(err); + }; + } +}); + +// 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 Writable2 = require_stream_writable(); + require_inherits()(Duplex, Readable2); + { + keys = objectKeys(Writable2.prototype); + for (v = 0; v < keys.length; v++) { + method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable2.prototype[method]; + } + } + var keys; + var method; + var v; + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + Readable2.call(this, options); + Writable2.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/string_decoder/node_modules/safe-buffer/index.js +var require_safe_buffer = __commonJS({ + "node_modules/string_decoder/node_modules/safe-buffer/index.js"(exports2, module2) { + var buffer = require("buffer"); + var Buffer2 = buffer.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 = buffer; + } else { + copyProps(buffer, 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(size, fill, encoding) { + if (typeof size !== "number") { + throw new TypeError("Argument must be a number"); + } + var buf = Buffer2(size); + 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(size) { + if (typeof size !== "number") { + throw new TypeError("Argument must be a number"); + } + return Buffer2(size); + }; + SafeBuffer.allocUnsafeSlow = function(size) { + if (typeof size !== "number") { + throw new TypeError("Argument must be a number"); + } + return buffer.SlowBuffer(size); + }; + } +}); + +// 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 j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self2.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self2.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + 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_errors3().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 noop3() { + } + function isRequest(stream2) { + return stream2.setHeader && typeof stream2.abort === "function"; + } + function eos(stream2, opts, callback) { + if (typeof opts === "function") return eos(stream2, null, opts); + if (!opts) opts = {}; + callback = once(callback || noop3); + var readable = opts.readable || opts.readable !== false && stream2.readable; + var writable = opts.writable || opts.writable !== false && stream2.writable; + var onlegacyfinish = function onlegacyfinish2() { + if (!stream2.writable) onfinish(); + }; + var writableEnded = stream2._writableState && stream2._writableState.finished; + var onfinish = function onfinish2() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream2); + }; + var readableEnded = stream2._readableState && stream2._readableState.endEmitted; + var onend = function onend2() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream2); + }; + var onerror = function onerror2(err) { + callback.call(stream2, err); + }; + var onclose = function onclose2() { + var err; + if (readable && !readableEnded) { + if (!stream2._readableState || !stream2._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream2, err); + } + if (writable && !writableEnded) { + if (!stream2._writableState || !stream2._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream2, err); + } + }; + var onrequest = function onrequest2() { + stream2.req.on("finish", onfinish); + }; + if (isRequest(stream2)) { + stream2.on("complete", onfinish); + stream2.on("abort", onclose); + if (stream2.req) onrequest(); + else stream2.on("request", onrequest); + } else if (writable && !stream2._writableState) { + stream2.on("end", onlegacyfinish); + stream2.on("close", onlegacyfinish); + } + stream2.on("end", onend); + stream2.on("finish", onfinish); + if (opts.error !== false) stream2.on("error", onerror); + stream2.on("close", onclose); + return function() { + stream2.removeListener("complete", onfinish); + stream2.removeListener("abort", onclose); + stream2.removeListener("request", onrequest); + if (stream2.req) stream2.req.removeListener("finish", onfinish); + stream2.removeListener("end", onlegacyfinish); + stream2.removeListener("close", onlegacyfinish); + stream2.removeListener("finish", onfinish); + stream2.removeListener("end", onend); + stream2.removeListener("error", onerror); + stream2.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) { + if (key in obj) { + Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); + } else { + obj[key] = value; + } + return obj; + } + var finished = require_end_of_stream(); + var kLastResolve = /* @__PURE__ */ Symbol("lastResolve"); + var kLastReject = /* @__PURE__ */ Symbol("lastReject"); + var kError = /* @__PURE__ */ Symbol("error"); + var kEnded = /* @__PURE__ */ Symbol("ended"); + var kLastPromise = /* @__PURE__ */ Symbol("lastPromise"); + var kHandlePromise = /* @__PURE__ */ Symbol("handlePromise"); + var kStream = /* @__PURE__ */ 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 error2 = this[kError]; + if (error2 !== null) { + return Promise.reject(error2); + } + 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(stream2) { + var _Object$create; + var iterator2 = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream2, + 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: stream2._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(stream2, 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; + }); + stream2.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(gen, resolve, reject, _next, _throw, key, arg) { + try { + var info2 = gen[key](arg); + var value = info2.value; + } catch (error2) { + reject(error2); + return; + } + if (info2.done) { + resolve(value); + } else { + Promise.resolve(value).then(_next, _throw); + } + } + function _asyncToGenerator(fn) { + return function() { + var self2 = this, args = arguments; + return new Promise(function(resolve, reject) { + var gen = fn.apply(self2, args); + function _next(value) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); + } + function _throw(err) { + asyncGeneratorStep(gen, 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); + if (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 = arguments[i] != null ? arguments[i] : {}; + if (i % 2) { + ownKeys(Object(source), true).forEach(function(key) { + _defineProperty(target, key, source[key]); + }); + } else if (Object.getOwnPropertyDescriptors) { + Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + } else { + ownKeys(Object(source)).forEach(function(key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + } + return target; + } + function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); + } else { + obj[key] = value; + } + return obj; + } + var ERR_INVALID_ARG_TYPE = require_errors3().codes.ERR_INVALID_ARG_TYPE; + function from(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 _ref = yield iterator2.next(), value = _ref.value, done = _ref.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 = from; + } +}); + +// 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 = global.Uint8Array || function() { + }; + function _uint8ArrayToBuffer(chunk) { + return Buffer2.from(chunk); + } + function _isUint8Array(obj) { + return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array; + } + var debugUtil = require("util"); + var debug2; + if (debugUtil && debugUtil.debuglog) { + debug2 = debugUtil.debuglog("stream"); + } else { + debug2 = function debug3() { + }; + } + var BufferList = require_buffer_list(); + var destroyImpl = require_destroy(); + var _require = require_state(); + var getHighWaterMark = _require.getHighWaterMark; + var _require$codes = require_errors3().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 from; + require_inherits()(Readable2, Stream); + var errorOrDestroy = destroyImpl.errorOrDestroy; + var kProxyEvents = ["error", "close", "destroy", "pause", "resume"]; + function prependListener(emitter, event, fn) { + if (typeof emitter.prependListener === "function") return emitter.prependListener(event, fn); + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn); + else emitter._events[event] = [fn, emitter._events[event]]; + } + function ReadableState(options, stream2, isDuplex) { + Duplex = Duplex || require_stream_duplex(); + options = options || {}; + if (typeof isDuplex !== "boolean") isDuplex = stream2 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(stream2, chunk, encoding, addToFront, skipChunkCheck) { + debug2("readableAddChunk", chunk); + var state = stream2._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream2, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + errorOrDestroy(stream2, er); + } 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(stream2, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT()); + else addChunk(stream2, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream2, 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(stream2, state, chunk, false); + else maybeReadMore(stream2, state); + } else { + addChunk(stream2, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + maybeReadMore(stream2, state); + } + } + return !state.ended && (state.length < state.highWaterMark || state.length === 0); + } + function addChunk(stream2, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream2.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(stream2); + } + maybeReadMore(stream2, state); + } + function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== "string" && chunk !== void 0 && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer", "Uint8Array"], chunk); + } + return er; + } + 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) { + debug2("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)) { + debug2("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; + debug2("need readable", doRead); + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug2("length less than watermark", doRead); + } + if (state.ended || state.reading) { + doRead = false; + debug2("reading or ended", doRead); + } else if (doRead) { + debug2("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(stream2, state) { + debug2("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(stream2); + } else { + state.needReadable = false; + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream2); + } + } + } + function emitReadable(stream2) { + var state = stream2._readableState; + debug2("emitReadable", state.needReadable, state.emittedReadable); + state.needReadable = false; + if (!state.emittedReadable) { + debug2("emitReadable", state.flowing); + state.emittedReadable = true; + process.nextTick(emitReadable_, stream2); + } + } + function emitReadable_(stream2) { + var state = stream2._readableState; + debug2("emitReadable_", state.destroyed, state.length, state.ended); + if (!state.destroyed && (state.length || state.ended)) { + stream2.emit("readable"); + state.emittedReadable = false; + } + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream2); + } + function maybeReadMore(stream2, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(maybeReadMore_, stream2, state); + } + } + function maybeReadMore_(stream2, state) { + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug2("maybeReadMore read 0"); + stream2.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; + debug2("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) { + debug2("onunpipe"); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + function onend() { + debug2("onend"); + dest.end(); + } + var ondrain = pipeOnDrain(src); + dest.on("drain", ondrain); + var cleanedUp = false; + function cleanup() { + debug2("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) { + debug2("ondata"); + var ret = dest.write(chunk); + debug2("dest.write", ret); + if (ret === false) { + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug2("false write response, pause", state.awaitDrain); + state.awaitDrain++; + } + src.pause(); + } + } + function onerror(er) { + debug2("onerror", er); + unpipe(); + dest.removeListener("error", onerror); + if (EElistenerCount(dest, "error") === 0) errorOrDestroy(dest, er); + } + prependListener(dest, "error", onerror); + function onclose() { + dest.removeListener("finish", onfinish); + unpipe(); + } + dest.once("close", onclose); + function onfinish() { + debug2("onfinish"); + dest.removeListener("close", onclose); + unpipe(); + } + dest.once("finish", onfinish); + function unpipe() { + debug2("unpipe"); + src.unpipe(dest); + } + dest.emit("pipe", src); + if (!state.flowing) { + debug2("pipe resume"); + src.resume(); + } + return dest; + }; + function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug2("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 index = indexOf(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 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, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + 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; + debug2("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, fn) { + var res = Stream.prototype.removeListener.call(this, ev, fn); + 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) { + debug2("readable nexttick read 0"); + self2.read(0); + } + Readable2.prototype.resume = function() { + var state = this._readableState; + if (!state.flowing) { + debug2("resume"); + state.flowing = !state.readableListening; + resume(this, state); + } + state.paused = false; + return this; + }; + function resume(stream2, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(resume_, stream2, state); + } + } + function resume_(stream2, state) { + debug2("resume", state.reading); + if (!state.reading) { + stream2.read(0); + } + state.resumeScheduled = false; + stream2.emit("resume"); + flow(stream2); + if (state.flowing && !state.reading) stream2.read(0); + } + Readable2.prototype.pause = function() { + debug2("call pause flowing=%j", this._readableState.flowing); + if (this._readableState.flowing !== false) { + debug2("pause"); + this._readableState.flowing = false; + this.emit("pause"); + } + this._readableState.paused = true; + return this; + }; + function flow(stream2) { + var state = stream2._readableState; + debug2("flow", state.flowing); + while (state.flowing && stream2.read() !== null) { + ; + } + } + Readable2.prototype.wrap = function(stream2) { + var _this = this; + var state = this._readableState; + var paused = false; + stream2.on("end", function() { + debug2("wrapped end"); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + _this.push(null); + }); + stream2.on("data", function(chunk) { + debug2("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; + stream2.pause(); + } + }); + for (var i in stream2) { + if (this[i] === void 0 && typeof stream2[i] === "function") { + this[i] = /* @__PURE__ */ (function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream2[method].apply(stream2, arguments); + }; + })(i); + } + } + for (var n = 0; n < kProxyEvents.length; n++) { + stream2.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + this._read = function(n2) { + debug2("wrapped _read", n2); + if (paused) { + paused = false; + stream2.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(stream2) { + var state = stream2._readableState; + debug2("endReadable", state.endEmitted); + if (!state.endEmitted) { + state.ended = true; + process.nextTick(endReadableNT, state, stream2); + } + } + function endReadableNT(state, stream2) { + debug2("endReadableNT", state.endEmitted, state.length); + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream2.readable = false; + stream2.emit("end"); + if (state.autoDestroy) { + var wState = stream2._writableState; + if (!wState || wState.autoDestroy && wState.finished) { + stream2.destroy(); + } + } + } + } + if (typeof Symbol === "function") { + Readable2.from = function(iterable, opts) { + if (from === void 0) { + from = require_from(); + } + return from(Readable2, iterable, opts); + }; + } + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } + } +}); + +// 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_errors3().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(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + if (cb === null) { + return this.emit("error", new ERR_MULTIPLE_CALLBACK()); + } + ts.writechunk = null; + ts.writecb = null; + if (data != null) + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.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(er, data) { + done(_this, er, 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 ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; + Transform.prototype._read = function(n) { + var ts = this._transformState; + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + ts.needTransform = true; + } + }; + Transform.prototype._destroy = function(err, cb) { + Duplex.prototype._destroy.call(this, err, function(err2) { + cb(err2); + }); + }; + function done(stream2, er, data) { + if (er) return stream2.emit("error", er); + if (data != null) + stream2.push(data); + if (stream2._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream2._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream2.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_errors3().codes; + var ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS; + var ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + function noop3(err) { + if (err) throw err; + } + function isRequest(stream2) { + return stream2.setHeader && typeof stream2.abort === "function"; + } + function destroyer(stream2, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream2.on("close", function() { + closed = true; + }); + if (eos === void 0) eos = require_end_of_stream(); + eos(stream2, { + 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 (isRequest(stream2)) return stream2.abort(); + if (typeof stream2.destroy === "function") return stream2.destroy(); + callback(err || new ERR_STREAM_DESTROYED("pipe")); + }; + } + function call(fn) { + fn(); + } + function pipe(from, to) { + return from.pipe(to); + } + function popCallback(streams) { + if (!streams.length) return noop3; + if (typeof streams[streams.length - 1] !== "function") return noop3; + 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 error2; + var destroys = streams.map(function(stream2, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream2, reading, writing, function(err) { + if (!error2) error2 = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error2); + }); + }); + return streams.reduce(pipe); + } + module2.exports = pipeline; + } +}); + +// node_modules/readable-stream/readable.js +var require_readable2 = __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/docker-modem/lib/http_duplex.js +var require_http_duplex = __commonJS({ + "node_modules/docker-modem/lib/http_duplex.js"(exports2, module2) { + module2.exports = HttpDuplex; + var util = require("util"); + var stream2 = require_readable2(); + util.inherits(HttpDuplex, stream2.Duplex); + function HttpDuplex(req, res, options) { + var self2 = this; + if (!(self2 instanceof HttpDuplex)) return new HttpDuplex(req, res, options); + stream2.Duplex.call(self2, options); + self2._output = null; + self2.connect(req, res); + } + HttpDuplex.prototype.connect = function(req, res) { + var self2 = this; + self2.req = req; + self2._output = res; + self2.emit("response", res); + res.on("data", function(c) { + if (!self2.push(c)) self2._output.pause(); + }); + res.on("end", function() { + self2.push(null); + }); + }; + HttpDuplex.prototype._read = function(n) { + if (this._output) this._output.resume(); + }; + HttpDuplex.prototype._write = function(chunk, encoding, cb) { + this.req.write(chunk, encoding); + cb(); + }; + HttpDuplex.prototype.end = function(chunk, encoding, cb) { + this._output.socket.destroySoon(); + return this.req.end(chunk, encoding, cb); + }; + HttpDuplex.prototype.destroy = function() { + this.req.destroy(); + this._output.socket.destroy(); + }; + HttpDuplex.prototype.destroySoon = function() { + this.req.destroy(); + this._output.socket.destroy(); + }; + } +}); + +// node_modules/ms/index.js +var require_ms = __commonJS({ + "node_modules/ms/index.js"(exports2, module2) { + var s = 1e3; + var m = s * 60; + var h = m * 60; + var d = h * 24; + var w = d * 7; + var y = d * 365.25; + module2.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === "string" && val.length > 0) { + return parse3(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 parse3(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 * y; + case "weeks": + case "week": + case "w": + return n * w; + 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 * m; + 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 >= m) { + return Math.round(ms / m) + "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 >= m) { + return plural(ms, msAbs, m, "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 hash = 0; + for (let i = 0; i < namespace.length; i++) { + hash = (hash << 5) - hash + namespace.charCodeAt(i); + hash |= 0; + } + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + function debug2(...args) { + if (!debug2.enabled) { + return; + } + const self2 = debug2; + 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 index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + if (match === "%%") { + return "%"; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === "function") { + const val = args[index]; + match = formatter.call(self2, val); + args.splice(index, 1); + index--; + } + return match; + }); + createDebug.formatArgs.call(self2, args); + const logFn = self2.log || createDebug.log; + logFn.apply(self2, args); + } + debug2.namespace = namespace; + debug2.useColors = createDebug.useColors(); + debug2.color = createDebug.selectColor(namespace); + debug2.extend = extend; + debug2.destroy = createDebug.destroy; + Object.defineProperty(debug2, "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(debug2); + } + return debug2; + } + function extend(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 split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean); + for (const ns of split) { + if (ns[0] === "-") { + createDebug.skips.push(ns.slice(1)); + } else { + createDebug.names.push(ns); + } + } + } + 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 skip of createDebug.skips) { + if (matchesTemplate(name, skip)) { + return false; + } + } + for (const ns of createDebug.names) { + if (matchesTemplate(name, ns)) { + 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 m; + 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 && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[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 index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, (match) => { + if (match === "%%") { + return; + } + index++; + if (match === "%c") { + lastC = index; + } + }); + 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 (error2) { + } + } + function load() { + let r; + try { + r = exports2.storage.getItem("debug") || exports2.storage.getItem("DEBUG"); + } catch (error2) { + } + if (!r && typeof process !== "undefined" && "env" in process) { + r = process.env.DEBUG; + } + return r; + } + function localstorage() { + try { + return localStorage; + } catch (error2) { + } + } + module2.exports = require_common()(exports2); + var { formatters } = module2.exports; + formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (error2) { + return "[UnexpectedJSONParseError]: " + error2.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 os4 = 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 = os4.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((sign) => sign 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 version = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10); + switch (env.TERM_PROGRAM) { + case "iTerm.app": + return version >= 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(stream2) { + const level = supportsColor(stream2, stream2 && stream2.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_node2 = __commonJS({ + "node_modules/debug/src/node.js"(exports2, module2) { + var tty = require("tty"); + var util = require("util"); + exports2.init = init; + exports2.log = log; + exports2.formatArgs = formatArgs; + exports2.save = save; + exports2.load = load; + exports2.useColors = useColors; + exports2.destroy = util.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 (error2) { + } + 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, (_, k) => { + return k.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(util.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(debug2) { + debug2.inspectOpts = {}; + const keys = Object.keys(exports2.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug2.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 util.inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" "); + }; + formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.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_node2(); + } + } +}); + +// node_modules/split-ca/index.js +var require_split_ca = __commonJS({ + "node_modules/split-ca/index.js"(exports2, module2) { + var fs4 = require("fs"); + module2.exports = function(filepath, split, encoding) { + split = typeof split !== "undefined" ? split : "\n"; + encoding = typeof encoding !== "undefined" ? encoding : "utf8"; + var ca = []; + var chain = fs4.readFileSync(filepath, encoding); + if (chain.indexOf("-END CERTIFICATE-") < 0 || chain.indexOf("-BEGIN CERTIFICATE-") < 0) { + throw Error("File does not contain 'BEGIN CERTIFICATE' or 'END CERTIFICATE'"); + } + chain = chain.split(split); + var cert = []; + var _i, _len; + for (_i = 0, _len = chain.length; _i < _len; _i++) { + var line = chain[_i]; + if (!(line.length !== 0)) { + continue; + } + cert.push(line); + if (line.match(/-END CERTIFICATE-/)) { + ca.push(cert.join(split)); + cert = []; + } + } + return ca; + }; + } +}); + +// node_modules/docker-modem/lib/modem.js +var require_modem = __commonJS({ + "node_modules/docker-modem/lib/modem.js"(exports2, module2) { + var querystring = require("querystring"); + var http2 = require_http(); + var fs4 = require("fs"); + var path = require("path"); + var url = require("url"); + var ssh = require_ssh(); + var HttpDuplex = require_http_duplex(); + var debug2 = require_src()("modem"); + var utils = require_utils2(); + var util = require("util"); + var splitca = require_split_ca(); + var os4 = require("os"); + var isWin = os4.type() === "Windows_NT"; + var stream2 = require("stream"); + var defaultOpts = function() { + var host; + var opts = {}; + if (!process.env.DOCKER_HOST) { + opts.socketPath = isWin ? "//./pipe/docker_engine" : findDefaultUnixSocket; + } else if (process.env.DOCKER_HOST.indexOf("unix://") === 0) { + opts.socketPath = process.env.DOCKER_HOST.substring(7) || findDefaultUnixSocket; + } else if (process.env.DOCKER_HOST.indexOf("npipe://") === 0) { + opts.socketPath = process.env.DOCKER_HOST.substring(8) || "//./pipe/docker_engine"; + } else { + var hostStr = process.env.DOCKER_HOST; + if (hostStr.indexOf("//") < 0) { + hostStr = "tcp://" + hostStr; + } + try { + host = new url.URL(hostStr); + } catch (err) { + throw new Error("DOCKER_HOST env variable should be something like tcp://localhost:1234"); + } + opts.port = host.port; + if (process.env.DOCKER_TLS_VERIFY === "1" || opts.port === "2376") { + opts.protocol = "https"; + } else if (host.protocol === "ssh:") { + opts.protocol = "ssh"; + opts.username = host.username; + opts.sshOptions = { + agent: process.env.SSH_AUTH_SOCK + }; + } else { + opts.protocol = "http"; + } + if (process.env.DOCKER_PATH_PREFIX) { + opts.pathPrefix = process.env.DOCKER_PATH_PREFIX; + } else { + opts.pathPrefix = "/"; + } + opts.host = host.hostname; + if (process.env.DOCKER_CERT_PATH) { + opts.ca = splitca(path.join(process.env.DOCKER_CERT_PATH, "ca.pem")); + opts.cert = fs4.readFileSync(path.join(process.env.DOCKER_CERT_PATH, "cert.pem")); + opts.key = fs4.readFileSync(path.join(process.env.DOCKER_CERT_PATH, "key.pem")); + } + if (process.env.DOCKER_CLIENT_TIMEOUT) { + opts.timeout = parseInt(process.env.DOCKER_CLIENT_TIMEOUT, 10); + } + } + return opts; + }; + var findDefaultUnixSocket = function() { + return new Promise(function(resolve) { + var userDockerSocket = path.join(os4.homedir(), ".docker", "run", "docker.sock"); + fs4.access(userDockerSocket, function(err) { + if (err) resolve("/var/run/docker.sock"); + else resolve(userDockerSocket); + }); + }); + }; + var Modem = function(options) { + var optDefaults = defaultOpts(); + var opts = Object.assign({}, optDefaults, options); + this.host = opts.host; + if (!this.host) { + this.socketPath = opts.socketPath; + } + this.port = opts.port; + this.pathPrefix = opts.pathPrefix; + this.username = opts.username; + this.password = opts.password; + this.version = opts.version; + this.key = opts.key; + this.cert = opts.cert; + this.ca = opts.ca; + this.timeout = opts.timeout; + this.connectionTimeout = opts.connectionTimeout; + this.checkServerIdentity = opts.checkServerIdentity; + this.agent = opts.agent; + this.headers = opts.headers || {}; + this.sshOptions = Object.assign({}, options ? options.sshOptions : {}, optDefaults.sshOptions); + if (this.sshOptions.agentForward === void 0) { + this.sshOptions.agentForward = opts.agentForward; + } + if (this.key && this.cert && this.ca) { + this.protocol = "https"; + } + this.protocol = opts.protocol || this.protocol || "http"; + }; + Modem.prototype.dial = function(options, callback) { + var opts, address, data; + if (options.options) { + opts = options.options; + } + if (opts && opts.authconfig) { + delete opts.authconfig; + } + if (opts && opts.abortSignal) { + delete opts.abortSignal; + } + if (this.version) { + options.path = "/" + this.version + options.path; + } + if (this.host) { + var parsed = url.parse(this.host); + address = url.format({ + protocol: parsed.protocol || this.protocol, + hostname: parsed.hostname || this.host, + port: this.port, + pathname: parsed.pathname || this.pathPrefix + }); + address = url.resolve(address, options.path); + } else { + address = options.path; + } + if (options.path.indexOf("?") !== -1) { + if (opts && Object.keys(opts).length > 0) { + address += this.buildQuerystring(opts._query || opts); + } else { + address = address.substring(0, address.length - 1); + } + } + var optionsf = { + path: address, + method: options.method, + headers: options.headers || Object.assign({}, this.headers), + key: this.key, + cert: this.cert, + ca: this.ca + }; + if (this.checkServerIdentity) { + optionsf.checkServerIdentity = this.checkServerIdentity; + } + if (this.agent) { + optionsf.agent = this.agent; + } + if (options.authconfig) { + optionsf.headers["X-Registry-Auth"] = options.authconfig.key || options.authconfig.base64 || Buffer.from(JSON.stringify(options.authconfig)).toString("base64").replace(/\+/g, "-").replace(/\//g, "_"); + } + if (options.registryconfig) { + optionsf.headers["X-Registry-Config"] = options.registryconfig.base64 || Buffer.from(JSON.stringify(options.registryconfig)).toString("base64"); + } + if (options.abortSignal) { + optionsf.signal = options.abortSignal; + } + if (options.file) { + if (typeof options.file === "string") { + data = fs4.createReadStream(path.resolve(options.file)); + } else { + data = options.file; + } + optionsf.headers["Content-Type"] = options?.headers?.["Content-Type"] ?? "application/tar"; + } else if (opts && options.method === "POST") { + data = JSON.stringify(opts._body || opts); + if (options.allowEmpty) { + optionsf.headers["Content-Type"] = options?.headers?.["Content-Type"] ?? "application/json"; + } else { + if (data !== "{}" && data !== '""') { + optionsf.headers["Content-Type"] = options?.headers?.["Content-Type"] ?? "application/json"; + } else { + data = void 0; + } + } + } + if (typeof data === "string") { + optionsf.headers["Content-Length"] = Buffer.byteLength(data); + } else if (Buffer.isBuffer(data) === true) { + optionsf.headers["Content-Length"] = data.length; + } else if (optionsf.method === "PUT" || options.hijack || options.openStdin) { + optionsf.headers["Transfer-Encoding"] = "chunked"; + } + if (options.hijack) { + optionsf.headers.Connection = "Upgrade"; + optionsf.headers.Upgrade = optionsf.headers.Upgrade ?? "tcp"; + } + if (this.socketPath) { + this.getSocketPath().then((socketPath) => { + optionsf.socketPath = socketPath; + this.buildRequest(optionsf, options, data, callback); + }); + } else { + var urlp = url.parse(address); + optionsf.hostname = urlp.hostname; + optionsf.port = urlp.port; + optionsf.path = urlp.path; + this.buildRequest(optionsf, options, data, callback); + } + }; + Modem.prototype.getSocketPath = function() { + if (!this.socketPath) return; + if (this.socketPathCache) return Promise.resolve(this.socketPathCache); + var socketPathValue = typeof this.socketPath === "function" ? this.socketPath() : this.socketPath; + this.socketPathCache = socketPathValue; + return Promise.resolve(socketPathValue); + }; + Modem.prototype.buildRequest = function(options, context3, data, callback) { + var self2 = this; + var connectionTimeoutTimer; + var finished = false; + var opts = self2.protocol === "ssh" ? Object.assign(options, { + agent: ssh(Object.assign({}, self2.sshOptions, { + "host": self2.host, + "port": self2.port, + "username": self2.username, + "password": self2.password + })), + protocol: "http:" + }) : options; + var req = null; + try { + req = http2[self2.protocol === "ssh" ? "http" : self2.protocol].request(opts, function() { + }); + } catch (e) { + callback(e); + return; + } + debug2("Sending: %s", util.inspect(options, { + showHidden: true, + depth: null + })); + if (self2.connectionTimeout) { + connectionTimeoutTimer = setTimeout(function() { + debug2("Connection Timeout of %s ms exceeded", self2.connectionTimeout); + req.destroy(); + }, self2.connectionTimeout); + } + if (self2.timeout) { + req.setTimeout(self2.timeout); + req.on("timeout", function() { + debug2("Timeout of %s ms exceeded", self2.timeout); + req.destroy(); + }); + } + if (context3.hijack === true) { + clearTimeout(connectionTimeoutTimer); + req.on("upgrade", function(res, sock, head) { + if (finished === false) { + finished = true; + if (head.length > 0) { + sock.unshift(head); + } + return callback(null, sock); + } + }); + } + req.on("connect", function() { + clearTimeout(connectionTimeoutTimer); + }); + req.on("disconnect", function() { + clearTimeout(connectionTimeoutTimer); + }); + req.on("response", function(res) { + clearTimeout(connectionTimeoutTimer); + if (context3.isStream === true) { + if (finished === false) { + finished = true; + self2.buildPayload(null, context3.isStream, context3.statusCodes, context3.openStdin, req, res, null, callback); + } + } else { + if (options.signal != null) { + stream2.addAbortSignal(options.signal, res); + } + var chunks = []; + res.on("data", function(chunk) { + chunks.push(chunk); + }); + res.on("end", function() { + var buffer = Buffer.concat(chunks); + var result = buffer.toString(); + debug2("Received: %s", result); + var json = utils.parseJSON(result) || buffer; + if (finished === false) { + finished = true; + self2.buildPayload(null, context3.isStream, context3.statusCodes, false, req, res, json, callback); + } + }); + } + }); + req.on("error", function(error2) { + clearTimeout(connectionTimeoutTimer); + if (finished === false) { + finished = true; + self2.buildPayload(error2, context3.isStream, context3.statusCodes, false, {}, {}, null, callback); + } + }); + if (typeof data === "string" || Buffer.isBuffer(data)) { + req.write(data); + } else if (data) { + data.on("error", function(error2) { + req.destroy(error2); + }); + data.pipe(req); + } + if (!context3.openStdin && (typeof data === "string" || data === void 0 || Buffer.isBuffer(data))) { + req.end(); + } + }; + Modem.prototype.buildPayload = function(err, isStream, statusCodes, openStdin, req, res, json, cb) { + if (err) return cb(err, null); + if (statusCodes[res.statusCode] !== true) { + getCause(isStream, res, json, function(err2, cause) { + if (err2) { + return cb(err2, null); + } + var msg = new Error( + "(HTTP code " + res.statusCode + ") " + (statusCodes[res.statusCode] || "unexpected") + " - " + (cause.message || cause.error || cause) + " " + ); + msg.reason = statusCodes[res.statusCode]; + msg.statusCode = res.statusCode; + msg.json = json; + cb(msg, null); + }); + } else { + if (openStdin) { + cb(null, new HttpDuplex(req, res)); + } else if (isStream) { + cb(null, res); + } else { + cb(null, json); + } + } + function getCause(isStream2, res2, json2, callback) { + var chunks = ""; + var done = false; + if (isStream2) { + res2.on("data", function(chunk) { + chunks += chunk; + }); + res2.on("error", function(err2) { + handler2(err2, null); + }); + res2.on("end", function() { + handler2(null, utils.parseJSON(chunks) || chunks); + }); + } else { + callback(null, json2); + } + function handler2(err2, data) { + if (done === false) { + if (err2) { + callback(err2); + } else { + callback(null, data); + } + } + done = true; + } + } + }; + Modem.prototype.demuxStream = function(streama, stdout, stderr) { + var pendingStreamType = null; + var pendingDataLength = null; + var buffer = Buffer.from(""); + function processData(data) { + if (data) { + buffer = Buffer.concat([buffer, data]); + } + if (pendingStreamType === null) { + if (buffer.length >= 8) { + var header = bufferSlice(8); + var streamType = header.readUInt8(0); + var dataLength = header.readUInt32BE(4); + if (streamType !== 0 && streamType !== 1 && streamType !== 2) { + var remaining = Buffer.concat([header, buffer]); + stdout.write(remaining); + buffer = Buffer.from(""); + pendingStreamType = null; + pendingDataLength = null; + streama.removeListener("data", processData); + streama.on("data", function(chunk) { + stdout.write(chunk); + }); + return; + } + pendingStreamType = streamType; + pendingDataLength = dataLength; + processData(); + } + } else { + if (buffer.length >= pendingDataLength) { + var content = bufferSlice(pendingDataLength); + if (pendingStreamType === 1) { + stdout.write(content); + } else { + stderr.write(content); + } + pendingStreamType = null; + pendingDataLength = null; + processData(); + } + } + } + function bufferSlice(end) { + var out = buffer.subarray(0, end); + buffer = Buffer.from(buffer.subarray(end, buffer.length)); + return out; + } + streama.on("data", processData); + }; + Modem.prototype.followProgress = function(streama, onFinished, onProgress) { + var buf = ""; + var output = []; + var finished = false; + streama.on("data", onStreamEvent); + streama.on("error", onStreamError); + streama.on("end", onStreamEnd); + streama.on("close", onStreamEnd); + function onStreamEvent(data) { + buf += data.toString(); + pump(); + function pump() { + var pos; + while ((pos = buf.indexOf("\n")) >= 0) { + if (pos == 0) { + buf = buf.slice(1); + continue; + } + processLine(buf.slice(0, pos)); + buf = buf.slice(pos + 1); + } + } + function processLine(line) { + if (line[line.length - 1] == "\r") line = line.substr(0, line.length - 1); + if (line.length > 0) { + var obj = JSON.parse(line); + output.push(obj); + if (onProgress) { + onProgress(obj); + } + } + } + } + ; + function onStreamError(err) { + finished = true; + streama.removeListener("data", onStreamEvent); + streama.removeListener("error", onStreamError); + streama.removeListener("end", onStreamEnd); + streama.removeListener("close", onStreamEnd); + onFinished(err, output); + } + function onStreamEnd() { + if (!finished) onFinished(null, output); + finished = true; + } + }; + Modem.prototype.buildQuerystring = function(opts) { + var clone = {}; + Object.keys(opts).map(function(key, i) { + if (opts[key] && typeof opts[key] === "object" && !Array.isArray(opts[key])) { + clone[key] = JSON.stringify(opts[key]); + } else { + clone[key] = opts[key]; + } + }); + return querystring.stringify(clone); + }; + module2.exports = Modem; + } +}); + +// node_modules/@balena/dockerignore/ignore.js +var require_ignore = __commonJS({ + "node_modules/@balena/dockerignore/ignore.js"(exports2, module2) { + "use strict"; + var path = require("path"); + var factory = (options) => new IgnoreBase(options); + factory.default = factory; + module2.exports = factory; + function make_array(subject) { + return Array.isArray(subject) ? subject : [subject]; + } + var REGEX_TRAILING_SLASH = /(?<=.)\/$/; + var REGEX_TRAILING_BACKSLASH = /(?<=.)\\$/; + var REGEX_TRAILING_PATH_SEP = path.sep === "\\" ? REGEX_TRAILING_BACKSLASH : REGEX_TRAILING_SLASH; + var KEY_IGNORE = typeof Symbol !== "undefined" ? /* @__PURE__ */ Symbol.for("dockerignore") : "dockerignore"; + function cleanPath(file) { + return path.normalize(file).replace(REGEX_TRAILING_PATH_SEP, ""); + } + function toSlash(file) { + if (path.sep === "/") { + return file; + } + return file.replace(/\\/g, "/"); + } + function fromSlash(file) { + if (path.sep === "/") { + return file; + } + return file.replace(/\//g, path.sep); + } + var IgnoreBase = class { + constructor({ + // https://github.com/kaelzhang/node-ignore/blob/5.1.4/index.js#L372 + ignorecase = true + } = {}) { + this._rules = []; + this._ignorecase = ignorecase; + this[KEY_IGNORE] = true; + this._initCache(); + } + _initCache() { + this._cache = {}; + } + // @param {Array.|string|Ignore} pattern + add(pattern) { + this._added = false; + if (typeof pattern === "string") { + pattern = pattern.split(/\r?\n/g); + } + make_array(pattern).forEach(this._addPattern, this); + if (this._added) { + this._initCache(); + } + return this; + } + // legacy + addPattern(pattern) { + return this.add(pattern); + } + _addPattern(pattern) { + if (pattern && pattern[KEY_IGNORE]) { + this._rules = this._rules.concat(pattern._rules); + this._added = true; + return; + } + if (this._checkPattern(pattern)) { + const rule = this._createRule(pattern.trim()); + if (rule !== null) { + this._added = true; + this._rules.push(rule); + } + } + } + _checkPattern(pattern) { + return pattern && typeof pattern === "string" && pattern.indexOf("#") !== 0 && pattern.trim() !== ""; + } + filter(paths) { + return make_array(paths).filter((path2) => this._filter(path2)); + } + createFilter() { + return (path2) => this._filter(path2); + } + ignores(path2) { + return !this._filter(path2); + } + // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L41-L53 + // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L29-L55 + _createRule(pattern) { + const origin = pattern; + let negative = false; + if (pattern[0] === "!") { + negative = true; + pattern = pattern.substring(1).trim(); + } + if (pattern.length > 0) { + pattern = cleanPath(pattern); + pattern = toSlash(pattern); + if (pattern.length > 1 && pattern[0] === "/") { + pattern = pattern.slice(1); + } + } + if (negative) { + pattern = "!" + pattern; + } + pattern = pattern.trim(); + if (pattern === "") { + return null; + } + pattern = cleanPath(pattern); + if (pattern[0] === "!") { + if (pattern.length === 1) { + return null; + } + negative = true; + pattern = pattern.substring(1); + } else { + negative = false; + } + return { + origin, + pattern, + // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L54 + dirs: pattern.split(path.sep), + negative + }; + } + // @returns `Boolean` true if the `path` is NOT ignored + _filter(path2) { + if (!path2) { + return false; + } + if (path2 in this._cache) { + return this._cache[path2]; + } + return this._cache[path2] = this._test(path2); + } + // @returns {Boolean} true if a file is NOT ignored + // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L62 + _test(file) { + file = fromSlash(file); + const parentPath = cleanPath(path.dirname(file)); + const parentPathDirs = parentPath.split(path.sep); + let matched = false; + this._rules.forEach((rule) => { + let match = this._match(file, rule); + if (!match && parentPath !== ".") { + if (rule.dirs.includes("**")) { + for (let i = rule.dirs.filter((x) => x !== "**").length; i <= parentPathDirs.length; i++) { + match = match || this._match(parentPathDirs.slice(0, i).join(path.sep), rule); + } + } else if (rule.dirs.length <= parentPathDirs.length) { + match = this._match(parentPathDirs.slice(0, rule.dirs.length).join(path.sep), rule); + } + } + if (match) { + matched = !rule.negative; + } + }); + return !matched; + } + // @returns {Boolean} true if a file is matched by a rule + _match(file, rule) { + return this._compile(rule).regexp.test(file); + } + // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L139 + _compile(rule) { + if (rule.regexp) { + return rule; + } + let regStr = "^"; + let escapedSlash = path.sep === "\\" ? "\\\\" : path.sep; + for (let i = 0; i < rule.pattern.length; i++) { + const ch = rule.pattern[i]; + if (ch === "*") { + if (rule.pattern[i + 1] === "*") { + i++; + if (rule.pattern[i + 1] === path.sep) { + i++; + } + if (rule.pattern[i + 1] === void 0) { + regStr += ".*"; + } else { + regStr += `(.*${escapedSlash})?`; + } + } else { + regStr += `[^${escapedSlash}]*`; + } + } else if (ch === "?") { + regStr += `[^${escapedSlash}]`; + } else if (ch === "." || ch === "$") { + regStr += `\\${ch}`; + } else if (ch === "\\") { + if (path.sep === "\\") { + regStr += escapedSlash; + continue; + } + if (rule.pattern[i + 1] !== void 0) { + regStr += "\\" + rule.pattern[i + 1]; + i++; + } else { + regStr += "\\"; + } + } else { + regStr += ch; + } + } + regStr += "$"; + rule.regexp = new RegExp(regStr, this._ignorecase ? "i" : ""); + return rule; + } + }; + } +}); + +// node_modules/chownr/chownr.js +var require_chownr = __commonJS({ + "node_modules/chownr/chownr.js"(exports2, module2) { + "use strict"; + var fs4 = require("fs"); + var path = require("path"); + var LCHOWN = fs4.lchown ? "lchown" : "chown"; + var LCHOWNSYNC = fs4.lchownSync ? "lchownSync" : "chownSync"; + var needEISDIRHandled = fs4.lchown && !process.version.match(/v1[1-9]+\./) && !process.version.match(/v10\.[6-9]/); + var lchownSync = (path2, uid, gid) => { + try { + return fs4[LCHOWNSYNC](path2, uid, gid); + } catch (er) { + if (er.code !== "ENOENT") + throw er; + } + }; + var chownSync = (path2, uid, gid) => { + try { + return fs4.chownSync(path2, uid, gid); + } catch (er) { + if (er.code !== "ENOENT") + throw er; + } + }; + var handleEISDIR = needEISDIRHandled ? (path2, uid, gid, cb) => (er) => { + if (!er || er.code !== "EISDIR") + cb(er); + else + fs4.chown(path2, uid, gid, cb); + } : (_, __, ___, cb) => cb; + var handleEISDirSync = needEISDIRHandled ? (path2, uid, gid) => { + try { + return lchownSync(path2, uid, gid); + } catch (er) { + if (er.code !== "EISDIR") + throw er; + chownSync(path2, uid, gid); + } + } : (path2, uid, gid) => lchownSync(path2, uid, gid); + var nodeVersion = process.version; + var readdir2 = (path2, options, cb) => fs4.readdir(path2, options, cb); + var readdirSync = (path2, options) => fs4.readdirSync(path2, options); + if (/^v4\./.test(nodeVersion)) + readdir2 = (path2, options, cb) => fs4.readdir(path2, cb); + var chown = (cpath, uid, gid, cb) => { + fs4[LCHOWN](cpath, uid, gid, handleEISDIR(cpath, uid, gid, (er) => { + cb(er && er.code !== "ENOENT" ? er : null); + })); + }; + var chownrKid = (p, child, uid, gid, cb) => { + if (typeof child === "string") + return fs4.lstat(path.resolve(p, child), (er, stats) => { + if (er) + return cb(er.code !== "ENOENT" ? er : null); + stats.name = child; + chownrKid(p, stats, uid, gid, cb); + }); + if (child.isDirectory()) { + chownr(path.resolve(p, child.name), uid, gid, (er) => { + if (er) + return cb(er); + const cpath = path.resolve(p, child.name); + chown(cpath, uid, gid, cb); + }); + } else { + const cpath = path.resolve(p, child.name); + chown(cpath, uid, gid, cb); + } + }; + var chownr = (p, uid, gid, cb) => { + readdir2(p, { withFileTypes: true }, (er, children) => { + if (er) { + if (er.code === "ENOENT") + return cb(); + else if (er.code !== "ENOTDIR" && er.code !== "ENOTSUP") + return cb(er); + } + if (er || !children.length) + return chown(p, uid, gid, cb); + let len = children.length; + let errState = null; + const then = (er2) => { + if (errState) + return; + if (er2) + return cb(errState = er2); + if (--len === 0) + return chown(p, uid, gid, cb); + }; + children.forEach((child) => chownrKid(p, child, uid, gid, then)); + }); + }; + var chownrKidSync = (p, child, uid, gid) => { + if (typeof child === "string") { + try { + const stats = fs4.lstatSync(path.resolve(p, child)); + stats.name = child; + child = stats; + } catch (er) { + if (er.code === "ENOENT") + return; + else + throw er; + } + } + if (child.isDirectory()) + chownrSync(path.resolve(p, child.name), uid, gid); + handleEISDirSync(path.resolve(p, child.name), uid, gid); + }; + var chownrSync = (p, uid, gid) => { + let children; + try { + children = readdirSync(p, { withFileTypes: true }); + } catch (er) { + if (er.code === "ENOENT") + return; + else if (er.code === "ENOTDIR" || er.code === "ENOTSUP") + return handleEISDirSync(p, uid, gid); + else + throw er; + } + if (children && children.length) + children.forEach((child) => chownrKidSync(p, child, uid, gid)); + return handleEISDirSync(p, uid, gid); + }; + module2.exports = chownr; + chownr.sync = chownrSync; + } +}); + +// node_modules/bl/BufferList.js +var require_BufferList = __commonJS({ + "node_modules/bl/BufferList.js"(exports2, module2) { + "use strict"; + var { Buffer: Buffer2 } = require("buffer"); + var symbol = /* @__PURE__ */ Symbol.for("BufferList"); + function BufferList(buf) { + if (!(this instanceof BufferList)) { + return new BufferList(buf); + } + BufferList._init.call(this, buf); + } + BufferList._init = function _init(buf) { + Object.defineProperty(this, symbol, { value: true }); + this._bufs = []; + this.length = 0; + if (buf) { + this.append(buf); + } + }; + BufferList.prototype._new = function _new(buf) { + return new BufferList(buf); + }; + BufferList.prototype._offset = function _offset(offset) { + if (offset === 0) { + return [0, 0]; + } + let tot = 0; + for (let i = 0; i < this._bufs.length; i++) { + const _t = tot + this._bufs[i].length; + if (offset < _t || i === this._bufs.length - 1) { + return [i, offset - tot]; + } + tot = _t; + } + }; + BufferList.prototype._reverseOffset = function(blOffset) { + const bufferId = blOffset[0]; + let offset = blOffset[1]; + for (let i = 0; i < bufferId; i++) { + offset += this._bufs[i].length; + } + return offset; + }; + BufferList.prototype.get = function get(index) { + if (index > this.length || index < 0) { + return void 0; + } + const offset = this._offset(index); + return this._bufs[offset[0]][offset[1]]; + }; + BufferList.prototype.slice = function slice(start, end) { + if (typeof start === "number" && start < 0) { + start += this.length; + } + if (typeof end === "number" && end < 0) { + end += this.length; + } + return this.copy(null, 0, start, end); + }; + BufferList.prototype.copy = function copy(dst, dstStart, srcStart, srcEnd) { + if (typeof srcStart !== "number" || srcStart < 0) { + srcStart = 0; + } + if (typeof srcEnd !== "number" || srcEnd > this.length) { + srcEnd = this.length; + } + if (srcStart >= this.length) { + return dst || Buffer2.alloc(0); + } + if (srcEnd <= 0) { + return dst || Buffer2.alloc(0); + } + const copy2 = !!dst; + const off = this._offset(srcStart); + const len = srcEnd - srcStart; + let bytes = len; + let bufoff = copy2 && dstStart || 0; + let start = off[1]; + if (srcStart === 0 && srcEnd === this.length) { + if (!copy2) { + return this._bufs.length === 1 ? this._bufs[0] : Buffer2.concat(this._bufs, this.length); + } + for (let i = 0; i < this._bufs.length; i++) { + this._bufs[i].copy(dst, bufoff); + bufoff += this._bufs[i].length; + } + return dst; + } + if (bytes <= this._bufs[off[0]].length - start) { + return copy2 ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes) : this._bufs[off[0]].slice(start, start + bytes); + } + if (!copy2) { + dst = Buffer2.allocUnsafe(len); + } + for (let i = off[0]; i < this._bufs.length; i++) { + const l = this._bufs[i].length - start; + if (bytes > l) { + this._bufs[i].copy(dst, bufoff, start); + bufoff += l; + } else { + this._bufs[i].copy(dst, bufoff, start, start + bytes); + bufoff += l; + break; + } + bytes -= l; + if (start) { + start = 0; + } + } + if (dst.length > bufoff) return dst.slice(0, bufoff); + return dst; + }; + BufferList.prototype.shallowSlice = function shallowSlice(start, end) { + start = start || 0; + end = typeof end !== "number" ? this.length : end; + if (start < 0) { + start += this.length; + } + if (end < 0) { + end += this.length; + } + if (start === end) { + return this._new(); + } + const startOffset = this._offset(start); + const endOffset = this._offset(end); + const buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1); + if (endOffset[1] === 0) { + buffers.pop(); + } else { + buffers[buffers.length - 1] = buffers[buffers.length - 1].slice(0, endOffset[1]); + } + if (startOffset[1] !== 0) { + buffers[0] = buffers[0].slice(startOffset[1]); + } + return this._new(buffers); + }; + BufferList.prototype.toString = function toString(encoding, start, end) { + return this.slice(start, end).toString(encoding); + }; + BufferList.prototype.consume = function consume(bytes) { + bytes = Math.trunc(bytes); + if (Number.isNaN(bytes) || bytes <= 0) return this; + while (this._bufs.length) { + if (bytes >= this._bufs[0].length) { + bytes -= this._bufs[0].length; + this.length -= this._bufs[0].length; + this._bufs.shift(); + } else { + this._bufs[0] = this._bufs[0].slice(bytes); + this.length -= bytes; + break; + } + } + return this; + }; + BufferList.prototype.duplicate = function duplicate() { + const copy = this._new(); + for (let i = 0; i < this._bufs.length; i++) { + copy.append(this._bufs[i]); + } + return copy; + }; + BufferList.prototype.append = function append(buf) { + if (buf == null) { + return this; + } + if (buf.buffer) { + this._appendBuffer(Buffer2.from(buf.buffer, buf.byteOffset, buf.byteLength)); + } else if (Array.isArray(buf)) { + for (let i = 0; i < buf.length; i++) { + this.append(buf[i]); + } + } else if (this._isBufferList(buf)) { + for (let i = 0; i < buf._bufs.length; i++) { + this.append(buf._bufs[i]); + } + } else { + if (typeof buf === "number") { + buf = buf.toString(); + } + this._appendBuffer(Buffer2.from(buf)); + } + return this; + }; + BufferList.prototype._appendBuffer = function appendBuffer(buf) { + this._bufs.push(buf); + this.length += buf.length; + }; + BufferList.prototype.indexOf = function(search, offset, encoding) { + if (encoding === void 0 && typeof offset === "string") { + encoding = offset; + offset = void 0; + } + if (typeof search === "function" || Array.isArray(search)) { + throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.'); + } else if (typeof search === "number") { + search = Buffer2.from([search]); + } else if (typeof search === "string") { + search = Buffer2.from(search, encoding); + } else if (this._isBufferList(search)) { + search = search.slice(); + } else if (Array.isArray(search.buffer)) { + search = Buffer2.from(search.buffer, search.byteOffset, search.byteLength); + } else if (!Buffer2.isBuffer(search)) { + search = Buffer2.from(search); + } + offset = Number(offset || 0); + if (isNaN(offset)) { + offset = 0; + } + if (offset < 0) { + offset = this.length + offset; + } + if (offset < 0) { + offset = 0; + } + if (search.length === 0) { + return offset > this.length ? this.length : offset; + } + const blOffset = this._offset(offset); + let blIndex = blOffset[0]; + let buffOffset = blOffset[1]; + for (; blIndex < this._bufs.length; blIndex++) { + const buff = this._bufs[blIndex]; + while (buffOffset < buff.length) { + const availableWindow = buff.length - buffOffset; + if (availableWindow >= search.length) { + const nativeSearchResult = buff.indexOf(search, buffOffset); + if (nativeSearchResult !== -1) { + return this._reverseOffset([blIndex, nativeSearchResult]); + } + buffOffset = buff.length - search.length + 1; + } else { + const revOffset = this._reverseOffset([blIndex, buffOffset]); + if (this._match(revOffset, search)) { + return revOffset; + } + buffOffset++; + } + } + buffOffset = 0; + } + return -1; + }; + BufferList.prototype._match = function(offset, search) { + if (this.length - offset < search.length) { + return false; + } + for (let searchOffset = 0; searchOffset < search.length; searchOffset++) { + if (this.get(offset + searchOffset) !== search[searchOffset]) { + return false; + } + } + return true; + }; + (function() { + const methods = { + readDoubleBE: 8, + readDoubleLE: 8, + readFloatBE: 4, + readFloatLE: 4, + readInt32BE: 4, + readInt32LE: 4, + readUInt32BE: 4, + readUInt32LE: 4, + readInt16BE: 2, + readInt16LE: 2, + readUInt16BE: 2, + readUInt16LE: 2, + readInt8: 1, + readUInt8: 1, + readIntBE: null, + readIntLE: null, + readUIntBE: null, + readUIntLE: null + }; + for (const m in methods) { + (function(m2) { + if (methods[m2] === null) { + BufferList.prototype[m2] = function(offset, byteLength) { + return this.slice(offset, offset + byteLength)[m2](0, byteLength); + }; + } else { + BufferList.prototype[m2] = function(offset = 0) { + return this.slice(offset, offset + methods[m2])[m2](0); + }; + } + })(m); + } + })(); + BufferList.prototype._isBufferList = function _isBufferList(b) { + return b instanceof BufferList || BufferList.isBufferList(b); + }; + BufferList.isBufferList = function isBufferList(b) { + return b != null && b[symbol]; + }; + module2.exports = BufferList; + } +}); + +// node_modules/bl/bl.js +var require_bl = __commonJS({ + "node_modules/bl/bl.js"(exports2, module2) { + "use strict"; + var DuplexStream = require_readable2().Duplex; + var inherits = require_inherits(); + var BufferList = require_BufferList(); + function BufferListStream(callback) { + if (!(this instanceof BufferListStream)) { + return new BufferListStream(callback); + } + if (typeof callback === "function") { + this._callback = callback; + const piper = function piper2(err) { + if (this._callback) { + this._callback(err); + this._callback = null; + } + }.bind(this); + this.on("pipe", function onPipe(src) { + src.on("error", piper); + }); + this.on("unpipe", function onUnpipe(src) { + src.removeListener("error", piper); + }); + callback = null; + } + BufferList._init.call(this, callback); + DuplexStream.call(this); + } + inherits(BufferListStream, DuplexStream); + Object.assign(BufferListStream.prototype, BufferList.prototype); + BufferListStream.prototype._new = function _new(callback) { + return new BufferListStream(callback); + }; + BufferListStream.prototype._write = function _write(buf, encoding, callback) { + this._appendBuffer(buf); + if (typeof callback === "function") { + callback(); + } + }; + BufferListStream.prototype._read = function _read(size) { + if (!this.length) { + return this.push(null); + } + size = Math.min(size, this.length); + this.push(this.slice(0, size)); + this.consume(size); + }; + BufferListStream.prototype.end = function end(chunk) { + DuplexStream.prototype.end.call(this, chunk); + if (this._callback) { + this._callback(null, this.slice()); + this._callback = null; + } + }; + BufferListStream.prototype._destroy = function _destroy(err, cb) { + this._bufs.length = 0; + this.length = 0; + cb(err); + }; + BufferListStream.prototype._isBufferList = function _isBufferList(b) { + return b instanceof BufferListStream || b instanceof BufferList || BufferListStream.isBufferList(b); + }; + BufferListStream.isBufferList = BufferList.isBufferList; + module2.exports = BufferListStream; + module2.exports.BufferListStream = BufferListStream; + module2.exports.BufferList = BufferList; + } +}); + +// node_modules/tar-fs/node_modules/tar-stream/headers.js +var require_headers2 = __commonJS({ + "node_modules/tar-fs/node_modules/tar-stream/headers.js"(exports2) { + var alloc = Buffer.alloc; + var ZEROS = "0000000000000000000"; + var SEVENS = "7777777777777777777"; + var ZERO_OFFSET = "0".charCodeAt(0); + var USTAR_MAGIC = Buffer.from("ustar\0", "binary"); + var USTAR_VER = Buffer.from("00", "binary"); + var GNU_MAGIC = Buffer.from("ustar ", "binary"); + var GNU_VER = Buffer.from(" \0", "binary"); + var MASK = parseInt("7777", 8); + var MAGIC_OFFSET = 257; + var VERSION_OFFSET = 263; + var clamp = function(index, len, defaultValue) { + if (typeof index !== "number") return defaultValue; + index = ~~index; + if (index >= len) return len; + if (index >= 0) return index; + index += len; + if (index >= 0) return index; + return 0; + }; + var toType = function(flag) { + switch (flag) { + case 0: + return "file"; + case 1: + return "link"; + case 2: + return "symlink"; + case 3: + return "character-device"; + case 4: + return "block-device"; + case 5: + return "directory"; + case 6: + return "fifo"; + case 7: + return "contiguous-file"; + case 72: + return "pax-header"; + case 55: + return "pax-global-header"; + case 27: + return "gnu-long-link-path"; + case 28: + case 30: + return "gnu-long-path"; + } + return null; + }; + var toTypeflag = function(flag) { + switch (flag) { + case "file": + return 0; + case "link": + return 1; + case "symlink": + return 2; + case "character-device": + return 3; + case "block-device": + return 4; + case "directory": + return 5; + case "fifo": + return 6; + case "contiguous-file": + return 7; + case "pax-header": + return 72; + } + return 0; + }; + var indexOf = function(block, num, offset, end) { + for (; offset < end; offset++) { + if (block[offset] === num) return offset; + } + return end; + }; + var cksum = function(block) { + var sum = 8 * 32; + for (var i = 0; i < 148; i++) sum += block[i]; + for (var j = 156; j < 512; j++) sum += block[j]; + return sum; + }; + var encodeOct = function(val, n) { + val = val.toString(8); + if (val.length > n) return SEVENS.slice(0, n) + " "; + else return ZEROS.slice(0, n - val.length) + val + " "; + }; + function parse256(buf) { + var positive; + if (buf[0] === 128) positive = true; + else if (buf[0] === 255) positive = false; + else return null; + var tuple = []; + for (var i = buf.length - 1; i > 0; i--) { + var byte = buf[i]; + if (positive) tuple.push(byte); + else tuple.push(255 - byte); + } + var sum = 0; + var l = tuple.length; + for (i = 0; i < l; i++) { + sum += tuple[i] * Math.pow(256, i); + } + return positive ? sum : -1 * sum; + } + var decodeOct = function(val, offset, length) { + val = val.slice(offset, offset + length); + offset = 0; + if (val[offset] & 128) { + return parse256(val); + } else { + while (offset < val.length && val[offset] === 32) offset++; + var end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length); + while (offset < end && val[offset] === 0) offset++; + if (end === offset) return 0; + return parseInt(val.slice(offset, end).toString(), 8); + } + }; + var decodeStr = function(val, offset, length, encoding) { + return val.slice(offset, indexOf(val, 0, offset, offset + length)).toString(encoding); + }; + var addLength = function(str) { + var len = Buffer.byteLength(str); + var digits = Math.floor(Math.log(len) / Math.log(10)) + 1; + if (len + digits >= Math.pow(10, digits)) digits++; + return len + digits + str; + }; + exports2.decodeLongPath = function(buf, encoding) { + return decodeStr(buf, 0, buf.length, encoding); + }; + exports2.encodePax = function(opts) { + var result = ""; + if (opts.name) result += addLength(" path=" + opts.name + "\n"); + if (opts.linkname) result += addLength(" linkpath=" + opts.linkname + "\n"); + var pax = opts.pax; + if (pax) { + for (var key in pax) { + result += addLength(" " + key + "=" + pax[key] + "\n"); + } + } + return Buffer.from(result); + }; + exports2.decodePax = function(buf) { + var result = {}; + while (buf.length) { + var i = 0; + while (i < buf.length && buf[i] !== 32) i++; + var len = parseInt(buf.slice(0, i).toString(), 10); + if (!len) return result; + var b = buf.slice(i + 1, len - 1).toString(); + var keyIndex = b.indexOf("="); + if (keyIndex === -1) return result; + result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1); + buf = buf.slice(len); + } + return result; + }; + exports2.encode = function(opts) { + var buf = alloc(512); + var name = opts.name; + var prefix = ""; + if (opts.typeflag === 5 && name[name.length - 1] !== "/") name += "/"; + if (Buffer.byteLength(name) !== name.length) return null; + while (Buffer.byteLength(name) > 100) { + var i = name.indexOf("/"); + if (i === -1) return null; + prefix += prefix ? "/" + name.slice(0, i) : name.slice(0, i); + name = name.slice(i + 1); + } + if (Buffer.byteLength(name) > 100 || Buffer.byteLength(prefix) > 155) return null; + if (opts.linkname && Buffer.byteLength(opts.linkname) > 100) return null; + buf.write(name); + buf.write(encodeOct(opts.mode & MASK, 6), 100); + buf.write(encodeOct(opts.uid, 6), 108); + buf.write(encodeOct(opts.gid, 6), 116); + buf.write(encodeOct(opts.size, 11), 124); + buf.write(encodeOct(opts.mtime.getTime() / 1e3 | 0, 11), 136); + buf[156] = ZERO_OFFSET + toTypeflag(opts.type); + if (opts.linkname) buf.write(opts.linkname, 157); + USTAR_MAGIC.copy(buf, MAGIC_OFFSET); + USTAR_VER.copy(buf, VERSION_OFFSET); + if (opts.uname) buf.write(opts.uname, 265); + if (opts.gname) buf.write(opts.gname, 297); + buf.write(encodeOct(opts.devmajor || 0, 6), 329); + buf.write(encodeOct(opts.devminor || 0, 6), 337); + if (prefix) buf.write(prefix, 345); + buf.write(encodeOct(cksum(buf), 6), 148); + return buf; + }; + exports2.decode = function(buf, filenameEncoding, allowUnknownFormat) { + var typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET; + var name = decodeStr(buf, 0, 100, filenameEncoding); + var mode = decodeOct(buf, 100, 8); + var uid = decodeOct(buf, 108, 8); + var gid = decodeOct(buf, 116, 8); + var size = decodeOct(buf, 124, 12); + var mtime = decodeOct(buf, 136, 12); + var type = toType(typeflag); + var linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100, filenameEncoding); + var uname = decodeStr(buf, 265, 32); + var gname = decodeStr(buf, 297, 32); + var devmajor = decodeOct(buf, 329, 8); + var devminor = decodeOct(buf, 337, 8); + var c = cksum(buf); + if (c === 8 * 32) return null; + if (c !== decodeOct(buf, 148, 8)) throw new Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?"); + if (USTAR_MAGIC.compare(buf, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0) { + if (buf[345]) name = decodeStr(buf, 345, 155, filenameEncoding) + "/" + name; + } else if (GNU_MAGIC.compare(buf, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0 && GNU_VER.compare(buf, VERSION_OFFSET, VERSION_OFFSET + 2) === 0) { + } else { + if (!allowUnknownFormat) { + throw new Error("Invalid tar header: unknown format."); + } + } + if (typeflag === 0 && name && name[name.length - 1] === "/") typeflag = 5; + return { + name, + mode, + uid, + gid, + size, + mtime: new Date(1e3 * mtime), + type, + linkname, + uname, + gname, + devmajor, + devminor + }; + }; + } +}); + +// node_modules/tar-fs/node_modules/tar-stream/extract.js +var require_extract = __commonJS({ + "node_modules/tar-fs/node_modules/tar-stream/extract.js"(exports2, module2) { + var util = require("util"); + var bl = require_bl(); + var headers = require_headers2(); + var Writable2 = require_readable2().Writable; + var PassThrough = require_readable2().PassThrough; + var noop3 = function() { + }; + var overflow = function(size) { + size &= 511; + return size && 512 - size; + }; + var emptyStream = function(self2, offset) { + var s = new Source(self2, offset); + s.end(); + return s; + }; + var mixinPax = function(header, pax) { + if (pax.path) header.name = pax.path; + if (pax.linkpath) header.linkname = pax.linkpath; + if (pax.size) header.size = parseInt(pax.size, 10); + header.pax = pax; + return header; + }; + var Source = function(self2, offset) { + this._parent = self2; + this.offset = offset; + PassThrough.call(this, { autoDestroy: false }); + }; + util.inherits(Source, PassThrough); + Source.prototype.destroy = function(err) { + this._parent.destroy(err); + }; + var Extract = function(opts) { + if (!(this instanceof Extract)) return new Extract(opts); + Writable2.call(this, opts); + opts = opts || {}; + this._offset = 0; + this._buffer = bl(); + this._missing = 0; + this._partial = false; + this._onparse = noop3; + this._header = null; + this._stream = null; + this._overflow = null; + this._cb = null; + this._locked = false; + this._destroyed = false; + this._pax = null; + this._paxGlobal = null; + this._gnuLongPath = null; + this._gnuLongLinkPath = null; + var self2 = this; + var b = self2._buffer; + var oncontinue = function() { + self2._continue(); + }; + var onunlock = function(err) { + self2._locked = false; + if (err) return self2.destroy(err); + if (!self2._stream) oncontinue(); + }; + var onstreamend = function() { + self2._stream = null; + var drain = overflow(self2._header.size); + if (drain) self2._parse(drain, ondrain); + else self2._parse(512, onheader); + if (!self2._locked) oncontinue(); + }; + var ondrain = function() { + self2._buffer.consume(overflow(self2._header.size)); + self2._parse(512, onheader); + oncontinue(); + }; + var onpaxglobalheader = function() { + var size = self2._header.size; + self2._paxGlobal = headers.decodePax(b.slice(0, size)); + b.consume(size); + onstreamend(); + }; + var onpaxheader = function() { + var size = self2._header.size; + self2._pax = headers.decodePax(b.slice(0, size)); + if (self2._paxGlobal) self2._pax = Object.assign({}, self2._paxGlobal, self2._pax); + b.consume(size); + onstreamend(); + }; + var ongnulongpath = function() { + var size = self2._header.size; + this._gnuLongPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding); + b.consume(size); + onstreamend(); + }; + var ongnulonglinkpath = function() { + var size = self2._header.size; + this._gnuLongLinkPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding); + b.consume(size); + onstreamend(); + }; + var onheader = function() { + var offset = self2._offset; + var header; + try { + header = self2._header = headers.decode(b.slice(0, 512), opts.filenameEncoding, opts.allowUnknownFormat); + } catch (err) { + self2.emit("error", err); + } + b.consume(512); + if (!header) { + self2._parse(512, onheader); + oncontinue(); + return; + } + if (header.type === "gnu-long-path") { + self2._parse(header.size, ongnulongpath); + oncontinue(); + return; + } + if (header.type === "gnu-long-link-path") { + self2._parse(header.size, ongnulonglinkpath); + oncontinue(); + return; + } + if (header.type === "pax-global-header") { + self2._parse(header.size, onpaxglobalheader); + oncontinue(); + return; + } + if (header.type === "pax-header") { + self2._parse(header.size, onpaxheader); + oncontinue(); + return; + } + if (self2._gnuLongPath) { + header.name = self2._gnuLongPath; + self2._gnuLongPath = null; + } + if (self2._gnuLongLinkPath) { + header.linkname = self2._gnuLongLinkPath; + self2._gnuLongLinkPath = null; + } + if (self2._pax) { + self2._header = header = mixinPax(header, self2._pax); + self2._pax = null; + } + self2._locked = true; + if (!header.size || header.type === "directory") { + self2._parse(512, onheader); + self2.emit("entry", header, emptyStream(self2, offset), onunlock); + return; + } + self2._stream = new Source(self2, offset); + self2.emit("entry", header, self2._stream, onunlock); + self2._parse(header.size, onstreamend); + oncontinue(); + }; + this._onheader = onheader; + this._parse(512, onheader); + }; + util.inherits(Extract, Writable2); + Extract.prototype.destroy = function(err) { + if (this._destroyed) return; + this._destroyed = true; + if (err) this.emit("error", err); + this.emit("close"); + if (this._stream) this._stream.emit("close"); + }; + Extract.prototype._parse = function(size, onparse) { + if (this._destroyed) return; + this._offset += size; + this._missing = size; + if (onparse === this._onheader) this._partial = false; + this._onparse = onparse; + }; + Extract.prototype._continue = function() { + if (this._destroyed) return; + var cb = this._cb; + this._cb = noop3; + if (this._overflow) this._write(this._overflow, void 0, cb); + else cb(); + }; + Extract.prototype._write = function(data, enc, cb) { + if (this._destroyed) return; + var s = this._stream; + var b = this._buffer; + var missing = this._missing; + if (data.length) this._partial = true; + if (data.length < missing) { + this._missing -= data.length; + this._overflow = null; + if (s) return s.write(data, cb); + b.append(data); + return cb(); + } + this._cb = cb; + this._missing = 0; + var overflow2 = null; + if (data.length > missing) { + overflow2 = data.slice(missing); + data = data.slice(0, missing); + } + if (s) s.end(data); + else b.append(data); + this._overflow = overflow2; + this._onparse(); + }; + Extract.prototype._final = function(cb) { + if (this._partial) return this.destroy(new Error("Unexpected end of data")); + cb(); + }; + module2.exports = Extract; + } +}); + +// node_modules/fs-constants/index.js +var require_fs_constants = __commonJS({ + "node_modules/fs-constants/index.js"(exports2, module2) { + module2.exports = require("fs").constants || require("constants"); + } +}); + +// node_modules/wrappy/wrappy.js +var require_wrappy = __commonJS({ + "node_modules/wrappy/wrappy.js"(exports2, module2) { + module2.exports = wrappy; + function wrappy(fn, cb) { + if (fn && cb) return wrappy(fn)(cb); + if (typeof fn !== "function") + throw new TypeError("need wrapper function"); + Object.keys(fn).forEach(function(k) { + wrapper[k] = fn[k]; + }); + return wrapper; + function wrapper() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + var ret = fn.apply(this, args); + var cb2 = args[args.length - 1]; + if (typeof ret === "function" && ret !== cb2) { + Object.keys(cb2).forEach(function(k) { + ret[k] = cb2[k]; + }); + } + return ret; + } + } + } +}); + +// node_modules/once/once.js +var require_once = __commonJS({ + "node_modules/once/once.js"(exports2, module2) { + var wrappy = require_wrappy(); + module2.exports = wrappy(once); + module2.exports.strict = wrappy(onceStrict); + once.proto = once(function() { + Object.defineProperty(Function.prototype, "once", { + value: function() { + return once(this); + }, + configurable: true + }); + Object.defineProperty(Function.prototype, "onceStrict", { + value: function() { + return onceStrict(this); + }, + configurable: true + }); + }); + function once(fn) { + var f = function() { + if (f.called) return f.value; + f.called = true; + return f.value = fn.apply(this, arguments); + }; + f.called = false; + return f; + } + function onceStrict(fn) { + var f = function() { + if (f.called) + throw new Error(f.onceError); + f.called = true; + return f.value = fn.apply(this, arguments); + }; + var name = fn.name || "Function wrapped with `once`"; + f.onceError = name + " shouldn't be called more than once"; + f.called = false; + return f; + } + } +}); + +// node_modules/end-of-stream/index.js +var require_end_of_stream2 = __commonJS({ + "node_modules/end-of-stream/index.js"(exports2, module2) { + var once = require_once(); + var noop3 = function() { + }; + var qnt = global.Bare ? queueMicrotask : process.nextTick.bind(process); + var isRequest = function(stream2) { + return stream2.setHeader && typeof stream2.abort === "function"; + }; + var isChildProcess = function(stream2) { + return stream2.stdio && Array.isArray(stream2.stdio) && stream2.stdio.length === 3; + }; + var eos = function(stream2, opts, callback) { + if (typeof opts === "function") return eos(stream2, null, opts); + if (!opts) opts = {}; + callback = once(callback || noop3); + var ws = stream2._writableState; + var rs = stream2._readableState; + var readable = opts.readable || opts.readable !== false && stream2.readable; + var writable = opts.writable || opts.writable !== false && stream2.writable; + var cancelled = false; + var onlegacyfinish = function() { + if (!stream2.writable) onfinish(); + }; + var onfinish = function() { + writable = false; + if (!readable) callback.call(stream2); + }; + var onend = function() { + readable = false; + if (!writable) callback.call(stream2); + }; + var onexit = function(exitCode) { + callback.call(stream2, exitCode ? new Error("exited with error code: " + exitCode) : null); + }; + var onerror = function(err) { + callback.call(stream2, err); + }; + var onclose = function() { + qnt(onclosenexttick); + }; + var onclosenexttick = function() { + if (cancelled) return; + if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream2, new Error("premature close")); + if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream2, new Error("premature close")); + }; + var onrequest = function() { + stream2.req.on("finish", onfinish); + }; + if (isRequest(stream2)) { + stream2.on("complete", onfinish); + stream2.on("abort", onclose); + if (stream2.req) onrequest(); + else stream2.on("request", onrequest); + } else if (writable && !ws) { + stream2.on("end", onlegacyfinish); + stream2.on("close", onlegacyfinish); + } + if (isChildProcess(stream2)) stream2.on("exit", onexit); + stream2.on("end", onend); + stream2.on("finish", onfinish); + if (opts.error !== false) stream2.on("error", onerror); + stream2.on("close", onclose); + return function() { + cancelled = true; + stream2.removeListener("complete", onfinish); + stream2.removeListener("abort", onclose); + stream2.removeListener("request", onrequest); + if (stream2.req) stream2.req.removeListener("finish", onfinish); + stream2.removeListener("end", onlegacyfinish); + stream2.removeListener("close", onlegacyfinish); + stream2.removeListener("finish", onfinish); + stream2.removeListener("exit", onexit); + stream2.removeListener("end", onend); + stream2.removeListener("error", onerror); + stream2.removeListener("close", onclose); + }; + }; + module2.exports = eos; + } +}); + +// node_modules/tar-fs/node_modules/tar-stream/pack.js +var require_pack = __commonJS({ + "node_modules/tar-fs/node_modules/tar-stream/pack.js"(exports2, module2) { + var constants3 = require_fs_constants(); + var eos = require_end_of_stream2(); + var inherits = require_inherits(); + var alloc = Buffer.alloc; + var Readable2 = require_readable2().Readable; + var Writable2 = require_readable2().Writable; + var StringDecoder = require("string_decoder").StringDecoder; + var headers = require_headers2(); + var DMODE = parseInt("755", 8); + var FMODE = parseInt("644", 8); + var END_OF_TAR = alloc(1024); + var noop3 = function() { + }; + var overflow = function(self2, size) { + size &= 511; + if (size) self2.push(END_OF_TAR.slice(0, 512 - size)); + }; + function modeToType(mode) { + switch (mode & constants3.S_IFMT) { + case constants3.S_IFBLK: + return "block-device"; + case constants3.S_IFCHR: + return "character-device"; + case constants3.S_IFDIR: + return "directory"; + case constants3.S_IFIFO: + return "fifo"; + case constants3.S_IFLNK: + return "symlink"; + } + return "file"; + } + var Sink = function(to) { + Writable2.call(this); + this.written = 0; + this._to = to; + this._destroyed = false; + }; + inherits(Sink, Writable2); + Sink.prototype._write = function(data, enc, cb) { + this.written += data.length; + if (this._to.push(data)) return cb(); + this._to._drain = cb; + }; + Sink.prototype.destroy = function() { + if (this._destroyed) return; + this._destroyed = true; + this.emit("close"); + }; + var LinkSink = function() { + Writable2.call(this); + this.linkname = ""; + this._decoder = new StringDecoder("utf-8"); + this._destroyed = false; + }; + inherits(LinkSink, Writable2); + LinkSink.prototype._write = function(data, enc, cb) { + this.linkname += this._decoder.write(data); + cb(); + }; + LinkSink.prototype.destroy = function() { + if (this._destroyed) return; + this._destroyed = true; + this.emit("close"); + }; + var Void = function() { + Writable2.call(this); + this._destroyed = false; + }; + inherits(Void, Writable2); + Void.prototype._write = function(data, enc, cb) { + cb(new Error("No body allowed for this entry")); + }; + Void.prototype.destroy = function() { + if (this._destroyed) return; + this._destroyed = true; + this.emit("close"); + }; + var Pack = function(opts) { + if (!(this instanceof Pack)) return new Pack(opts); + Readable2.call(this, opts); + this._drain = noop3; + this._finalized = false; + this._finalizing = false; + this._destroyed = false; + this._stream = null; + }; + inherits(Pack, Readable2); + Pack.prototype.entry = function(header, buffer, callback) { + if (this._stream) throw new Error("already piping an entry"); + if (this._finalized || this._destroyed) return; + if (typeof buffer === "function") { + callback = buffer; + buffer = null; + } + if (!callback) callback = noop3; + var self2 = this; + if (!header.size || header.type === "symlink") header.size = 0; + if (!header.type) header.type = modeToType(header.mode); + if (!header.mode) header.mode = header.type === "directory" ? DMODE : FMODE; + if (!header.uid) header.uid = 0; + if (!header.gid) header.gid = 0; + if (!header.mtime) header.mtime = /* @__PURE__ */ new Date(); + if (typeof buffer === "string") buffer = Buffer.from(buffer); + if (Buffer.isBuffer(buffer)) { + header.size = buffer.length; + this._encode(header); + var ok = this.push(buffer); + overflow(self2, header.size); + if (ok) process.nextTick(callback); + else this._drain = callback; + return new Void(); + } + if (header.type === "symlink" && !header.linkname) { + var linkSink = new LinkSink(); + eos(linkSink, function(err) { + if (err) { + self2.destroy(); + return callback(err); + } + header.linkname = linkSink.linkname; + self2._encode(header); + callback(); + }); + return linkSink; + } + this._encode(header); + if (header.type !== "file" && header.type !== "contiguous-file") { + process.nextTick(callback); + return new Void(); + } + var sink = new Sink(this); + this._stream = sink; + eos(sink, function(err) { + self2._stream = null; + if (err) { + self2.destroy(); + return callback(err); + } + if (sink.written !== header.size) { + self2.destroy(); + return callback(new Error("size mismatch")); + } + overflow(self2, header.size); + if (self2._finalizing) self2.finalize(); + callback(); + }); + return sink; + }; + Pack.prototype.finalize = function() { + if (this._stream) { + this._finalizing = true; + return; + } + if (this._finalized) return; + this._finalized = true; + this.push(END_OF_TAR); + this.push(null); + }; + Pack.prototype.destroy = function(err) { + if (this._destroyed) return; + this._destroyed = true; + if (err) this.emit("error", err); + this.emit("close"); + if (this._stream && this._stream.destroy) this._stream.destroy(); + }; + Pack.prototype._encode = function(header) { + if (!header.pax) { + var buf = headers.encode(header); + if (buf) { + this.push(buf); + return; + } + } + this._encodePax(header); + }; + Pack.prototype._encodePax = function(header) { + var paxHeader = headers.encodePax({ + name: header.name, + linkname: header.linkname, + pax: header.pax + }); + var newHeader = { + name: "PaxHeader", + mode: header.mode, + uid: header.uid, + gid: header.gid, + size: paxHeader.length, + mtime: header.mtime, + type: "pax-header", + linkname: header.linkname && "PaxHeader", + uname: header.uname, + gname: header.gname, + devmajor: header.devmajor, + devminor: header.devminor + }; + this.push(headers.encode(newHeader)); + this.push(paxHeader); + overflow(this, paxHeader.length); + newHeader.size = header.size; + newHeader.type = header.type; + this.push(headers.encode(newHeader)); + }; + Pack.prototype._read = function(n) { + var drain = this._drain; + this._drain = noop3; + drain(); + }; + module2.exports = Pack; + } +}); + +// node_modules/tar-fs/node_modules/tar-stream/index.js +var require_tar_stream = __commonJS({ + "node_modules/tar-fs/node_modules/tar-stream/index.js"(exports2) { + exports2.extract = require_extract(); + exports2.pack = require_pack(); + } +}); + +// node_modules/pump/index.js +var require_pump = __commonJS({ + "node_modules/pump/index.js"(exports2, module2) { + var once = require_once(); + var eos = require_end_of_stream2(); + var fs4; + try { + fs4 = require("fs"); + } catch (e) { + } + var noop3 = function() { + }; + var ancient = typeof process === "undefined" ? false : /^v?\.0/.test(process.version); + var isFn = function(fn) { + return typeof fn === "function"; + }; + var isFS = function(stream2) { + if (!ancient) return false; + if (!fs4) return false; + return (stream2 instanceof (fs4.ReadStream || noop3) || stream2 instanceof (fs4.WriteStream || noop3)) && isFn(stream2.close); + }; + var isRequest = function(stream2) { + return stream2.setHeader && isFn(stream2.abort); + }; + var destroyer = function(stream2, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream2.on("close", function() { + closed = true; + }); + eos(stream2, { 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 (isFS(stream2)) return stream2.close(noop3); + if (isRequest(stream2)) return stream2.abort(); + if (isFn(stream2.destroy)) return stream2.destroy(); + callback(err || new Error("stream was destroyed")); + }; + }; + var call = function(fn) { + fn(); + }; + var pipe = function(from, to) { + return from.pipe(to); + }; + var pump = function() { + var streams = Array.prototype.slice.call(arguments); + var callback = isFn(streams[streams.length - 1] || noop3) && streams.pop() || noop3; + if (Array.isArray(streams[0])) streams = streams[0]; + if (streams.length < 2) throw new Error("pump requires two streams per minimum"); + var error2; + var destroys = streams.map(function(stream2, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream2, reading, writing, function(err) { + if (!error2) error2 = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error2); + }); + }); + return streams.reduce(pipe); + }; + module2.exports = pump; + } +}); + +// node_modules/mkdirp-classic/index.js +var require_mkdirp_classic = __commonJS({ + "node_modules/mkdirp-classic/index.js"(exports2, module2) { + var path = require("path"); + var fs4 = require("fs"); + var _0777 = parseInt("0777", 8); + module2.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; + function mkdirP(p, opts, f, made) { + if (typeof opts === "function") { + f = opts; + opts = {}; + } else if (!opts || typeof opts !== "object") { + opts = { mode: opts }; + } + var mode = opts.mode; + var xfs = opts.fs || fs4; + if (mode === void 0) { + mode = _0777 & ~process.umask(); + } + if (!made) made = null; + var cb = f || function() { + }; + p = path.resolve(p); + xfs.mkdir(p, mode, function(er) { + if (!er) { + made = made || p; + return cb(null, made); + } + switch (er.code) { + case "ENOENT": + mkdirP(path.dirname(p), opts, function(er2, made2) { + if (er2) cb(er2, made2); + else mkdirP(p, opts, cb, made2); + }); + break; + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + xfs.stat(p, function(er2, stat2) { + if (er2 || !stat2.isDirectory()) cb(er, made); + else cb(null, made); + }); + break; + } + }); + } + mkdirP.sync = function sync(p, opts, made) { + if (!opts || typeof opts !== "object") { + opts = { mode: opts }; + } + var mode = opts.mode; + var xfs = opts.fs || fs4; + if (mode === void 0) { + mode = _0777 & ~process.umask(); + } + if (!made) made = null; + p = path.resolve(p); + try { + xfs.mkdirSync(p, mode); + made = made || p; + } catch (err0) { + switch (err0.code) { + case "ENOENT": + made = sync(path.dirname(p), opts, made); + sync(p, opts, made); + break; + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + var stat2; + try { + stat2 = xfs.statSync(p); + } catch (err1) { + throw err0; + } + if (!stat2.isDirectory()) throw err0; + break; + } + } + return made; + }; + } +}); + +// node_modules/tar-fs/index.js +var require_tar_fs = __commonJS({ + "node_modules/tar-fs/index.js"(exports2) { + var chownr = require_chownr(); + var tar = require_tar_stream(); + var pump = require_pump(); + var mkdirp = require_mkdirp_classic(); + var fs4 = require("fs"); + var path = require("path"); + var os4 = require("os"); + var win32 = os4.platform() === "win32"; + var noop3 = function() { + }; + var echo = function(name) { + return name; + }; + var normalize = !win32 ? echo : function(name) { + return name.replace(/\\/g, "/").replace(/[:?<>|]/g, "_"); + }; + var statAll = function(fs5, stat2, cwd, ignore, entries, sort) { + var queue = entries || ["."]; + return function loop(callback) { + if (!queue.length) return callback(); + var next = queue.shift(); + var nextAbs = path.join(cwd, next); + stat2.call(fs5, nextAbs, function(err, stat3) { + if (err) return callback(err); + if (!stat3.isDirectory()) return callback(null, next, stat3); + fs5.readdir(nextAbs, function(err2, files) { + if (err2) return callback(err2); + if (sort) files.sort(); + for (var i = 0; i < files.length; i++) { + if (!ignore(path.join(cwd, next, files[i]))) queue.push(path.join(next, files[i])); + } + callback(null, next, stat3); + }); + }); + }; + }; + var strip = function(map, level) { + return function(header) { + header.name = header.name.split("/").slice(level).join("/"); + var linkname = header.linkname; + if (linkname && (header.type === "link" || path.isAbsolute(linkname))) { + header.linkname = linkname.split("/").slice(level).join("/"); + } + return map(header); + }; + }; + exports2.pack = function(cwd, opts) { + if (!cwd) cwd = "."; + if (!opts) opts = {}; + var xfs = opts.fs || fs4; + var ignore = opts.ignore || opts.filter || noop3; + var map = opts.map || noop3; + var mapStream = opts.mapStream || echo; + var statNext = statAll(xfs, opts.dereference ? xfs.stat : xfs.lstat, cwd, ignore, opts.entries, opts.sort); + var strict = opts.strict !== false; + var umask = typeof opts.umask === "number" ? ~opts.umask : ~processUmask(); + var dmode = typeof opts.dmode === "number" ? opts.dmode : 0; + var fmode = typeof opts.fmode === "number" ? opts.fmode : 0; + var pack2 = opts.pack || tar.pack(); + var finish = opts.finish || noop3; + if (opts.strip) map = strip(map, opts.strip); + if (opts.readable) { + dmode |= parseInt(555, 8); + fmode |= parseInt(444, 8); + } + if (opts.writable) { + dmode |= parseInt(333, 8); + fmode |= parseInt(222, 8); + } + var onsymlink = function(filename, header) { + xfs.readlink(path.join(cwd, filename), function(err, linkname) { + if (err) return pack2.destroy(err); + header.linkname = normalize(linkname); + pack2.entry(header, onnextentry); + }); + }; + var onstat = function(err, filename, stat2) { + if (err) return pack2.destroy(err); + if (!filename) { + if (opts.finalize !== false) pack2.finalize(); + return finish(pack2); + } + if (stat2.isSocket()) return onnextentry(); + var header = { + name: normalize(filename), + mode: (stat2.mode | (stat2.isDirectory() ? dmode : fmode)) & umask, + mtime: stat2.mtime, + size: stat2.size, + type: "file", + uid: stat2.uid, + gid: stat2.gid + }; + if (stat2.isDirectory()) { + header.size = 0; + header.type = "directory"; + header = map(header) || header; + return pack2.entry(header, onnextentry); + } + if (stat2.isSymbolicLink()) { + header.size = 0; + header.type = "symlink"; + header = map(header) || header; + return onsymlink(filename, header); + } + header = map(header) || header; + if (!stat2.isFile()) { + if (strict) return pack2.destroy(new Error("unsupported type for " + filename)); + return onnextentry(); + } + var entry = pack2.entry(header, onnextentry); + if (!entry) return; + var rs = mapStream(xfs.createReadStream(path.join(cwd, filename), { start: 0, end: header.size > 0 ? header.size - 1 : header.size }), header); + rs.on("error", function(err2) { + entry.destroy(err2); + }); + pump(rs, entry); + }; + var onnextentry = function(err) { + if (err) return pack2.destroy(err); + statNext(onstat); + }; + onnextentry(); + return pack2; + }; + var head = function(list) { + return list.length ? list[list.length - 1] : null; + }; + var processGetuid = function() { + return process.getuid ? process.getuid() : -1; + }; + var processUmask = function() { + return process.umask ? process.umask() : 0; + }; + exports2.extract = function(cwd, opts) { + if (!cwd) cwd = "."; + if (!opts) opts = {}; + var xfs = opts.fs || fs4; + var ignore = opts.ignore || opts.filter || noop3; + var map = opts.map || noop3; + var mapStream = opts.mapStream || echo; + var own = opts.chown !== false && !win32 && processGetuid() === 0; + var extract2 = opts.extract || tar.extract(); + var stack = []; + var now = /* @__PURE__ */ new Date(); + var umask = typeof opts.umask === "number" ? ~opts.umask : ~processUmask(); + var dmode = typeof opts.dmode === "number" ? opts.dmode : 0; + var fmode = typeof opts.fmode === "number" ? opts.fmode : 0; + var strict = opts.strict !== false; + if (opts.strip) map = strip(map, opts.strip); + if (opts.readable) { + dmode |= parseInt(555, 8); + fmode |= parseInt(444, 8); + } + if (opts.writable) { + dmode |= parseInt(333, 8); + fmode |= parseInt(222, 8); + } + var utimesParent = function(name, cb) { + var top; + while ((top = head(stack)) && name.slice(0, top[0].length) !== top[0]) stack.pop(); + if (!top) return cb(); + xfs.utimes(top[0], now, top[1], cb); + }; + var utimes = function(name, header, cb) { + if (opts.utimes === false) return cb(); + if (header.type === "directory") return xfs.utimes(name, now, header.mtime, cb); + if (header.type === "symlink") return utimesParent(name, cb); + xfs.utimes(name, now, header.mtime, function(err) { + if (err) return cb(err); + utimesParent(name, cb); + }); + }; + var chperm = function(name, header, cb) { + var link = header.type === "symlink"; + var chmod2 = link ? xfs.lchmod : xfs.chmod; + var chown = link ? xfs.lchown : xfs.chown; + if (!chmod2) return cb(); + var mode = (header.mode | (header.type === "directory" ? dmode : fmode)) & umask; + if (chown && own) chown.call(xfs, name, header.uid, header.gid, onchown); + else onchown(null); + function onchown(err) { + if (err) return cb(err); + if (!chmod2) return cb(); + chmod2.call(xfs, name, mode, cb); + } + }; + extract2.on("entry", function(header, stream2, next) { + header = map(header) || header; + header.name = normalize(header.name); + var name = path.join(cwd, path.join("/", header.name)); + if (ignore(name, header)) { + stream2.resume(); + return next(); + } + var stat2 = function(err) { + if (err) return next(err); + utimes(name, header, function(err2) { + if (err2) return next(err2); + if (win32) return next(); + chperm(name, header, next); + }); + }; + var onsymlink = function() { + if (win32) return next(); + xfs.unlink(name, function() { + var dst = path.resolve(path.dirname(name), header.linkname); + if (!inCwd(dst, cwd)) return next(new Error(name + " is not a valid symlink")); + xfs.symlink(header.linkname, name, stat2); + }); + }; + var onlink = function() { + if (win32) return next(); + xfs.unlink(name, function() { + var srcpath = path.join(cwd, path.join("/", header.linkname)); + xfs.realpath(srcpath, function(err, dst) { + if (err || !inCwd(dst, cwd)) return next(new Error(name + " is not a valid hardlink")); + xfs.link(dst, name, function(err2) { + if (err2 && err2.code === "EPERM" && opts.hardlinkAsFilesFallback) { + stream2 = xfs.createReadStream(srcpath); + return onfile(); + } + stat2(err2); + }); + }); + }); + }; + var onfile = function() { + var ws = xfs.createWriteStream(name); + var rs = mapStream(stream2, header); + ws.on("error", function(err) { + rs.destroy(err); + }); + pump(rs, ws, function(err) { + if (err) return next(err); + ws.on("close", stat2); + }); + }; + if (header.type === "directory") { + stack.push([name, header.mtime]); + return mkdirfix(name, { + fs: xfs, + own, + uid: header.uid, + gid: header.gid + }, stat2); + } + var dir = path.dirname(name); + validate(xfs, dir, path.join(cwd, "."), function(err, valid) { + if (err) return next(err); + if (!valid) return next(new Error(dir + " is not a valid path")); + mkdirfix(dir, { + fs: xfs, + own, + uid: header.uid, + gid: header.gid + }, function(err2) { + if (err2) return next(err2); + switch (header.type) { + case "file": + return onfile(); + case "link": + return onlink(); + case "symlink": + return onsymlink(); + } + if (strict) return next(new Error("unsupported type for " + name + " (" + header.type + ")")); + stream2.resume(); + next(); + }); + }); + }); + if (opts.finish) extract2.on("finish", opts.finish); + return extract2; + }; + function validate(fs5, name, root, cb) { + if (name === root) return cb(null, true); + fs5.lstat(name, function(err, st) { + if (err && err.code !== "ENOENT") return cb(err); + if (err || st.isDirectory()) return validate(fs5, path.join(name, ".."), root, cb); + cb(null, false); + }); + } + function mkdirfix(name, opts, cb) { + mkdirp(name, { fs: opts.fs }, function(err, made) { + if (!err && made && opts.own) { + chownr(made, opts.uid, opts.gid, cb); + } else { + cb(err); + } + }); + } + function inCwd(dst, cwd) { + cwd = path.resolve(cwd); + return cwd === dst || dst.startsWith(cwd + path.sep); + } + } +}); + +// node_modules/dockerode/lib/util.js +var require_util9 = __commonJS({ + "node_modules/dockerode/lib/util.js"(exports2, module2) { + var DockerIgnore = require_ignore(); + var fs4 = require("fs"); + var path = require("path"); + var tar = require_tar_fs(); + var zlib = require("zlib"); + var arr = []; + var each = arr.forEach; + var slice = arr.slice; + module2.exports.extend = function(obj) { + each.call(slice.call(arguments, 1), function(source) { + if (source) { + for (var prop in source) { + obj[prop] = source[prop]; + } + } + }); + return obj; + }; + module2.exports.processArgs = function(opts, callback, defaultOpts) { + if (!callback && typeof opts === "function") { + callback = opts; + opts = null; + } + return { + callback, + opts: module2.exports.extend({}, defaultOpts, opts) + }; + }; + module2.exports.parseRepositoryTag = function(input) { + var separatorPos; + var digestPos = input.indexOf("@"); + var colonPos = input.lastIndexOf(":"); + if (digestPos >= 0) { + separatorPos = digestPos; + } else if (colonPos >= 0) { + separatorPos = colonPos; + } else { + return { + repository: input + }; + } + var tag = input.slice(separatorPos + 1); + if (tag.indexOf("/") === -1) { + return { + repository: input.slice(0, separatorPos), + tag + }; + } + return { + repository: input + }; + }; + module2.exports.prepareBuildContext = function(file, next) { + if (file && file.context) { + fs4.readFile(path.join(file.context, ".dockerignore"), (err, data) => { + let ignoreFn; + let filterFn; + if (!err) { + const dockerIgnore = DockerIgnore({ ignorecase: false }).add(data.toString()); + filterFn = dockerIgnore.createFilter(); + ignoreFn = (path2) => { + return !filterFn(path2); + }; + } + const entries = file.src.slice() || []; + const pack2 = tar.pack(file.context, { + entries: filterFn ? entries.filter(filterFn) : entries, + ignore: ignoreFn + // Only works on directories + }); + next(pack2.pipe(zlib.createGzip())); + }); + } else { + next(file); + } + }; + } +}); + +// node_modules/dockerode/lib/exec.js +var require_exec = __commonJS({ + "node_modules/dockerode/lib/exec.js"(exports2, module2) { + var util = require_util9(); + var Exec = function(modem, id) { + this.modem = modem; + this.id = id; + }; + Exec.prototype[require("util").inspect.custom] = function() { + return this; + }; + Exec.prototype.start = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/exec/" + this.id + "/start", + method: "POST", + abortSignal: args.opts.abortSignal, + isStream: true, + allowEmpty: true, + hijack: args.opts.hijack, + openStdin: args.opts.stdin, + statusCodes: { + 200: true, + 204: true, + 404: "no such exec", + 409: "container stopped/paused", + 500: "container not running" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, data); + }); + } + }; + Exec.prototype.resize = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/exec/" + this.id + "/resize?", + method: "POST", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: "no such exec", + 500: "container not running" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, data); + }); + } + }; + Exec.prototype.inspect = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/exec/" + this.id + "/json", + method: "GET", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: "no such exec", + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, data); + }); + } + }; + module2.exports = Exec; + } +}); + +// node_modules/dockerode/lib/container.js +var require_container = __commonJS({ + "node_modules/dockerode/lib/container.js"(exports2, module2) { + var extend = require_util9().extend; + var Exec = require_exec(); + var util = require_util9(); + var Container2 = function(modem, id) { + this.modem = modem; + this.id = id; + this.defaultOptions = { + top: {}, + start: {}, + commit: {}, + stop: {}, + pause: {}, + unpause: {}, + restart: {}, + resize: {}, + attach: {}, + remove: {}, + copy: {}, + kill: {}, + exec: {}, + rename: {}, + log: {}, + stats: {}, + getArchive: {}, + infoArchive: {}, + putArchive: {}, + update: {}, + wait: {} + }; + }; + Container2.prototype[require("util").inspect.custom] = function() { + return this; + }; + Container2.prototype.inspect = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/containers/" + this.id + "/json?", + method: "GET", + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: "no such container", + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Container2.prototype.rename = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback, this.defaultOptions.rename); + var optsf = { + path: "/containers/" + this.id + "/rename?", + method: "POST", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 204: true, + 404: "no such container", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Container2.prototype.update = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback, this.defaultOptions.update); + var optsf = { + path: "/containers/" + this.id + "/update", + method: "POST", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 204: true, + 400: "bad parameter", + 404: "no such container", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Container2.prototype.top = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback, this.defaultOptions.top); + var optsf = { + path: "/containers/" + this.id + "/top?", + method: "GET", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: "no such container", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Container2.prototype.changes = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/containers/" + this.id + "/changes", + method: "GET", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: "no such container", + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Container2.prototype.listCheckpoint = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/containers/" + this.id + "/checkpoints?", + method: "GET", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: "no such container", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Container2.prototype.deleteCheckpoint = function(checkpoint, opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/containers/" + this.id + "/checkpoints/" + checkpoint + "?", + method: "DELETE", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + // unofficial, but proxies may return it + 204: true, + 404: "no such container", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Container2.prototype.createCheckpoint = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/containers/" + this.id + "/checkpoints", + method: "POST", + abortSignal: args.opts.abortSignal, + allowEmpty: true, + statusCodes: { + 200: true, + //unofficial, but proxies may return it + 201: true, + 204: true, + 404: "no such container", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Container2.prototype.export = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/containers/" + this.id + "/export", + method: "GET", + abortSignal: args.opts.abortSignal, + isStream: true, + statusCodes: { + 200: true, + 404: "no such container", + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Container2.prototype.start = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback, this.defaultOptions.start); + var optsf = { + path: "/containers/" + this.id + "/start?", + method: "POST", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + // unofficial, but proxies may return it + 204: true, + 304: "container already started", + 404: "no such container", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Container2.prototype.pause = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback, this.defaultOptions.pause); + var optsf = { + path: "/containers/" + this.id + "/pause", + method: "POST", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + // unofficial, but proxies may return it + 204: true, + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Container2.prototype.unpause = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback, this.defaultOptions.unpause); + var optsf = { + path: "/containers/" + this.id + "/unpause", + method: "POST", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + // unofficial, but proxies may return it + 204: true, + 404: "no such container", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Container2.prototype.exec = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback, this.defaultOptions.exec); + var optsf = { + path: "/containers/" + this.id + "/exec", + method: "POST", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + // unofficial, but proxies may return it + 201: true, + 404: "no such container", + 409: "container stopped/paused", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(new Exec(self2.modem, data.Id)); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, new Exec(self2.modem, data.Id)); + }); + } + }; + Container2.prototype.commit = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback, this.defaultOptions.commit); + args.opts.container = this.id; + var optsf = { + path: "/commit?", + method: "POST", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + // unofficial, but proxies may return it + 201: true, + 404: "no such container", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Container2.prototype.stop = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback, this.defaultOptions.stop); + var optsf = { + path: "/containers/" + this.id + "/stop?", + method: "POST", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + // unofficial, but proxies may return it + 204: true, + 304: "container already stopped", + 404: "no such container", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Container2.prototype.restart = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback, this.defaultOptions.restart); + var optsf = { + path: "/containers/" + this.id + "/restart?", + method: "POST", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + // unofficial, but proxies may return it + 204: true, + 404: "no such container", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Container2.prototype.kill = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback, this.defaultOptions.kill); + var optsf = { + path: "/containers/" + this.id + "/kill?", + method: "POST", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + // unofficial, but proxies may return it + 204: true, + 404: "no such container", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Container2.prototype.resize = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback, this.defaultOptions.resize); + var optsf = { + path: "/containers/" + this.id + "/resize?", + method: "POST", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: "bad parameter", + 404: "no such container", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Container2.prototype.attach = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback, this.defaultOptions.attach); + var optsf = { + path: "/containers/" + this.id + "/attach?", + method: "POST", + abortSignal: args.opts.abortSignal, + isStream: true, + hijack: args.opts.hijack, + openStdin: args.opts.stdin, + statusCodes: { + 200: true, + 404: "no such container", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, stream2) { + if (err) { + return reject(err); + } + resolve(stream2); + }); + }); + } else { + this.modem.dial(optsf, function(err, stream2) { + args.callback(err, stream2); + }); + } + }; + Container2.prototype.wait = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback, this.defaultOptions.wait); + var optsf = { + path: "/containers/" + this.id + "/wait?", + method: "POST", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: "bad parameter", + 404: "no such container", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Container2.prototype.remove = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback, this.defaultOptions.remove); + var optsf = { + path: "/containers/" + this.id + "?", + method: "DELETE", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + // unofficial, but proxies may return it + 204: true, + 400: "bad parameter", + 404: "no such container", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Container2.prototype.copy = function(opts, callback) { + var self2 = this; + console.log("container.copy is deprecated since Docker v1.8.x"); + var args = util.processArgs(opts, callback, this.defaultOptions.copy); + var optsf = { + path: "/containers/" + this.id + "/copy", + method: "POST", + abortSignal: args.opts.abortSignal, + isStream: true, + statusCodes: { + 200: true, + 404: "no such container", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Container2.prototype.getArchive = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback, this.defaultOptions.getArchive); + var optsf = { + path: "/containers/" + this.id + "/archive?", + method: "GET", + abortSignal: args.opts.abortSignal, + isStream: true, + statusCodes: { + 200: true, + 400: "client error, bad parameters", + 404: "no such container", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Container2.prototype.infoArchive = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback, this.defaultOptions.infoArchive); + var optsf = { + path: "/containers/" + this.id + "/archive?", + method: "HEAD", + abortSignal: args.opts.abortSignal, + isStream: true, + statusCodes: { + 200: true, + 400: "client error, bad parameters", + 404: "no such container", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Container2.prototype.putArchive = function(file, opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback, this.defaultOptions.putArchive); + var optsf = { + path: "/containers/" + this.id + "/archive?", + method: "PUT", + file, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: "client error, bad parameters", + 403: "client error, permission denied", + 404: "no such container", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Container2.prototype.logs = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback, this.defaultOptions.log); + var optsf = { + path: "/containers/" + this.id + "/logs?", + method: "GET", + abortSignal: args.opts.abortSignal, + isStream: args.opts.follow || false, + statusCodes: { + 200: true, + 404: "no such container", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Container2.prototype.stats = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback, this.defaultOptions.stats); + var isStream = true; + if (args.opts.stream === false) { + isStream = false; + } + var optsf = { + path: "/containers/" + this.id + "/stats?", + method: "GET", + abortSignal: args.opts.abortSignal, + isStream, + statusCodes: { + 200: true, + 404: "no such container", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + module2.exports = Container2; + } +}); + +// node_modules/dockerode/lib/image.js +var require_image = __commonJS({ + "node_modules/dockerode/lib/image.js"(exports2, module2) { + var util = require_util9(); + var Image = function(modem, name) { + this.modem = modem; + this.name = name; + }; + Image.prototype[require("util").inspect.custom] = function() { + return this; + }; + Image.prototype.inspect = function(opts, callback) { + var args = util.processArgs(opts, callback); + var self2 = this; + var opts = { + path: "/images/" + this.name + "/json", + method: "GET", + options: args.opts, + statusCodes: { + 200: true, + 404: "no such image", + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(opts, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(opts, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, data); + }); + } + }; + Image.prototype.distribution = function(opts, callback) { + var args = util.processArgs(opts, callback); + var self2 = this; + var fopts = { + path: "/distribution/" + this.name + "/json", + method: "GET", + statusCodes: { + 200: true, + 401: "no such image", + 500: "server error" + }, + authconfig: args.opts ? args.opts.authconfig : void 0 + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(fopts, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(fopts, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, data); + }); + } + }; + Image.prototype.history = function(callback) { + var self2 = this; + var opts = { + path: "/images/" + this.name + "/history", + method: "GET", + statusCodes: { + 200: true, + 404: "no such image", + 500: "server error" + } + }; + if (callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(opts, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(opts, function(err, data) { + if (err) return callback(err, data); + callback(err, data); + }); + } + }; + Image.prototype.get = function(callback) { + var self2 = this; + var opts = { + path: "/images/" + this.name + "/get", + method: "GET", + isStream: true, + statusCodes: { + 200: true, + 500: "server error" + } + }; + if (callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(opts, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(opts, function(err, data) { + if (err) return callback(err, data); + callback(err, data); + }); + } + }; + Image.prototype.push = function(opts, callback, auth2) { + var self2 = this; + var args = util.processArgs(opts, callback); + var isStream = true; + if (args.opts.stream === false) { + isStream = false; + } + var optsf = { + path: "/images/" + this.name + "/push?", + method: "POST", + options: args.opts, + authconfig: args.opts.authconfig || auth2, + abortSignal: args.opts.abortSignal, + isStream, + statusCodes: { + 200: true, + 404: "no such image", + 500: "server error" + } + }; + delete optsf.options.authconfig; + if (callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } + }; + Image.prototype.tag = function(opts, callback) { + var self2 = this; + var optsf = { + path: "/images/" + this.name + "/tag?", + method: "POST", + options: opts, + abortSignal: opts && opts.abortSignal, + statusCodes: { + 200: true, + // unofficial, but proxies may return it + 201: true, + 400: "bad parameter", + 404: "no such image", + 409: "conflict", + 500: "server error" + } + }; + if (callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } + }; + Image.prototype.remove = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/images/" + this.name + "?", + method: "DELETE", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: "no such image", + 409: "conflict", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + module2.exports = Image; + } +}); + +// node_modules/dockerode/lib/volume.js +var require_volume = __commonJS({ + "node_modules/dockerode/lib/volume.js"(exports2, module2) { + var util = require_util9(); + var Volume = function(modem, name) { + this.modem = modem; + this.name = name; + }; + Volume.prototype[require("util").inspect.custom] = function() { + return this; + }; + Volume.prototype.inspect = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/volumes/" + this.name, + method: "GET", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: "no such volume", + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Volume.prototype.remove = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/volumes/" + this.name, + method: "DELETE", + abortSignal: args.opts.abortSignal, + statusCodes: { + 204: true, + 404: "no such volume", + 409: "conflict", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + module2.exports = Volume; + } +}); + +// node_modules/dockerode/lib/network.js +var require_network = __commonJS({ + "node_modules/dockerode/lib/network.js"(exports2, module2) { + var util = require_util9(); + var Network = function(modem, id) { + this.modem = modem; + this.id = id; + }; + Network.prototype[require("util").inspect.custom] = function() { + return this; + }; + Network.prototype.inspect = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var opts = { + path: "/networks/" + this.id + "?", + method: "GET", + statusCodes: { + 200: true, + 404: "no such network", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(opts, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(opts, function(err, data) { + args.callback(err, data); + }); + } + }; + Network.prototype.remove = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/networks/" + this.id, + method: "DELETE", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 204: true, + 404: "no such network", + 409: "conflict", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Network.prototype.connect = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/networks/" + this.id + "/connect", + method: "POST", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 201: true, + 404: "network or container is not found", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Network.prototype.disconnect = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/networks/" + this.id + "/disconnect", + method: "POST", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 201: true, + 404: "network or container is not found", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + module2.exports = Network; + } +}); + +// node_modules/dockerode/lib/service.js +var require_service = __commonJS({ + "node_modules/dockerode/lib/service.js"(exports2, module2) { + var util = require_util9(); + var Service = function(modem, id) { + this.modem = modem; + this.id = id; + }; + Service.prototype[require("util").inspect.custom] = function() { + return this; + }; + Service.prototype.inspect = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/services/" + this.id, + method: "GET", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: "no such service", + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Service.prototype.remove = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/services/" + this.id, + method: "DELETE", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 204: true, + 404: "no such service", + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Service.prototype.update = function(auth2, opts, callback) { + var self2 = this; + if (!callback) { + var t = typeof opts; + if (t === "function") { + callback = opts; + opts = auth2; + auth2 = opts.authconfig || void 0; + } else if (t === "undefined") { + opts = auth2; + auth2 = opts.authconfig || void 0; + } + } + var optsf = { + path: "/services/" + this.id + "/update?", + method: "POST", + abortSignal: opts && opts.abortSignal, + statusCodes: { + 200: true, + 404: "no such service", + 500: "server error" + }, + authconfig: auth2, + options: opts + }; + if (callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } + }; + Service.prototype.logs = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback, {}); + var optsf = { + path: "/services/" + this.id + "/logs?", + method: "GET", + abortSignal: args.opts.abortSignal, + isStream: args.opts.follow || false, + statusCodes: { + 200: true, + 404: "no such service", + 500: "server error", + 503: "node is not part of a swarm" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + module2.exports = Service; + } +}); + +// node_modules/dockerode/lib/plugin.js +var require_plugin = __commonJS({ + "node_modules/dockerode/lib/plugin.js"(exports2, module2) { + var util = require_util9(); + var Plugin = function(modem, name, remote) { + this.modem = modem; + this.name = name; + this.remote = remote || name; + }; + Plugin.prototype[require("util").inspect.custom] = function() { + return this; + }; + Plugin.prototype.inspect = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/plugins/" + this.name + "/json", + method: "GET", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: "plugin is not installed", + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Plugin.prototype.remove = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/plugins/" + this.name + "?", + method: "DELETE", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: "plugin is not installed", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, data); + }); + } + }; + Plugin.prototype.privileges = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/plugins/privileges?", + method: "GET", + options: { + "remote": this.remote + }, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Plugin.prototype.pull = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + if (args.opts._query && !args.opts._query.name) { + args.opts._query.name = this.name; + } + if (args.opts._query && !args.opts._query.remote) { + args.opts._query.remote = this.remote; + } + var optsf = { + path: "/plugins/pull?", + method: "POST", + abortSignal: args.opts.abortSignal, + isStream: true, + options: args.opts, + statusCodes: { + 200: true, + // unofficial, but proxies may return it + 204: true, + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Plugin.prototype.enable = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/plugins/" + this.name + "/enable?", + method: "POST", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Plugin.prototype.disable = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/plugins/" + this.name + "/disable", + method: "POST", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Plugin.prototype.push = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/plugins/" + this.name + "/push", + method: "POST", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: "plugin not installed", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Plugin.prototype.configure = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/plugins/" + this.name + "/set", + method: "POST", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 204: true, + 404: "plugin not installed", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Plugin.prototype.upgrade = function(auth2, opts, callback) { + var self2 = this; + if (!callback && typeof opts === "function") { + callback = opts; + opts = auth2; + auth2 = opts.authconfig || void 0; + } + var optsf = { + path: "/plugins/" + this.name + "/upgrade?", + method: "POST", + abortSignal: opts && opts.abortSignal, + statusCodes: { + 200: true, + 204: true, + 404: "plugin not installed", + 500: "server error" + }, + authconfig: auth2, + options: opts + }; + if (callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } + }; + module2.exports = Plugin; + } +}); + +// node_modules/dockerode/lib/secret.js +var require_secret = __commonJS({ + "node_modules/dockerode/lib/secret.js"(exports2, module2) { + var util = require_util9(); + var Secret = function(modem, id) { + this.modem = modem; + this.id = id; + }; + Secret.prototype[require("util").inspect.custom] = function() { + return this; + }; + Secret.prototype.inspect = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/secrets/" + this.id, + method: "GET", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: "secret not found", + 406: "node is not part of a swarm", + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Secret.prototype.update = function(opts, callback) { + var self2 = this; + if (!callback && typeof opts === "function") { + callback = opts; + } + var optsf = { + path: "/secrets/" + this.id + "/update?", + method: "POST", + abortSignal: opts && opts.abortSignal, + statusCodes: { + 200: true, + 404: "secret not found", + 500: "server error" + }, + options: opts + }; + if (callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } + }; + Secret.prototype.remove = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/secrets/" + this.id, + method: "DELETE", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 204: true, + 404: "secret not found", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + module2.exports = Secret; + } +}); + +// node_modules/dockerode/lib/config.js +var require_config = __commonJS({ + "node_modules/dockerode/lib/config.js"(exports2, module2) { + var util = require_util9(); + var Config = function(modem, id) { + this.modem = modem; + this.id = id; + }; + Config.prototype[require("util").inspect.custom] = function() { + return this; + }; + Config.prototype.inspect = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/configs/" + this.id, + method: "GET", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: "config not found", + 500: "server error", + 503: "node is not part of a swarm" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Config.prototype.update = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/configs/" + this.id + "/update?", + method: "POST", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: "config not found", + 500: "server error", + 503: "node is not part of a swarm" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Config.prototype.remove = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/configs/" + this.id, + method: "DELETE", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 204: true, + 404: "config not found", + 500: "server error", + 503: "node is not part of a swarm" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + module2.exports = Config; + } +}); + +// node_modules/dockerode/lib/task.js +var require_task = __commonJS({ + "node_modules/dockerode/lib/task.js"(exports2, module2) { + var util = require_util9(); + var Task = function(modem, id) { + this.modem = modem; + this.id = id; + this.defaultOptions = { + log: {} + }; + }; + Task.prototype[require("util").inspect.custom] = function() { + return this; + }; + Task.prototype.inspect = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/tasks/" + this.id, + method: "GET", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: "unknown task", + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Task.prototype.logs = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback, this.defaultOptions.log); + var optsf = { + path: "/tasks/" + this.id + "/logs?", + method: "GET", + abortSignal: args.opts.abortSignal, + isStream: args.opts.follow || false, + statusCodes: { + 101: true, + 200: true, + 404: "no such container", + 500: "server error", + 503: "node is not part of a swarm" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + module2.exports = Task; + } +}); + +// node_modules/dockerode/lib/node.js +var require_node3 = __commonJS({ + "node_modules/dockerode/lib/node.js"(exports2, module2) { + var util = require_util9(); + var Node = function(modem, id) { + this.modem = modem; + this.id = id; + }; + Node.prototype[require("util").inspect.custom] = function() { + return this; + }; + Node.prototype.inspect = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/nodes/" + this.id, + method: "GET", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: "no such node", + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Node.prototype.update = function(opts, callback) { + var self2 = this; + if (!callback && typeof opts === "function") { + callback = opts; + } + var optsf = { + path: "/nodes/" + this.id + "/update?", + method: "POST", + abortSignal: opts && opts.abortSignal, + statusCodes: { + 200: true, + 404: "no such node", + 406: "node is not part of a swarm", + 500: "server error" + }, + options: opts + }; + if (callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } + }; + Node.prototype.remove = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/nodes/" + this.id + "?", + method: "DELETE", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 404: "no such node", + 500: "server error" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + module2.exports = Node; + } +}); + +// node_modules/@grpc/grpc-js/build/src/constants.js +var require_constants7 = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/constants.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH = exports2.DEFAULT_MAX_SEND_MESSAGE_LENGTH = exports2.Propagate = exports2.LogVerbosity = exports2.Status = void 0; + var Status; + (function(Status2) { + Status2[Status2["OK"] = 0] = "OK"; + Status2[Status2["CANCELLED"] = 1] = "CANCELLED"; + Status2[Status2["UNKNOWN"] = 2] = "UNKNOWN"; + Status2[Status2["INVALID_ARGUMENT"] = 3] = "INVALID_ARGUMENT"; + Status2[Status2["DEADLINE_EXCEEDED"] = 4] = "DEADLINE_EXCEEDED"; + Status2[Status2["NOT_FOUND"] = 5] = "NOT_FOUND"; + Status2[Status2["ALREADY_EXISTS"] = 6] = "ALREADY_EXISTS"; + Status2[Status2["PERMISSION_DENIED"] = 7] = "PERMISSION_DENIED"; + Status2[Status2["RESOURCE_EXHAUSTED"] = 8] = "RESOURCE_EXHAUSTED"; + Status2[Status2["FAILED_PRECONDITION"] = 9] = "FAILED_PRECONDITION"; + Status2[Status2["ABORTED"] = 10] = "ABORTED"; + Status2[Status2["OUT_OF_RANGE"] = 11] = "OUT_OF_RANGE"; + Status2[Status2["UNIMPLEMENTED"] = 12] = "UNIMPLEMENTED"; + Status2[Status2["INTERNAL"] = 13] = "INTERNAL"; + Status2[Status2["UNAVAILABLE"] = 14] = "UNAVAILABLE"; + Status2[Status2["DATA_LOSS"] = 15] = "DATA_LOSS"; + Status2[Status2["UNAUTHENTICATED"] = 16] = "UNAUTHENTICATED"; + })(Status || (exports2.Status = Status = {})); + var LogVerbosity; + (function(LogVerbosity2) { + LogVerbosity2[LogVerbosity2["DEBUG"] = 0] = "DEBUG"; + LogVerbosity2[LogVerbosity2["INFO"] = 1] = "INFO"; + LogVerbosity2[LogVerbosity2["ERROR"] = 2] = "ERROR"; + LogVerbosity2[LogVerbosity2["NONE"] = 3] = "NONE"; + })(LogVerbosity || (exports2.LogVerbosity = LogVerbosity = {})); + var Propagate; + (function(Propagate2) { + Propagate2[Propagate2["DEADLINE"] = 1] = "DEADLINE"; + Propagate2[Propagate2["CENSUS_STATS_CONTEXT"] = 2] = "CENSUS_STATS_CONTEXT"; + Propagate2[Propagate2["CENSUS_TRACING_CONTEXT"] = 4] = "CENSUS_TRACING_CONTEXT"; + Propagate2[Propagate2["CANCELLATION"] = 8] = "CANCELLATION"; + Propagate2[Propagate2["DEFAULTS"] = 65535] = "DEFAULTS"; + })(Propagate || (exports2.Propagate = Propagate = {})); + exports2.DEFAULT_MAX_SEND_MESSAGE_LENGTH = -1; + exports2.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH = 4 * 1024 * 1024; + } +}); + +// node_modules/@grpc/grpc-js/package.json +var require_package2 = __commonJS({ + "node_modules/@grpc/grpc-js/package.json"(exports2, module2) { + module2.exports = { + name: "@grpc/grpc-js", + version: "1.14.4", + description: "gRPC Library for Node - pure JS implementation", + homepage: "https://grpc.io/", + repository: "https://github.com/grpc/grpc-node/tree/master/packages/grpc-js", + main: "build/src/index.js", + engines: { + node: ">=12.10.0" + }, + keywords: [], + author: { + name: "Google Inc." + }, + types: "build/src/index.d.ts", + license: "Apache-2.0", + devDependencies: { + "@grpc/proto-loader": "file:../proto-loader", + "@types/gulp": "^4.0.17", + "@types/gulp-mocha": "0.0.37", + "@types/lodash": "^4.14.202", + "@types/mocha": "^10.0.6", + "@types/ncp": "^2.0.8", + "@types/node": ">=20.11.20", + "@types/pify": "^5.0.4", + "@types/semver": "^7.5.8", + "@typescript-eslint/eslint-plugin": "^7.1.0", + "@typescript-eslint/parser": "^7.1.0", + "@typescript-eslint/typescript-estree": "^7.1.0", + "clang-format": "^1.8.0", + eslint: "^8.42.0", + "eslint-config-prettier": "^8.8.0", + "eslint-plugin-node": "^11.1.0", + "eslint-plugin-prettier": "^4.2.1", + execa: "^2.0.3", + gulp: "^4.0.2", + "gulp-mocha": "^6.0.0", + lodash: "^4.17.21", + madge: "^5.0.1", + "mocha-jenkins-reporter": "^0.4.1", + ncp: "^2.0.0", + pify: "^4.0.1", + prettier: "^2.8.8", + rimraf: "^3.0.2", + semver: "^7.6.0", + "ts-node": "^10.9.2", + typescript: "^5.3.3" + }, + contributors: [ + { + name: "Google Inc." + } + ], + scripts: { + build: "npm run compile", + clean: "rimraf ./build", + compile: "tsc -p .", + format: 'clang-format -i -style="{Language: JavaScript, BasedOnStyle: Google, ColumnLimit: 80}" src/*.ts test/*.ts', + lint: "eslint src/*.ts test/*.ts", + prepare: "npm run copy-protos && npm run generate-types && npm run generate-test-types && npm run compile", + test: "gulp test", + check: "npm run lint", + fix: "eslint --fix src/*.ts test/*.ts", + pretest: "npm run generate-types && npm run generate-test-types && npm run compile", + posttest: "npm run check && madge -c ./build/src", + "generate-types": "proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --includeDirs proto/ --include-dirs proto/ proto/xds/ proto/protoc-gen-validate/ -O src/generated/ --grpcLib ../index channelz.proto xds/service/orca/v3/orca.proto", + "generate-test-types": "proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --include-dirs test/fixtures/ -O test/generated/ --grpcLib ../../src/index test_service.proto echo_service.proto", + "copy-protos": "node ./copy-protos" + }, + dependencies: { + "@grpc/proto-loader": "^0.8.0", + "@js-sdsl/ordered-map": "^4.4.2" + }, + files: [ + "src/**/*.ts", + "build/src/**/*.{js,d.ts,js.map}", + "proto/**/*.proto", + "proto/**/LICENSE", + "LICENSE", + "deps/envoy-api/envoy/api/v2/**/*.proto", + "deps/envoy-api/envoy/config/**/*.proto", + "deps/envoy-api/envoy/service/**/*.proto", + "deps/envoy-api/envoy/type/**/*.proto", + "deps/udpa/udpa/**/*.proto", + "deps/googleapis/google/api/*.proto", + "deps/googleapis/google/rpc/*.proto", + "deps/protoc-gen-validate/validate/**/*.proto" + ] + }; + } +}); + +// node_modules/@grpc/grpc-js/build/src/logging.js +var require_logging = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/logging.js"(exports2) { + "use strict"; + var _a; + var _b; + var _c; + var _d; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.log = exports2.setLoggerVerbosity = exports2.setLogger = exports2.getLogger = void 0; + exports2.trace = trace; + exports2.isTracerEnabled = isTracerEnabled; + var constants_1 = require_constants7(); + var process_1 = require("process"); + var clientVersion = require_package2().version; + var DEFAULT_LOGGER = { + error: (message, ...optionalParams) => { + console.error("E " + message, ...optionalParams); + }, + info: (message, ...optionalParams) => { + console.error("I " + message, ...optionalParams); + }, + debug: (message, ...optionalParams) => { + console.error("D " + message, ...optionalParams); + } + }; + var _logger = DEFAULT_LOGGER; + var _logVerbosity = constants_1.LogVerbosity.ERROR; + var verbosityString = (_b = (_a = process.env.GRPC_NODE_VERBOSITY) !== null && _a !== void 0 ? _a : process.env.GRPC_VERBOSITY) !== null && _b !== void 0 ? _b : ""; + switch (verbosityString.toUpperCase()) { + case "DEBUG": + _logVerbosity = constants_1.LogVerbosity.DEBUG; + break; + case "INFO": + _logVerbosity = constants_1.LogVerbosity.INFO; + break; + case "ERROR": + _logVerbosity = constants_1.LogVerbosity.ERROR; + break; + case "NONE": + _logVerbosity = constants_1.LogVerbosity.NONE; + break; + default: + } + var getLogger = () => { + return _logger; + }; + exports2.getLogger = getLogger; + var setLogger = (logger) => { + _logger = logger; + }; + exports2.setLogger = setLogger; + var setLoggerVerbosity = (verbosity) => { + _logVerbosity = verbosity; + }; + exports2.setLoggerVerbosity = setLoggerVerbosity; + var log = (severity, ...args) => { + let logFunction; + if (severity >= _logVerbosity) { + switch (severity) { + case constants_1.LogVerbosity.DEBUG: + logFunction = _logger.debug; + break; + case constants_1.LogVerbosity.INFO: + logFunction = _logger.info; + break; + case constants_1.LogVerbosity.ERROR: + logFunction = _logger.error; + break; + } + if (!logFunction) { + logFunction = _logger.error; + } + if (logFunction) { + logFunction.bind(_logger)(...args); + } + } + }; + exports2.log = log; + var tracersString = (_d = (_c = process.env.GRPC_NODE_TRACE) !== null && _c !== void 0 ? _c : process.env.GRPC_TRACE) !== null && _d !== void 0 ? _d : ""; + var enabledTracers = /* @__PURE__ */ new Set(); + var disabledTracers = /* @__PURE__ */ new Set(); + for (const tracerName of tracersString.split(",")) { + if (tracerName.startsWith("-")) { + disabledTracers.add(tracerName.substring(1)); + } else { + enabledTracers.add(tracerName); + } + } + var allEnabled = enabledTracers.has("all"); + function trace(severity, tracer, text) { + if (isTracerEnabled(tracer)) { + (0, exports2.log)(severity, (/* @__PURE__ */ new Date()).toISOString() + " | v" + clientVersion + " " + process_1.pid + " | " + tracer + " | " + text); + } + } + function isTracerEnabled(tracer) { + return !disabledTracers.has(tracer) && (allEnabled || enabledTracers.has(tracer)); + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/error.js +var require_error = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/error.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getErrorMessage = getErrorMessage; + exports2.getErrorCode = getErrorCode; + function getErrorMessage(error2) { + if (error2 instanceof Error) { + return error2.message; + } else { + return String(error2); + } + } + function getErrorCode(error2) { + if (typeof error2 === "object" && error2 !== null && "code" in error2 && typeof error2.code === "number") { + return error2.code; + } else { + return null; + } + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/metadata.js +var require_metadata = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/metadata.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Metadata = void 0; + var logging_1 = require_logging(); + var constants_1 = require_constants7(); + var error_1 = require_error(); + var LEGAL_KEY_REGEX = /^[:0-9a-z_.-]+$/; + var LEGAL_NON_BINARY_VALUE_REGEX = /^[ -~]*$/; + function isLegalKey(key) { + return LEGAL_KEY_REGEX.test(key); + } + function isLegalNonBinaryValue(value) { + return LEGAL_NON_BINARY_VALUE_REGEX.test(value); + } + function isBinaryKey(key) { + return key.endsWith("-bin"); + } + function isCustomMetadata(key) { + return !key.startsWith("grpc-"); + } + function normalizeKey(key) { + return key.toLowerCase(); + } + function validate(key, value) { + if (!isLegalKey(key)) { + throw new Error('Metadata key "' + key + '" contains illegal characters'); + } + if (value !== null && value !== void 0) { + if (isBinaryKey(key)) { + if (!Buffer.isBuffer(value)) { + throw new Error("keys that end with '-bin' must have Buffer values"); + } + } else { + if (Buffer.isBuffer(value)) { + throw new Error("keys that don't end with '-bin' must have String values"); + } + if (!isLegalNonBinaryValue(value)) { + throw new Error('Metadata string value "' + value + '" contains illegal characters'); + } + } + } + } + var Metadata = class _Metadata { + constructor(options = {}) { + this.internalRepr = /* @__PURE__ */ new Map(); + this.opaqueData = /* @__PURE__ */ new Map(); + this.options = options; + } + /** + * Sets the given value for the given key by replacing any other values + * associated with that key. Normalizes the key. + * @param key The key to whose value should be set. + * @param value The value to set. Must be a buffer if and only + * if the normalized key ends with '-bin'. + */ + set(key, value) { + key = normalizeKey(key); + validate(key, value); + this.internalRepr.set(key, [value]); + } + /** + * Adds the given value for the given key by appending to a list of previous + * values associated with that key. Normalizes the key. + * @param key The key for which a new value should be appended. + * @param value The value to add. Must be a buffer if and only + * if the normalized key ends with '-bin'. + */ + add(key, value) { + key = normalizeKey(key); + validate(key, value); + const existingValue = this.internalRepr.get(key); + if (existingValue === void 0) { + this.internalRepr.set(key, [value]); + } else { + existingValue.push(value); + } + } + /** + * Removes the given key and any associated values. Normalizes the key. + * @param key The key whose values should be removed. + */ + remove(key) { + key = normalizeKey(key); + this.internalRepr.delete(key); + } + /** + * Gets a list of all values associated with the key. Normalizes the key. + * @param key The key whose value should be retrieved. + * @return A list of values associated with the given key. + */ + get(key) { + key = normalizeKey(key); + return this.internalRepr.get(key) || []; + } + /** + * Gets a plain object mapping each key to the first value associated with it. + * This reflects the most common way that people will want to see metadata. + * @return A key/value mapping of the metadata. + */ + getMap() { + const result = {}; + for (const [key, values] of this.internalRepr) { + if (values.length > 0) { + const v = values[0]; + result[key] = Buffer.isBuffer(v) ? Buffer.from(v) : v; + } + } + return result; + } + /** + * Clones the metadata object. + * @return The newly cloned object. + */ + clone() { + const newMetadata = new _Metadata(this.options); + const newInternalRepr = newMetadata.internalRepr; + for (const [key, value] of this.internalRepr) { + const clonedValue = value.map((v) => { + if (Buffer.isBuffer(v)) { + return Buffer.from(v); + } else { + return v; + } + }); + newInternalRepr.set(key, clonedValue); + } + return newMetadata; + } + /** + * Merges all key-value pairs from a given Metadata object into this one. + * If both this object and the given object have values in the same key, + * values from the other Metadata object will be appended to this object's + * values. + * @param other A Metadata object. + */ + merge(other) { + for (const [key, values] of other.internalRepr) { + const mergedValue = (this.internalRepr.get(key) || []).concat(values); + this.internalRepr.set(key, mergedValue); + } + } + setOptions(options) { + this.options = options; + } + getOptions() { + return this.options; + } + /** + * Creates an OutgoingHttpHeaders object that can be used with the http2 API. + */ + toHttp2Headers() { + const result = {}; + for (const [key, values] of this.internalRepr) { + if (key.startsWith(":")) { + continue; + } + result[key] = values.map(bufToString); + } + return result; + } + /** + * This modifies the behavior of JSON.stringify to show an object + * representation of the metadata map. + */ + toJSON() { + const result = {}; + for (const [key, values] of this.internalRepr) { + result[key] = values; + } + return result; + } + /** + * Attach additional data of any type to the metadata object, which will not + * be included when sending headers. The data can later be retrieved with + * `getOpaque`. Keys with the prefix `grpc` are reserved for use by this + * library. + * @param key + * @param value + */ + setOpaque(key, value) { + this.opaqueData.set(key, value); + } + /** + * Retrieve data previously added with `setOpaque`. + * @param key + * @returns + */ + getOpaque(key) { + return this.opaqueData.get(key); + } + /** + * Returns a new Metadata object based fields in a given IncomingHttpHeaders + * object. + * @param headers An IncomingHttpHeaders object. + */ + static fromHttp2Headers(headers) { + const result = new _Metadata(); + for (const key of Object.keys(headers)) { + if (key.charAt(0) === ":") { + continue; + } + const values = headers[key]; + try { + if (isBinaryKey(key)) { + if (Array.isArray(values)) { + values.forEach((value) => { + result.add(key, Buffer.from(value, "base64")); + }); + } else if (values !== void 0) { + if (isCustomMetadata(key)) { + values.split(",").forEach((v) => { + result.add(key, Buffer.from(v.trim(), "base64")); + }); + } else { + result.add(key, Buffer.from(values, "base64")); + } + } + } else { + if (Array.isArray(values)) { + values.forEach((value) => { + result.add(key, value); + }); + } else if (values !== void 0) { + result.add(key, values); + } + } + } catch (error2) { + const message = `Failed to add metadata entry ${key}: ${values}. ${(0, error_1.getErrorMessage)(error2)}. For more information see https://github.com/grpc/grpc-node/issues/1173`; + (0, logging_1.log)(constants_1.LogVerbosity.ERROR, message); + } + } + return result; + } + }; + exports2.Metadata = Metadata; + var bufToString = (val) => { + return Buffer.isBuffer(val) ? val.toString("base64") : val; + }; + } +}); + +// node_modules/@grpc/grpc-js/build/src/call-credentials.js +var require_call_credentials = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/call-credentials.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CallCredentials = void 0; + var metadata_1 = require_metadata(); + function isCurrentOauth2Client(client) { + return "getRequestHeaders" in client && typeof client.getRequestHeaders === "function"; + } + var CallCredentials = class _CallCredentials { + /** + * Creates a new CallCredentials object from a given function that generates + * Metadata objects. + * @param metadataGenerator A function that accepts a set of options, and + * generates a Metadata object based on these options, which is passed back + * to the caller via a supplied (err, metadata) callback. + */ + static createFromMetadataGenerator(metadataGenerator) { + return new SingleCallCredentials(metadataGenerator); + } + /** + * Create a gRPC credential from a Google credential object. + * @param googleCredentials The authentication client to use. + * @return The resulting CallCredentials object. + */ + static createFromGoogleCredential(googleCredentials) { + return _CallCredentials.createFromMetadataGenerator((options, callback) => { + let getHeaders; + if (isCurrentOauth2Client(googleCredentials)) { + getHeaders = googleCredentials.getRequestHeaders(options.service_url); + } else { + getHeaders = new Promise((resolve, reject) => { + googleCredentials.getRequestMetadata(options.service_url, (err, headers) => { + if (err) { + reject(err); + return; + } + if (!headers) { + reject(new Error("Headers not set by metadata plugin")); + return; + } + resolve(headers); + }); + }); + } + getHeaders.then((headers) => { + const metadata = new metadata_1.Metadata(); + for (const key of Object.keys(headers)) { + metadata.add(key, headers[key]); + } + callback(null, metadata); + }, (err) => { + callback(err); + }); + }); + } + static createEmpty() { + return new EmptyCallCredentials(); + } + }; + exports2.CallCredentials = CallCredentials; + var ComposedCallCredentials = class _ComposedCallCredentials extends CallCredentials { + constructor(creds) { + super(); + this.creds = creds; + } + async generateMetadata(options) { + const base = new metadata_1.Metadata(); + const generated = await Promise.all(this.creds.map((cred) => cred.generateMetadata(options))); + for (const gen of generated) { + base.merge(gen); + } + return base; + } + compose(other) { + return new _ComposedCallCredentials(this.creds.concat([other])); + } + _equals(other) { + if (this === other) { + return true; + } + if (other instanceof _ComposedCallCredentials) { + return this.creds.every((value, index) => value._equals(other.creds[index])); + } else { + return false; + } + } + }; + var SingleCallCredentials = class _SingleCallCredentials extends CallCredentials { + constructor(metadataGenerator) { + super(); + this.metadataGenerator = metadataGenerator; + } + generateMetadata(options) { + return new Promise((resolve, reject) => { + this.metadataGenerator(options, (err, metadata) => { + if (metadata !== void 0) { + resolve(metadata); + } else { + reject(err); + } + }); + }); + } + compose(other) { + return new ComposedCallCredentials([this, other]); + } + _equals(other) { + if (this === other) { + return true; + } + if (other instanceof _SingleCallCredentials) { + return this.metadataGenerator === other.metadataGenerator; + } else { + return false; + } + } + }; + var EmptyCallCredentials = class _EmptyCallCredentials extends CallCredentials { + generateMetadata(options) { + return Promise.resolve(new metadata_1.Metadata()); + } + compose(other) { + return other; + } + _equals(other) { + return other instanceof _EmptyCallCredentials; + } + }; + } +}); + +// node_modules/@grpc/grpc-js/build/src/tls-helpers.js +var require_tls_helpers = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/tls-helpers.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CIPHER_SUITES = void 0; + exports2.getDefaultRootsData = getDefaultRootsData; + var fs4 = require("fs"); + exports2.CIPHER_SUITES = process.env.GRPC_SSL_CIPHER_SUITES; + var DEFAULT_ROOTS_FILE_PATH = process.env.GRPC_DEFAULT_SSL_ROOTS_FILE_PATH; + var defaultRootsData = null; + function getDefaultRootsData() { + if (DEFAULT_ROOTS_FILE_PATH) { + if (defaultRootsData === null) { + defaultRootsData = fs4.readFileSync(DEFAULT_ROOTS_FILE_PATH); + } + return defaultRootsData; + } + return null; + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/uri-parser.js +var require_uri_parser = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/uri-parser.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.parseUri = parseUri; + exports2.splitHostPort = splitHostPort; + exports2.combineHostPort = combineHostPort; + exports2.uriToString = uriToString; + var URI_REGEX = /^(?:([A-Za-z0-9+.-]+):)?(?:\/\/([^/]*)\/)?(.+)$/; + function parseUri(uriString) { + const parsedUri = URI_REGEX.exec(uriString); + if (parsedUri === null) { + return null; + } + return { + scheme: parsedUri[1], + authority: parsedUri[2], + path: parsedUri[3] + }; + } + var NUMBER_REGEX = /^\d+$/; + function splitHostPort(path) { + if (path.startsWith("[")) { + const hostEnd = path.indexOf("]"); + if (hostEnd === -1) { + return null; + } + const host = path.substring(1, hostEnd); + if (host.indexOf(":") === -1) { + return null; + } + if (path.length > hostEnd + 1) { + if (path[hostEnd + 1] === ":") { + const portString = path.substring(hostEnd + 2); + if (NUMBER_REGEX.test(portString)) { + return { + host, + port: +portString + }; + } else { + return null; + } + } else { + return null; + } + } else { + return { + host + }; + } + } else { + const splitPath = path.split(":"); + if (splitPath.length === 2) { + if (NUMBER_REGEX.test(splitPath[1])) { + return { + host: splitPath[0], + port: +splitPath[1] + }; + } else { + return null; + } + } else { + return { + host: path + }; + } + } + } + function combineHostPort(hostPort) { + if (hostPort.port === void 0) { + return hostPort.host; + } else { + if (hostPort.host.includes(":")) { + return `[${hostPort.host}]:${hostPort.port}`; + } else { + return `${hostPort.host}:${hostPort.port}`; + } + } + } + function uriToString(uri) { + let result = ""; + if (uri.scheme !== void 0) { + result += uri.scheme + ":"; + } + if (uri.authority !== void 0) { + result += "//" + uri.authority + "/"; + } + result += uri.path; + return result; + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/resolver.js +var require_resolver = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/resolver.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CHANNEL_ARGS_CONFIG_SELECTOR_KEY = void 0; + exports2.registerResolver = registerResolver; + exports2.registerDefaultScheme = registerDefaultScheme; + exports2.createResolver = createResolver; + exports2.getDefaultAuthority = getDefaultAuthority; + exports2.mapUriDefaultScheme = mapUriDefaultScheme; + var uri_parser_1 = require_uri_parser(); + exports2.CHANNEL_ARGS_CONFIG_SELECTOR_KEY = "grpc.internal.config_selector"; + var registeredResolvers = {}; + var defaultScheme = null; + function registerResolver(scheme, resolverClass) { + registeredResolvers[scheme] = resolverClass; + } + function registerDefaultScheme(scheme) { + defaultScheme = scheme; + } + function createResolver(target, listener, options) { + if (target.scheme !== void 0 && target.scheme in registeredResolvers) { + return new registeredResolvers[target.scheme](target, listener, options); + } else { + throw new Error(`No resolver could be created for target ${(0, uri_parser_1.uriToString)(target)}`); + } + } + function getDefaultAuthority(target) { + if (target.scheme !== void 0 && target.scheme in registeredResolvers) { + return registeredResolvers[target.scheme].getDefaultAuthority(target); + } else { + throw new Error(`Invalid target ${(0, uri_parser_1.uriToString)(target)}`); + } + } + function mapUriDefaultScheme(target) { + if (target.scheme === void 0 || !(target.scheme in registeredResolvers)) { + if (defaultScheme !== null) { + return { + scheme: defaultScheme, + authority: void 0, + path: (0, uri_parser_1.uriToString)(target) + }; + } else { + return null; + } + } + return target; + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/channel-credentials.js +var require_channel_credentials = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/channel-credentials.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ChannelCredentials = void 0; + exports2.createCertificateProviderChannelCredentials = createCertificateProviderChannelCredentials; + var tls_1 = require("tls"); + var call_credentials_1 = require_call_credentials(); + var tls_helpers_1 = require_tls_helpers(); + var uri_parser_1 = require_uri_parser(); + var resolver_1 = require_resolver(); + var logging_1 = require_logging(); + var constants_1 = require_constants7(); + function verifyIsBufferOrNull(obj, friendlyName) { + if (obj && !(obj instanceof Buffer)) { + throw new TypeError(`${friendlyName}, if provided, must be a Buffer.`); + } + } + var ChannelCredentials = class { + /** + * Returns a copy of this object with the included set of per-call credentials + * expanded to include callCredentials. + * @param callCredentials A CallCredentials object to associate with this + * instance. + */ + compose(callCredentials) { + return new ComposedChannelCredentialsImpl(this, callCredentials); + } + /** + * Return a new ChannelCredentials instance with a given set of credentials. + * The resulting instance can be used to construct a Channel that communicates + * over TLS. + * @param rootCerts The root certificate data. + * @param privateKey The client certificate private key, if available. + * @param certChain The client certificate key chain, if available. + * @param verifyOptions Additional options to modify certificate verification + */ + static createSsl(rootCerts, privateKey, certChain, verifyOptions) { + var _a; + verifyIsBufferOrNull(rootCerts, "Root certificate"); + verifyIsBufferOrNull(privateKey, "Private key"); + verifyIsBufferOrNull(certChain, "Certificate chain"); + if (privateKey && !certChain) { + throw new Error("Private key must be given with accompanying certificate chain"); + } + if (!privateKey && certChain) { + throw new Error("Certificate chain must be given with accompanying private key"); + } + const secureContext = (0, tls_1.createSecureContext)({ + ca: (_a = rootCerts !== null && rootCerts !== void 0 ? rootCerts : (0, tls_helpers_1.getDefaultRootsData)()) !== null && _a !== void 0 ? _a : void 0, + key: privateKey !== null && privateKey !== void 0 ? privateKey : void 0, + cert: certChain !== null && certChain !== void 0 ? certChain : void 0, + ciphers: tls_helpers_1.CIPHER_SUITES + }); + return new SecureChannelCredentialsImpl(secureContext, verifyOptions !== null && verifyOptions !== void 0 ? verifyOptions : {}); + } + /** + * Return a new ChannelCredentials instance with credentials created using + * the provided secureContext. The resulting instances can be used to + * construct a Channel that communicates over TLS. gRPC will not override + * anything in the provided secureContext, so the environment variables + * GRPC_SSL_CIPHER_SUITES and GRPC_DEFAULT_SSL_ROOTS_FILE_PATH will + * not be applied. + * @param secureContext The return value of tls.createSecureContext() + * @param verifyOptions Additional options to modify certificate verification + */ + static createFromSecureContext(secureContext, verifyOptions) { + return new SecureChannelCredentialsImpl(secureContext, verifyOptions !== null && verifyOptions !== void 0 ? verifyOptions : {}); + } + /** + * Return a new ChannelCredentials instance with no credentials. + */ + static createInsecure() { + return new InsecureChannelCredentialsImpl(); + } + }; + exports2.ChannelCredentials = ChannelCredentials; + var InsecureChannelCredentialsImpl = class _InsecureChannelCredentialsImpl extends ChannelCredentials { + constructor() { + super(); + } + compose(callCredentials) { + throw new Error("Cannot compose insecure credentials"); + } + _isSecure() { + return false; + } + _equals(other) { + return other instanceof _InsecureChannelCredentialsImpl; + } + _createSecureConnector(channelTarget, options, callCredentials) { + return { + connect(socket) { + return Promise.resolve({ + socket, + secure: false + }); + }, + waitForReady: () => { + return Promise.resolve(); + }, + getCallCredentials: () => { + return callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty(); + }, + destroy() { + } + }; + } + }; + function getConnectionOptions(secureContext, verifyOptions, channelTarget, options) { + var _a, _b; + const connectionOptions = { + secureContext + }; + let realTarget = channelTarget; + if ("grpc.http_connect_target" in options) { + const parsedTarget = (0, uri_parser_1.parseUri)(options["grpc.http_connect_target"]); + if (parsedTarget) { + realTarget = parsedTarget; + } + } + const targetPath = (0, resolver_1.getDefaultAuthority)(realTarget); + const hostPort = (0, uri_parser_1.splitHostPort)(targetPath); + const remoteHost = (_a = hostPort === null || hostPort === void 0 ? void 0 : hostPort.host) !== null && _a !== void 0 ? _a : targetPath; + connectionOptions.host = remoteHost; + if (verifyOptions.checkServerIdentity) { + connectionOptions.checkServerIdentity = verifyOptions.checkServerIdentity; + } + if (verifyOptions.rejectUnauthorized !== void 0) { + connectionOptions.rejectUnauthorized = verifyOptions.rejectUnauthorized; + } + connectionOptions.ALPNProtocols = ["h2"]; + if (options["grpc.ssl_target_name_override"]) { + const sslTargetNameOverride = options["grpc.ssl_target_name_override"]; + const originalCheckServerIdentity = (_b = connectionOptions.checkServerIdentity) !== null && _b !== void 0 ? _b : tls_1.checkServerIdentity; + connectionOptions.checkServerIdentity = (host, cert) => { + return originalCheckServerIdentity(sslTargetNameOverride, cert); + }; + connectionOptions.servername = sslTargetNameOverride; + } else { + connectionOptions.servername = remoteHost; + } + if (options["grpc-node.tls_enable_trace"]) { + connectionOptions.enableTrace = true; + } + return connectionOptions; + } + var SecureConnectorImpl = class { + constructor(connectionOptions, callCredentials) { + this.connectionOptions = connectionOptions; + this.callCredentials = callCredentials; + } + connect(socket) { + const tlsConnectOptions = Object.assign({ socket }, this.connectionOptions); + return new Promise((resolve, reject) => { + const tlsSocket = (0, tls_1.connect)(tlsConnectOptions, () => { + var _a; + if (((_a = this.connectionOptions.rejectUnauthorized) !== null && _a !== void 0 ? _a : true) && !tlsSocket.authorized) { + reject(tlsSocket.authorizationError); + return; + } + resolve({ + socket: tlsSocket, + secure: true + }); + }); + tlsSocket.on("error", (error2) => { + reject(error2); + }); + }); + } + waitForReady() { + return Promise.resolve(); + } + getCallCredentials() { + return this.callCredentials; + } + destroy() { + } + }; + var SecureChannelCredentialsImpl = class _SecureChannelCredentialsImpl extends ChannelCredentials { + constructor(secureContext, verifyOptions) { + super(); + this.secureContext = secureContext; + this.verifyOptions = verifyOptions; + } + _isSecure() { + return true; + } + _equals(other) { + if (this === other) { + return true; + } + if (other instanceof _SecureChannelCredentialsImpl) { + return this.secureContext === other.secureContext && this.verifyOptions.checkServerIdentity === other.verifyOptions.checkServerIdentity; + } else { + return false; + } + } + _createSecureConnector(channelTarget, options, callCredentials) { + const connectionOptions = getConnectionOptions(this.secureContext, this.verifyOptions, channelTarget, options); + return new SecureConnectorImpl(connectionOptions, callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty()); + } + }; + var CertificateProviderChannelCredentialsImpl = class _CertificateProviderChannelCredentialsImpl extends ChannelCredentials { + constructor(caCertificateProvider, identityCertificateProvider, verifyOptions) { + super(); + this.caCertificateProvider = caCertificateProvider; + this.identityCertificateProvider = identityCertificateProvider; + this.verifyOptions = verifyOptions; + this.refcount = 0; + this.latestCaUpdate = void 0; + this.latestIdentityUpdate = void 0; + this.caCertificateUpdateListener = this.handleCaCertificateUpdate.bind(this); + this.identityCertificateUpdateListener = this.handleIdentityCertitificateUpdate.bind(this); + this.secureContextWatchers = []; + } + _isSecure() { + return true; + } + _equals(other) { + var _a, _b; + if (this === other) { + return true; + } + if (other instanceof _CertificateProviderChannelCredentialsImpl) { + return this.caCertificateProvider === other.caCertificateProvider && this.identityCertificateProvider === other.identityCertificateProvider && ((_a = this.verifyOptions) === null || _a === void 0 ? void 0 : _a.checkServerIdentity) === ((_b = other.verifyOptions) === null || _b === void 0 ? void 0 : _b.checkServerIdentity); + } else { + return false; + } + } + ref() { + var _a; + if (this.refcount === 0) { + this.caCertificateProvider.addCaCertificateListener(this.caCertificateUpdateListener); + (_a = this.identityCertificateProvider) === null || _a === void 0 ? void 0 : _a.addIdentityCertificateListener(this.identityCertificateUpdateListener); + } + this.refcount += 1; + } + unref() { + var _a; + this.refcount -= 1; + if (this.refcount === 0) { + this.caCertificateProvider.removeCaCertificateListener(this.caCertificateUpdateListener); + (_a = this.identityCertificateProvider) === null || _a === void 0 ? void 0 : _a.removeIdentityCertificateListener(this.identityCertificateUpdateListener); + } + } + _createSecureConnector(channelTarget, options, callCredentials) { + this.ref(); + return new _CertificateProviderChannelCredentialsImpl.SecureConnectorImpl(this, channelTarget, options, callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty()); + } + maybeUpdateWatchers() { + if (this.hasReceivedUpdates()) { + for (const watcher of this.secureContextWatchers) { + watcher(this.getLatestSecureContext()); + } + this.secureContextWatchers = []; + } + } + handleCaCertificateUpdate(update) { + this.latestCaUpdate = update; + this.maybeUpdateWatchers(); + } + handleIdentityCertitificateUpdate(update) { + this.latestIdentityUpdate = update; + this.maybeUpdateWatchers(); + } + hasReceivedUpdates() { + if (this.latestCaUpdate === void 0) { + return false; + } + if (this.identityCertificateProvider && this.latestIdentityUpdate === void 0) { + return false; + } + return true; + } + getSecureContext() { + if (this.hasReceivedUpdates()) { + return Promise.resolve(this.getLatestSecureContext()); + } else { + return new Promise((resolve) => { + this.secureContextWatchers.push(resolve); + }); + } + } + getLatestSecureContext() { + var _a, _b; + if (!this.latestCaUpdate) { + return null; + } + if (this.identityCertificateProvider !== null && !this.latestIdentityUpdate) { + return null; + } + try { + return (0, tls_1.createSecureContext)({ + ca: this.latestCaUpdate.caCertificate, + key: (_a = this.latestIdentityUpdate) === null || _a === void 0 ? void 0 : _a.privateKey, + cert: (_b = this.latestIdentityUpdate) === null || _b === void 0 ? void 0 : _b.certificate, + ciphers: tls_helpers_1.CIPHER_SUITES + }); + } catch (e) { + (0, logging_1.log)(constants_1.LogVerbosity.ERROR, "Failed to createSecureContext with error " + e.message); + return null; + } + } + }; + CertificateProviderChannelCredentialsImpl.SecureConnectorImpl = class { + constructor(parent, channelTarget, options, callCredentials) { + this.parent = parent; + this.channelTarget = channelTarget; + this.options = options; + this.callCredentials = callCredentials; + } + connect(socket) { + return new Promise((resolve, reject) => { + const secureContext = this.parent.getLatestSecureContext(); + if (!secureContext) { + reject(new Error("Failed to load credentials")); + return; + } + if (socket.closed) { + reject(new Error("Socket closed while loading credentials")); + } + const connnectionOptions = getConnectionOptions(secureContext, this.parent.verifyOptions, this.channelTarget, this.options); + const tlsConnectOptions = Object.assign({ socket }, connnectionOptions); + const closeCallback = () => { + reject(new Error("Socket closed")); + }; + const errorCallback = (error2) => { + reject(error2); + }; + const tlsSocket = (0, tls_1.connect)(tlsConnectOptions, () => { + var _a; + tlsSocket.removeListener("close", closeCallback); + tlsSocket.removeListener("error", errorCallback); + if (((_a = this.parent.verifyOptions.rejectUnauthorized) !== null && _a !== void 0 ? _a : true) && !tlsSocket.authorized) { + reject(tlsSocket.authorizationError); + return; + } + resolve({ + socket: tlsSocket, + secure: true + }); + }); + tlsSocket.once("close", closeCallback); + tlsSocket.once("error", errorCallback); + }); + } + async waitForReady() { + await this.parent.getSecureContext(); + } + getCallCredentials() { + return this.callCredentials; + } + destroy() { + this.parent.unref(); + } + }; + function createCertificateProviderChannelCredentials(caCertificateProvider, identityCertificateProvider, verifyOptions) { + return new CertificateProviderChannelCredentialsImpl(caCertificateProvider, identityCertificateProvider, verifyOptions !== null && verifyOptions !== void 0 ? verifyOptions : {}); + } + var ComposedChannelCredentialsImpl = class _ComposedChannelCredentialsImpl extends ChannelCredentials { + constructor(channelCredentials, callCredentials) { + super(); + this.channelCredentials = channelCredentials; + this.callCredentials = callCredentials; + if (!channelCredentials._isSecure()) { + throw new Error("Cannot compose insecure credentials"); + } + } + compose(callCredentials) { + const combinedCallCredentials = this.callCredentials.compose(callCredentials); + return new _ComposedChannelCredentialsImpl(this.channelCredentials, combinedCallCredentials); + } + _isSecure() { + return true; + } + _equals(other) { + if (this === other) { + return true; + } + if (other instanceof _ComposedChannelCredentialsImpl) { + return this.channelCredentials._equals(other.channelCredentials) && this.callCredentials._equals(other.callCredentials); + } else { + return false; + } + } + _createSecureConnector(channelTarget, options, callCredentials) { + const combinedCallCredentials = this.callCredentials.compose(callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty()); + return this.channelCredentials._createSecureConnector(channelTarget, options, combinedCallCredentials); + } + }; + } +}); + +// node_modules/@grpc/grpc-js/build/src/load-balancer.js +var require_load_balancer = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/load-balancer.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createChildChannelControlHelper = createChildChannelControlHelper; + exports2.registerLoadBalancerType = registerLoadBalancerType; + exports2.registerDefaultLoadBalancerType = registerDefaultLoadBalancerType; + exports2.createLoadBalancer = createLoadBalancer; + exports2.isLoadBalancerNameRegistered = isLoadBalancerNameRegistered; + exports2.parseLoadBalancingConfig = parseLoadBalancingConfig; + exports2.getDefaultConfig = getDefaultConfig; + exports2.selectLbConfigFromList = selectLbConfigFromList; + var logging_1 = require_logging(); + var constants_1 = require_constants7(); + function createChildChannelControlHelper(parent, overrides) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; + return { + createSubchannel: (_b = (_a = overrides.createSubchannel) === null || _a === void 0 ? void 0 : _a.bind(overrides)) !== null && _b !== void 0 ? _b : parent.createSubchannel.bind(parent), + updateState: (_d = (_c = overrides.updateState) === null || _c === void 0 ? void 0 : _c.bind(overrides)) !== null && _d !== void 0 ? _d : parent.updateState.bind(parent), + requestReresolution: (_f = (_e = overrides.requestReresolution) === null || _e === void 0 ? void 0 : _e.bind(overrides)) !== null && _f !== void 0 ? _f : parent.requestReresolution.bind(parent), + addChannelzChild: (_h = (_g = overrides.addChannelzChild) === null || _g === void 0 ? void 0 : _g.bind(overrides)) !== null && _h !== void 0 ? _h : parent.addChannelzChild.bind(parent), + removeChannelzChild: (_k = (_j = overrides.removeChannelzChild) === null || _j === void 0 ? void 0 : _j.bind(overrides)) !== null && _k !== void 0 ? _k : parent.removeChannelzChild.bind(parent) + }; + } + var registeredLoadBalancerTypes = {}; + var defaultLoadBalancerType = null; + function registerLoadBalancerType(typeName, loadBalancerType, loadBalancingConfigType) { + registeredLoadBalancerTypes[typeName] = { + LoadBalancer: loadBalancerType, + LoadBalancingConfig: loadBalancingConfigType + }; + } + function registerDefaultLoadBalancerType(typeName) { + defaultLoadBalancerType = typeName; + } + function createLoadBalancer(config, channelControlHelper) { + const typeName = config.getLoadBalancerName(); + if (typeName in registeredLoadBalancerTypes) { + return new registeredLoadBalancerTypes[typeName].LoadBalancer(channelControlHelper); + } else { + return null; + } + } + function isLoadBalancerNameRegistered(typeName) { + return typeName in registeredLoadBalancerTypes; + } + function parseLoadBalancingConfig(rawConfig) { + const keys = Object.keys(rawConfig); + if (keys.length !== 1) { + throw new Error("Provided load balancing config has multiple conflicting entries"); + } + const typeName = keys[0]; + if (typeName in registeredLoadBalancerTypes) { + try { + return registeredLoadBalancerTypes[typeName].LoadBalancingConfig.createFromJson(rawConfig[typeName]); + } catch (e) { + throw new Error(`${typeName}: ${e.message}`); + } + } else { + throw new Error(`Unrecognized load balancing config name ${typeName}`); + } + } + function getDefaultConfig() { + if (!defaultLoadBalancerType) { + throw new Error("No default load balancer type registered"); + } + return new registeredLoadBalancerTypes[defaultLoadBalancerType].LoadBalancingConfig(); + } + function selectLbConfigFromList(configs, fallbackTodefault = false) { + for (const config of configs) { + try { + return parseLoadBalancingConfig(config); + } catch (e) { + (0, logging_1.log)(constants_1.LogVerbosity.DEBUG, "Config parsing failed with error", e.message); + continue; + } + } + if (fallbackTodefault) { + if (defaultLoadBalancerType) { + return new registeredLoadBalancerTypes[defaultLoadBalancerType].LoadBalancingConfig(); + } else { + return null; + } + } else { + return null; + } + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/service-config.js +var require_service_config = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/service-config.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.validateRetryThrottling = validateRetryThrottling; + exports2.validateServiceConfig = validateServiceConfig; + exports2.extractAndSelectServiceConfig = extractAndSelectServiceConfig; + var os4 = require("os"); + var constants_1 = require_constants7(); + var DURATION_REGEX = /^\d+(\.\d{1,9})?s$/; + var CLIENT_LANGUAGE_STRING = "node"; + function validateName(obj) { + if ("service" in obj && obj.service !== "") { + if (typeof obj.service !== "string") { + throw new Error(`Invalid method config name: invalid service: expected type string, got ${typeof obj.service}`); + } + if ("method" in obj && obj.method !== "") { + if (typeof obj.method !== "string") { + throw new Error(`Invalid method config name: invalid method: expected type string, got ${typeof obj.service}`); + } + return { + service: obj.service, + method: obj.method + }; + } else { + return { + service: obj.service + }; + } + } else { + if ("method" in obj && obj.method !== void 0) { + throw new Error(`Invalid method config name: method set with empty or unset service`); + } + return {}; + } + } + function validateRetryPolicy(obj) { + if (!("maxAttempts" in obj) || !Number.isInteger(obj.maxAttempts) || obj.maxAttempts < 2) { + throw new Error("Invalid method config retry policy: maxAttempts must be an integer at least 2"); + } + if (!("initialBackoff" in obj) || typeof obj.initialBackoff !== "string" || !DURATION_REGEX.test(obj.initialBackoff)) { + throw new Error("Invalid method config retry policy: initialBackoff must be a string consisting of a positive integer or decimal followed by s"); + } + if (!("maxBackoff" in obj) || typeof obj.maxBackoff !== "string" || !DURATION_REGEX.test(obj.maxBackoff)) { + throw new Error("Invalid method config retry policy: maxBackoff must be a string consisting of a positive integer or decimal followed by s"); + } + if (!("backoffMultiplier" in obj) || typeof obj.backoffMultiplier !== "number" || obj.backoffMultiplier <= 0) { + throw new Error("Invalid method config retry policy: backoffMultiplier must be a number greater than 0"); + } + if (!("retryableStatusCodes" in obj && Array.isArray(obj.retryableStatusCodes))) { + throw new Error("Invalid method config retry policy: retryableStatusCodes is required"); + } + if (obj.retryableStatusCodes.length === 0) { + throw new Error("Invalid method config retry policy: retryableStatusCodes must be non-empty"); + } + for (const value of obj.retryableStatusCodes) { + if (typeof value === "number") { + if (!Object.values(constants_1.Status).includes(value)) { + throw new Error("Invalid method config retry policy: retryableStatusCodes value not in status code range"); + } + } else if (typeof value === "string") { + if (!Object.values(constants_1.Status).includes(value.toUpperCase())) { + throw new Error("Invalid method config retry policy: retryableStatusCodes value not a status code name"); + } + } else { + throw new Error("Invalid method config retry policy: retryableStatusCodes value must be a string or number"); + } + } + return { + maxAttempts: obj.maxAttempts, + initialBackoff: obj.initialBackoff, + maxBackoff: obj.maxBackoff, + backoffMultiplier: obj.backoffMultiplier, + retryableStatusCodes: obj.retryableStatusCodes + }; + } + function validateHedgingPolicy(obj) { + if (!("maxAttempts" in obj) || !Number.isInteger(obj.maxAttempts) || obj.maxAttempts < 2) { + throw new Error("Invalid method config hedging policy: maxAttempts must be an integer at least 2"); + } + if ("hedgingDelay" in obj && (typeof obj.hedgingDelay !== "string" || !DURATION_REGEX.test(obj.hedgingDelay))) { + throw new Error("Invalid method config hedging policy: hedgingDelay must be a string consisting of a positive integer followed by s"); + } + if ("nonFatalStatusCodes" in obj && Array.isArray(obj.nonFatalStatusCodes)) { + for (const value of obj.nonFatalStatusCodes) { + if (typeof value === "number") { + if (!Object.values(constants_1.Status).includes(value)) { + throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value not in status code range"); + } + } else if (typeof value === "string") { + if (!Object.values(constants_1.Status).includes(value.toUpperCase())) { + throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value not a status code name"); + } + } else { + throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value must be a string or number"); + } + } + } + const result = { + maxAttempts: obj.maxAttempts + }; + if (obj.hedgingDelay) { + result.hedgingDelay = obj.hedgingDelay; + } + if (obj.nonFatalStatusCodes) { + result.nonFatalStatusCodes = obj.nonFatalStatusCodes; + } + return result; + } + function validateMethodConfig(obj) { + var _a; + const result = { + name: [] + }; + if (!("name" in obj) || !Array.isArray(obj.name)) { + throw new Error("Invalid method config: invalid name array"); + } + for (const name of obj.name) { + result.name.push(validateName(name)); + } + if ("waitForReady" in obj) { + if (typeof obj.waitForReady !== "boolean") { + throw new Error("Invalid method config: invalid waitForReady"); + } + result.waitForReady = obj.waitForReady; + } + if ("timeout" in obj) { + if (typeof obj.timeout === "object") { + if (!("seconds" in obj.timeout) || !(typeof obj.timeout.seconds === "number")) { + throw new Error("Invalid method config: invalid timeout.seconds"); + } + if (!("nanos" in obj.timeout) || !(typeof obj.timeout.nanos === "number")) { + throw new Error("Invalid method config: invalid timeout.nanos"); + } + result.timeout = obj.timeout; + } else if (typeof obj.timeout === "string" && DURATION_REGEX.test(obj.timeout)) { + const timeoutParts = obj.timeout.substring(0, obj.timeout.length - 1).split("."); + result.timeout = { + seconds: timeoutParts[0] | 0, + nanos: ((_a = timeoutParts[1]) !== null && _a !== void 0 ? _a : 0) | 0 + }; + } else { + throw new Error("Invalid method config: invalid timeout"); + } + } + if ("maxRequestBytes" in obj) { + if (typeof obj.maxRequestBytes !== "number") { + throw new Error("Invalid method config: invalid maxRequestBytes"); + } + result.maxRequestBytes = obj.maxRequestBytes; + } + if ("maxResponseBytes" in obj) { + if (typeof obj.maxResponseBytes !== "number") { + throw new Error("Invalid method config: invalid maxRequestBytes"); + } + result.maxResponseBytes = obj.maxResponseBytes; + } + if ("retryPolicy" in obj) { + if ("hedgingPolicy" in obj) { + throw new Error("Invalid method config: retryPolicy and hedgingPolicy cannot both be specified"); + } else { + result.retryPolicy = validateRetryPolicy(obj.retryPolicy); + } + } else if ("hedgingPolicy" in obj) { + result.hedgingPolicy = validateHedgingPolicy(obj.hedgingPolicy); + } + return result; + } + function validateRetryThrottling(obj) { + if (!("maxTokens" in obj) || typeof obj.maxTokens !== "number" || obj.maxTokens <= 0 || obj.maxTokens > 1e3) { + throw new Error("Invalid retryThrottling: maxTokens must be a number in (0, 1000]"); + } + if (!("tokenRatio" in obj) || typeof obj.tokenRatio !== "number" || obj.tokenRatio <= 0) { + throw new Error("Invalid retryThrottling: tokenRatio must be a number greater than 0"); + } + return { + maxTokens: +obj.maxTokens.toFixed(3), + tokenRatio: +obj.tokenRatio.toFixed(3) + }; + } + function validateLoadBalancingConfig(obj) { + if (!(typeof obj === "object" && obj !== null)) { + throw new Error(`Invalid loadBalancingConfig: unexpected type ${typeof obj}`); + } + const keys = Object.keys(obj); + if (keys.length > 1) { + throw new Error(`Invalid loadBalancingConfig: unexpected multiple keys ${keys}`); + } + if (keys.length === 0) { + throw new Error("Invalid loadBalancingConfig: load balancing policy name required"); + } + return { + [keys[0]]: obj[keys[0]] + }; + } + function validateServiceConfig(obj) { + const result = { + loadBalancingConfig: [], + methodConfig: [] + }; + if ("loadBalancingPolicy" in obj) { + if (typeof obj.loadBalancingPolicy === "string") { + result.loadBalancingPolicy = obj.loadBalancingPolicy; + } else { + throw new Error("Invalid service config: invalid loadBalancingPolicy"); + } + } + if ("loadBalancingConfig" in obj) { + if (Array.isArray(obj.loadBalancingConfig)) { + for (const config of obj.loadBalancingConfig) { + result.loadBalancingConfig.push(validateLoadBalancingConfig(config)); + } + } else { + throw new Error("Invalid service config: invalid loadBalancingConfig"); + } + } + if ("methodConfig" in obj) { + if (Array.isArray(obj.methodConfig)) { + for (const methodConfig of obj.methodConfig) { + result.methodConfig.push(validateMethodConfig(methodConfig)); + } + } + } + if ("retryThrottling" in obj) { + result.retryThrottling = validateRetryThrottling(obj.retryThrottling); + } + const seenMethodNames = []; + for (const methodConfig of result.methodConfig) { + for (const name of methodConfig.name) { + for (const seenName of seenMethodNames) { + if (name.service === seenName.service && name.method === seenName.method) { + throw new Error(`Invalid service config: duplicate name ${name.service}/${name.method}`); + } + } + seenMethodNames.push(name); + } + } + return result; + } + function validateCanaryConfig(obj) { + if (!("serviceConfig" in obj)) { + throw new Error("Invalid service config choice: missing service config"); + } + const result = { + serviceConfig: validateServiceConfig(obj.serviceConfig) + }; + if ("clientLanguage" in obj) { + if (Array.isArray(obj.clientLanguage)) { + result.clientLanguage = []; + for (const lang of obj.clientLanguage) { + if (typeof lang === "string") { + result.clientLanguage.push(lang); + } else { + throw new Error("Invalid service config choice: invalid clientLanguage"); + } + } + } else { + throw new Error("Invalid service config choice: invalid clientLanguage"); + } + } + if ("clientHostname" in obj) { + if (Array.isArray(obj.clientHostname)) { + result.clientHostname = []; + for (const lang of obj.clientHostname) { + if (typeof lang === "string") { + result.clientHostname.push(lang); + } else { + throw new Error("Invalid service config choice: invalid clientHostname"); + } + } + } else { + throw new Error("Invalid service config choice: invalid clientHostname"); + } + } + if ("percentage" in obj) { + if (typeof obj.percentage === "number" && 0 <= obj.percentage && obj.percentage <= 100) { + result.percentage = obj.percentage; + } else { + throw new Error("Invalid service config choice: invalid percentage"); + } + } + const allowedFields = [ + "clientLanguage", + "percentage", + "clientHostname", + "serviceConfig" + ]; + for (const field in obj) { + if (!allowedFields.includes(field)) { + throw new Error(`Invalid service config choice: unexpected field ${field}`); + } + } + return result; + } + function validateAndSelectCanaryConfig(obj, percentage) { + if (!Array.isArray(obj)) { + throw new Error("Invalid service config list"); + } + for (const config of obj) { + const validatedConfig = validateCanaryConfig(config); + if (typeof validatedConfig.percentage === "number" && percentage > validatedConfig.percentage) { + continue; + } + if (Array.isArray(validatedConfig.clientHostname)) { + let hostnameMatched = false; + for (const hostname of validatedConfig.clientHostname) { + if (hostname === os4.hostname()) { + hostnameMatched = true; + } + } + if (!hostnameMatched) { + continue; + } + } + if (Array.isArray(validatedConfig.clientLanguage)) { + let languageMatched = false; + for (const language of validatedConfig.clientLanguage) { + if (language === CLIENT_LANGUAGE_STRING) { + languageMatched = true; + } + } + if (!languageMatched) { + continue; + } + } + return validatedConfig.serviceConfig; + } + throw new Error("No matching service config found"); + } + function extractAndSelectServiceConfig(txtRecord, percentage) { + for (const record of txtRecord) { + if (record.length > 0 && record[0].startsWith("grpc_config=")) { + const recordString = record.join("").substring("grpc_config=".length); + const recordJson = JSON.parse(recordString); + return validateAndSelectCanaryConfig(recordJson, percentage); + } + } + return null; + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/connectivity-state.js +var require_connectivity_state = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/connectivity-state.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ConnectivityState = void 0; + var ConnectivityState; + (function(ConnectivityState2) { + ConnectivityState2[ConnectivityState2["IDLE"] = 0] = "IDLE"; + ConnectivityState2[ConnectivityState2["CONNECTING"] = 1] = "CONNECTING"; + ConnectivityState2[ConnectivityState2["READY"] = 2] = "READY"; + ConnectivityState2[ConnectivityState2["TRANSIENT_FAILURE"] = 3] = "TRANSIENT_FAILURE"; + ConnectivityState2[ConnectivityState2["SHUTDOWN"] = 4] = "SHUTDOWN"; + })(ConnectivityState || (exports2.ConnectivityState = ConnectivityState = {})); + } +}); + +// node_modules/@grpc/grpc-js/build/src/picker.js +var require_picker = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/picker.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.QueuePicker = exports2.UnavailablePicker = exports2.PickResultType = void 0; + var metadata_1 = require_metadata(); + var constants_1 = require_constants7(); + var PickResultType; + (function(PickResultType2) { + PickResultType2[PickResultType2["COMPLETE"] = 0] = "COMPLETE"; + PickResultType2[PickResultType2["QUEUE"] = 1] = "QUEUE"; + PickResultType2[PickResultType2["TRANSIENT_FAILURE"] = 2] = "TRANSIENT_FAILURE"; + PickResultType2[PickResultType2["DROP"] = 3] = "DROP"; + })(PickResultType || (exports2.PickResultType = PickResultType = {})); + var UnavailablePicker = class { + constructor(status) { + this.status = Object.assign({ code: constants_1.Status.UNAVAILABLE, details: "No connection established", metadata: new metadata_1.Metadata() }, status); + } + pick(pickArgs) { + return { + pickResultType: PickResultType.TRANSIENT_FAILURE, + subchannel: null, + status: this.status, + onCallStarted: null, + onCallEnded: null + }; + } + }; + exports2.UnavailablePicker = UnavailablePicker; + var QueuePicker = class { + // Constructed with a load balancer. Calls exitIdle on it the first time pick is called + constructor(loadBalancer, childPicker) { + this.loadBalancer = loadBalancer; + this.childPicker = childPicker; + this.calledExitIdle = false; + } + pick(pickArgs) { + if (!this.calledExitIdle) { + process.nextTick(() => { + this.loadBalancer.exitIdle(); + }); + this.calledExitIdle = true; + } + if (this.childPicker) { + return this.childPicker.pick(pickArgs); + } else { + return { + pickResultType: PickResultType.QUEUE, + subchannel: null, + status: null, + onCallStarted: null, + onCallEnded: null + }; + } + } + }; + exports2.QueuePicker = QueuePicker; + } +}); + +// node_modules/@grpc/grpc-js/build/src/backoff-timeout.js +var require_backoff_timeout = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/backoff-timeout.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.BackoffTimeout = void 0; + var constants_1 = require_constants7(); + var logging = require_logging(); + var TRACER_NAME = "backoff"; + var INITIAL_BACKOFF_MS = 1e3; + var BACKOFF_MULTIPLIER = 1.6; + var MAX_BACKOFF_MS = 12e4; + var BACKOFF_JITTER = 0.2; + function uniformRandom(min, max) { + return Math.random() * (max - min) + min; + } + var BackoffTimeout = class _BackoffTimeout { + constructor(callback, options) { + this.callback = callback; + this.initialDelay = INITIAL_BACKOFF_MS; + this.multiplier = BACKOFF_MULTIPLIER; + this.maxDelay = MAX_BACKOFF_MS; + this.jitter = BACKOFF_JITTER; + this.running = false; + this.hasRef = true; + this.startTime = /* @__PURE__ */ new Date(); + this.endTime = /* @__PURE__ */ new Date(); + this.id = _BackoffTimeout.getNextId(); + if (options) { + if (options.initialDelay) { + this.initialDelay = options.initialDelay; + } + if (options.multiplier) { + this.multiplier = options.multiplier; + } + if (options.jitter) { + this.jitter = options.jitter; + } + if (options.maxDelay) { + this.maxDelay = options.maxDelay; + } + } + this.trace("constructed initialDelay=" + this.initialDelay + " multiplier=" + this.multiplier + " jitter=" + this.jitter + " maxDelay=" + this.maxDelay); + this.nextDelay = this.initialDelay; + this.timerId = setTimeout(() => { + }, 0); + clearTimeout(this.timerId); + } + static getNextId() { + return this.nextId++; + } + trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "{" + this.id + "} " + text); + } + runTimer(delay) { + var _a, _b; + this.trace("runTimer(delay=" + delay + ")"); + this.endTime = this.startTime; + this.endTime.setMilliseconds(this.endTime.getMilliseconds() + delay); + clearTimeout(this.timerId); + this.timerId = setTimeout(() => { + this.trace("timer fired"); + this.running = false; + this.callback(); + }, delay); + if (!this.hasRef) { + (_b = (_a = this.timerId).unref) === null || _b === void 0 ? void 0 : _b.call(_a); + } + } + /** + * Call the callback after the current amount of delay time + */ + runOnce() { + this.trace("runOnce()"); + this.running = true; + this.startTime = /* @__PURE__ */ new Date(); + this.runTimer(this.nextDelay); + const nextBackoff = Math.min(this.nextDelay * this.multiplier, this.maxDelay); + const jitterMagnitude = nextBackoff * this.jitter; + this.nextDelay = nextBackoff + uniformRandom(-jitterMagnitude, jitterMagnitude); + } + /** + * Stop the timer. The callback will not be called until `runOnce` is called + * again. + */ + stop() { + this.trace("stop()"); + clearTimeout(this.timerId); + this.running = false; + } + /** + * Reset the delay time to its initial value. If the timer is still running, + * retroactively apply that reset to the current timer. + */ + reset() { + this.trace("reset() running=" + this.running); + this.nextDelay = this.initialDelay; + if (this.running) { + const now = /* @__PURE__ */ new Date(); + const newEndTime = this.startTime; + newEndTime.setMilliseconds(newEndTime.getMilliseconds() + this.nextDelay); + clearTimeout(this.timerId); + if (now < newEndTime) { + this.runTimer(newEndTime.getTime() - now.getTime()); + } else { + this.running = false; + } + } + } + /** + * Check whether the timer is currently running. + */ + isRunning() { + return this.running; + } + /** + * Set that while the timer is running, it should keep the Node process + * running. + */ + ref() { + var _a, _b; + this.hasRef = true; + (_b = (_a = this.timerId).ref) === null || _b === void 0 ? void 0 : _b.call(_a); + } + /** + * Set that while the timer is running, it should not keep the Node process + * running. + */ + unref() { + var _a, _b; + this.hasRef = false; + (_b = (_a = this.timerId).unref) === null || _b === void 0 ? void 0 : _b.call(_a); + } + /** + * Get the approximate timestamp of when the timer will fire. Only valid if + * this.isRunning() is true. + */ + getEndTime() { + return this.endTime; + } + }; + exports2.BackoffTimeout = BackoffTimeout; + BackoffTimeout.nextId = 0; + } +}); + +// node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.js +var require_load_balancer_child_handler = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ChildLoadBalancerHandler = void 0; + var load_balancer_1 = require_load_balancer(); + var connectivity_state_1 = require_connectivity_state(); + var TYPE_NAME = "child_load_balancer_helper"; + var ChildLoadBalancerHandler = class { + constructor(channelControlHelper) { + this.channelControlHelper = channelControlHelper; + this.currentChild = null; + this.pendingChild = null; + this.latestConfig = null; + this.ChildPolicyHelper = class { + constructor(parent) { + this.parent = parent; + this.child = null; + } + createSubchannel(subchannelAddress, subchannelArgs) { + return this.parent.channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs); + } + updateState(connectivityState, picker, errorMessage) { + var _a; + if (this.calledByPendingChild()) { + if (connectivityState === connectivity_state_1.ConnectivityState.CONNECTING) { + return; + } + (_a = this.parent.currentChild) === null || _a === void 0 ? void 0 : _a.destroy(); + this.parent.currentChild = this.parent.pendingChild; + this.parent.pendingChild = null; + } else if (!this.calledByCurrentChild()) { + return; + } + this.parent.channelControlHelper.updateState(connectivityState, picker, errorMessage); + } + requestReresolution() { + var _a; + const latestChild = (_a = this.parent.pendingChild) !== null && _a !== void 0 ? _a : this.parent.currentChild; + if (this.child === latestChild) { + this.parent.channelControlHelper.requestReresolution(); + } + } + setChild(newChild) { + this.child = newChild; + } + addChannelzChild(child) { + this.parent.channelControlHelper.addChannelzChild(child); + } + removeChannelzChild(child) { + this.parent.channelControlHelper.removeChannelzChild(child); + } + calledByPendingChild() { + return this.child === this.parent.pendingChild; + } + calledByCurrentChild() { + return this.child === this.parent.currentChild; + } + }; + } + configUpdateRequiresNewPolicyInstance(oldConfig, newConfig) { + return oldConfig.getLoadBalancerName() !== newConfig.getLoadBalancerName(); + } + /** + * Prerequisites: lbConfig !== null and lbConfig.name is registered + * @param endpointList + * @param lbConfig + * @param attributes + */ + updateAddressList(endpointList, lbConfig, options, resolutionNote) { + let childToUpdate; + if (this.currentChild === null || this.latestConfig === null || this.configUpdateRequiresNewPolicyInstance(this.latestConfig, lbConfig)) { + const newHelper = new this.ChildPolicyHelper(this); + const newChild = (0, load_balancer_1.createLoadBalancer)(lbConfig, newHelper); + newHelper.setChild(newChild); + if (this.currentChild === null) { + this.currentChild = newChild; + childToUpdate = this.currentChild; + } else { + if (this.pendingChild) { + this.pendingChild.destroy(); + } + this.pendingChild = newChild; + childToUpdate = this.pendingChild; + } + } else { + if (this.pendingChild === null) { + childToUpdate = this.currentChild; + } else { + childToUpdate = this.pendingChild; + } + } + this.latestConfig = lbConfig; + return childToUpdate.updateAddressList(endpointList, lbConfig, options, resolutionNote); + } + exitIdle() { + if (this.currentChild) { + this.currentChild.exitIdle(); + if (this.pendingChild) { + this.pendingChild.exitIdle(); + } + } + } + resetBackoff() { + if (this.currentChild) { + this.currentChild.resetBackoff(); + if (this.pendingChild) { + this.pendingChild.resetBackoff(); + } + } + } + destroy() { + if (this.currentChild) { + this.currentChild.destroy(); + this.currentChild = null; + } + if (this.pendingChild) { + this.pendingChild.destroy(); + this.pendingChild = null; + } + } + getTypeName() { + return TYPE_NAME; + } + }; + exports2.ChildLoadBalancerHandler = ChildLoadBalancerHandler; + } +}); + +// node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.js +var require_resolving_load_balancer = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ResolvingLoadBalancer = void 0; + var load_balancer_1 = require_load_balancer(); + var service_config_1 = require_service_config(); + var connectivity_state_1 = require_connectivity_state(); + var resolver_1 = require_resolver(); + var picker_1 = require_picker(); + var backoff_timeout_1 = require_backoff_timeout(); + var constants_1 = require_constants7(); + var metadata_1 = require_metadata(); + var logging = require_logging(); + var constants_2 = require_constants7(); + var uri_parser_1 = require_uri_parser(); + var load_balancer_child_handler_1 = require_load_balancer_child_handler(); + var TRACER_NAME = "resolving_load_balancer"; + function trace(text) { + logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, text); + } + var NAME_MATCH_LEVEL_ORDER = [ + "SERVICE_AND_METHOD", + "SERVICE", + "EMPTY" + ]; + function hasMatchingName(service, method, methodConfig, matchLevel) { + for (const name of methodConfig.name) { + switch (matchLevel) { + case "EMPTY": + if (!name.service && !name.method) { + return true; + } + break; + case "SERVICE": + if (name.service === service && !name.method) { + return true; + } + break; + case "SERVICE_AND_METHOD": + if (name.service === service && name.method === method) { + return true; + } + } + } + return false; + } + function findMatchingConfig(service, method, methodConfigs, matchLevel) { + for (const config of methodConfigs) { + if (hasMatchingName(service, method, config, matchLevel)) { + return config; + } + } + return null; + } + function getDefaultConfigSelector(serviceConfig) { + return { + invoke(methodName, metadata) { + var _a, _b; + const splitName = methodName.split("/").filter((x) => x.length > 0); + const service = (_a = splitName[0]) !== null && _a !== void 0 ? _a : ""; + const method = (_b = splitName[1]) !== null && _b !== void 0 ? _b : ""; + if (serviceConfig && serviceConfig.methodConfig) { + for (const matchLevel of NAME_MATCH_LEVEL_ORDER) { + const matchingConfig = findMatchingConfig(service, method, serviceConfig.methodConfig, matchLevel); + if (matchingConfig) { + return { + methodConfig: matchingConfig, + pickInformation: {}, + status: constants_1.Status.OK, + dynamicFilterFactories: [] + }; + } + } + } + return { + methodConfig: { name: [] }, + pickInformation: {}, + status: constants_1.Status.OK, + dynamicFilterFactories: [] + }; + }, + unref() { + } + }; + } + var ResolvingLoadBalancer = class { + /** + * Wrapper class that behaves like a `LoadBalancer` and also handles name + * resolution internally. + * @param target The address of the backend to connect to. + * @param channelControlHelper `ChannelControlHelper` instance provided by + * this load balancer's owner. + * @param defaultServiceConfig The default service configuration to be used + * if none is provided by the name resolver. A `null` value indicates + * that the default behavior should be the default unconfigured behavior. + * In practice, that means using the "pick first" load balancer + * implmentation + */ + constructor(target, channelControlHelper, channelOptions, onSuccessfulResolution, onFailedResolution) { + this.target = target; + this.channelControlHelper = channelControlHelper; + this.channelOptions = channelOptions; + this.onSuccessfulResolution = onSuccessfulResolution; + this.onFailedResolution = onFailedResolution; + this.latestChildState = connectivity_state_1.ConnectivityState.IDLE; + this.latestChildPicker = new picker_1.QueuePicker(this); + this.latestChildErrorMessage = null; + this.currentState = connectivity_state_1.ConnectivityState.IDLE; + this.previousServiceConfig = null; + this.continueResolving = false; + if (channelOptions["grpc.service_config"]) { + this.defaultServiceConfig = (0, service_config_1.validateServiceConfig)(JSON.parse(channelOptions["grpc.service_config"])); + } else { + this.defaultServiceConfig = { + loadBalancingConfig: [], + methodConfig: [] + }; + } + this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null); + this.childLoadBalancer = new load_balancer_child_handler_1.ChildLoadBalancerHandler({ + createSubchannel: channelControlHelper.createSubchannel.bind(channelControlHelper), + requestReresolution: () => { + if (this.backoffTimeout.isRunning()) { + trace("requestReresolution delayed by backoff timer until " + this.backoffTimeout.getEndTime().toISOString()); + this.continueResolving = true; + } else { + this.updateResolution(); + } + }, + updateState: (newState, picker, errorMessage) => { + this.latestChildState = newState; + this.latestChildPicker = picker; + this.latestChildErrorMessage = errorMessage; + this.updateState(newState, picker, errorMessage); + }, + addChannelzChild: channelControlHelper.addChannelzChild.bind(channelControlHelper), + removeChannelzChild: channelControlHelper.removeChannelzChild.bind(channelControlHelper) + }); + this.innerResolver = (0, resolver_1.createResolver)(target, this.handleResolverResult.bind(this), channelOptions); + const backoffOptions = { + initialDelay: channelOptions["grpc.initial_reconnect_backoff_ms"], + maxDelay: channelOptions["grpc.max_reconnect_backoff_ms"] + }; + this.backoffTimeout = new backoff_timeout_1.BackoffTimeout(() => { + if (this.continueResolving) { + this.updateResolution(); + this.continueResolving = false; + } else { + this.updateState(this.latestChildState, this.latestChildPicker, this.latestChildErrorMessage); + } + }, backoffOptions); + this.backoffTimeout.unref(); + } + handleResolverResult(endpointList, attributes, serviceConfig, resolutionNote) { + var _a, _b; + this.backoffTimeout.stop(); + this.backoffTimeout.reset(); + let resultAccepted = true; + let workingServiceConfig = null; + if (serviceConfig === null) { + workingServiceConfig = this.defaultServiceConfig; + } else if (serviceConfig.ok) { + workingServiceConfig = serviceConfig.value; + } else { + if (this.previousServiceConfig !== null) { + workingServiceConfig = this.previousServiceConfig; + } else { + resultAccepted = false; + this.handleResolutionFailure(serviceConfig.error); + } + } + if (workingServiceConfig !== null) { + const workingConfigList = (_a = workingServiceConfig === null || workingServiceConfig === void 0 ? void 0 : workingServiceConfig.loadBalancingConfig) !== null && _a !== void 0 ? _a : []; + const loadBalancingConfig = (0, load_balancer_1.selectLbConfigFromList)(workingConfigList, true); + if (loadBalancingConfig === null) { + resultAccepted = false; + this.handleResolutionFailure({ + code: constants_1.Status.UNAVAILABLE, + details: "All load balancer options in service config are not compatible", + metadata: new metadata_1.Metadata() + }); + } else { + resultAccepted = this.childLoadBalancer.updateAddressList(endpointList, loadBalancingConfig, Object.assign(Object.assign({}, this.channelOptions), attributes), resolutionNote); + } + } + if (resultAccepted) { + this.onSuccessfulResolution(workingServiceConfig, (_b = attributes[resolver_1.CHANNEL_ARGS_CONFIG_SELECTOR_KEY]) !== null && _b !== void 0 ? _b : getDefaultConfigSelector(workingServiceConfig)); + } + return resultAccepted; + } + updateResolution() { + this.innerResolver.updateResolution(); + if (this.currentState === connectivity_state_1.ConnectivityState.IDLE) { + this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, this.latestChildPicker, this.latestChildErrorMessage); + } + this.backoffTimeout.runOnce(); + } + updateState(connectivityState, picker, errorMessage) { + trace((0, uri_parser_1.uriToString)(this.target) + " " + connectivity_state_1.ConnectivityState[this.currentState] + " -> " + connectivity_state_1.ConnectivityState[connectivityState]); + if (connectivityState === connectivity_state_1.ConnectivityState.IDLE) { + picker = new picker_1.QueuePicker(this, picker); + } + this.currentState = connectivityState; + this.channelControlHelper.updateState(connectivityState, picker, errorMessage); + } + handleResolutionFailure(error2) { + if (this.latestChildState === connectivity_state_1.ConnectivityState.IDLE) { + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(error2), error2.details); + this.onFailedResolution(error2); + } + } + exitIdle() { + if (this.currentState === connectivity_state_1.ConnectivityState.IDLE || this.currentState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { + if (this.backoffTimeout.isRunning()) { + this.continueResolving = true; + } else { + this.updateResolution(); + } + } + this.childLoadBalancer.exitIdle(); + } + updateAddressList(endpointList, lbConfig) { + throw new Error("updateAddressList not supported on ResolvingLoadBalancer"); + } + resetBackoff() { + this.backoffTimeout.reset(); + this.childLoadBalancer.resetBackoff(); + } + destroy() { + this.childLoadBalancer.destroy(); + this.innerResolver.destroy(); + this.backoffTimeout.reset(); + this.backoffTimeout.stop(); + this.latestChildState = connectivity_state_1.ConnectivityState.IDLE; + this.latestChildPicker = new picker_1.QueuePicker(this); + this.currentState = connectivity_state_1.ConnectivityState.IDLE; + this.previousServiceConfig = null; + this.continueResolving = false; + } + getTypeName() { + return "resolving_load_balancer"; + } + }; + exports2.ResolvingLoadBalancer = ResolvingLoadBalancer; + } +}); + +// node_modules/@grpc/grpc-js/build/src/channel-options.js +var require_channel_options = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/channel-options.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.recognizedOptions = void 0; + exports2.channelOptionsEqual = channelOptionsEqual; + exports2.recognizedOptions = { + "grpc.ssl_target_name_override": true, + "grpc.primary_user_agent": true, + "grpc.secondary_user_agent": true, + "grpc.default_authority": true, + "grpc.keepalive_time_ms": true, + "grpc.keepalive_timeout_ms": true, + "grpc.keepalive_permit_without_calls": true, + "grpc.service_config": true, + "grpc.max_concurrent_streams": true, + "grpc.initial_reconnect_backoff_ms": true, + "grpc.max_reconnect_backoff_ms": true, + "grpc.use_local_subchannel_pool": true, + "grpc.max_send_message_length": true, + "grpc.max_receive_message_length": true, + "grpc.enable_http_proxy": true, + "grpc.enable_channelz": true, + "grpc.dns_min_time_between_resolutions_ms": true, + "grpc.enable_retries": true, + "grpc.per_rpc_retry_buffer_size": true, + "grpc.retry_buffer_size": true, + "grpc.max_connection_age_ms": true, + "grpc.max_connection_age_grace_ms": true, + "grpc-node.max_session_memory": true, + "grpc.service_config_disable_resolution": true, + "grpc.client_idle_timeout_ms": true, + "grpc-node.tls_enable_trace": true, + "grpc.lb.ring_hash.ring_size_cap": true, + "grpc-node.retry_max_attempts_limit": true, + "grpc-node.flow_control_window": true, + "grpc.server_call_metric_recording": true + }; + function channelOptionsEqual(options1, options2) { + const keys1 = Object.keys(options1).sort(); + const keys2 = Object.keys(options2).sort(); + if (keys1.length !== keys2.length) { + return false; + } + for (let i = 0; i < keys1.length; i += 1) { + if (keys1[i] !== keys2[i]) { + return false; + } + if (options1[keys1[i]] !== options2[keys2[i]]) { + return false; + } + } + return true; + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/subchannel-address.js +var require_subchannel_address = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/subchannel-address.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.EndpointMap = void 0; + exports2.isTcpSubchannelAddress = isTcpSubchannelAddress; + exports2.subchannelAddressEqual = subchannelAddressEqual; + exports2.subchannelAddressToString = subchannelAddressToString; + exports2.stringToSubchannelAddress = stringToSubchannelAddress; + exports2.endpointEqual = endpointEqual; + exports2.endpointToString = endpointToString; + exports2.endpointHasAddress = endpointHasAddress; + var net_1 = require("net"); + function isTcpSubchannelAddress(address) { + return "port" in address; + } + function subchannelAddressEqual(address1, address2) { + if (!address1 && !address2) { + return true; + } + if (!address1 || !address2) { + return false; + } + if (isTcpSubchannelAddress(address1)) { + return isTcpSubchannelAddress(address2) && address1.host === address2.host && address1.port === address2.port; + } else { + return !isTcpSubchannelAddress(address2) && address1.path === address2.path; + } + } + function subchannelAddressToString(address) { + if (isTcpSubchannelAddress(address)) { + if ((0, net_1.isIPv6)(address.host)) { + return "[" + address.host + "]:" + address.port; + } else { + return address.host + ":" + address.port; + } + } else { + return address.path; + } + } + var DEFAULT_PORT = 443; + function stringToSubchannelAddress(addressString, port) { + if ((0, net_1.isIP)(addressString)) { + return { + host: addressString, + port: port !== null && port !== void 0 ? port : DEFAULT_PORT + }; + } else { + return { + path: addressString + }; + } + } + function endpointEqual(endpoint1, endpoint2) { + if (endpoint1.addresses.length !== endpoint2.addresses.length) { + return false; + } + for (let i = 0; i < endpoint1.addresses.length; i++) { + if (!subchannelAddressEqual(endpoint1.addresses[i], endpoint2.addresses[i])) { + return false; + } + } + return true; + } + function endpointToString(endpoint2) { + return "[" + endpoint2.addresses.map(subchannelAddressToString).join(", ") + "]"; + } + function endpointHasAddress(endpoint2, expectedAddress) { + for (const address of endpoint2.addresses) { + if (subchannelAddressEqual(address, expectedAddress)) { + return true; + } + } + return false; + } + function endpointEqualUnordered(endpoint1, endpoint2) { + if (endpoint1.addresses.length !== endpoint2.addresses.length) { + return false; + } + for (const address1 of endpoint1.addresses) { + let matchFound = false; + for (const address2 of endpoint2.addresses) { + if (subchannelAddressEqual(address1, address2)) { + matchFound = true; + break; + } + } + if (!matchFound) { + return false; + } + } + return true; + } + var EndpointMap = class { + constructor() { + this.map = /* @__PURE__ */ new Set(); + } + get size() { + return this.map.size; + } + getForSubchannelAddress(address) { + for (const entry of this.map) { + if (endpointHasAddress(entry.key, address)) { + return entry.value; + } + } + return void 0; + } + /** + * Delete any entries in this map with keys that are not in endpoints + * @param endpoints + */ + deleteMissing(endpoints) { + const removedValues = []; + for (const entry of this.map) { + let foundEntry = false; + for (const endpoint2 of endpoints) { + if (endpointEqualUnordered(endpoint2, entry.key)) { + foundEntry = true; + } + } + if (!foundEntry) { + removedValues.push(entry.value); + this.map.delete(entry); + } + } + return removedValues; + } + get(endpoint2) { + for (const entry of this.map) { + if (endpointEqualUnordered(endpoint2, entry.key)) { + return entry.value; + } + } + return void 0; + } + set(endpoint2, mapEntry) { + for (const entry of this.map) { + if (endpointEqualUnordered(endpoint2, entry.key)) { + entry.value = mapEntry; + return; + } + } + this.map.add({ key: endpoint2, value: mapEntry }); + } + delete(endpoint2) { + for (const entry of this.map) { + if (endpointEqualUnordered(endpoint2, entry.key)) { + this.map.delete(entry); + return; + } + } + } + has(endpoint2) { + for (const entry of this.map) { + if (endpointEqualUnordered(endpoint2, entry.key)) { + return true; + } + } + return false; + } + clear() { + this.map.clear(); + } + *keys() { + for (const entry of this.map) { + yield entry.key; + } + } + *values() { + for (const entry of this.map) { + yield entry.value; + } + } + *entries() { + for (const entry of this.map) { + yield [entry.key, entry.value]; + } + } + }; + exports2.EndpointMap = EndpointMap; + } +}); + +// node_modules/@js-sdsl/ordered-map/dist/cjs/index.js +var require_cjs = __commonJS({ + "node_modules/@js-sdsl/ordered-map/dist/cjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "t", { + value: true + }); + var TreeNode = class { + constructor(t, e, s = 1) { + this.i = void 0; + this.h = void 0; + this.o = void 0; + this.u = t; + this.l = e; + this.p = s; + } + I() { + let t = this; + const e = t.o.o === t; + if (e && t.p === 1) { + t = t.h; + } else if (t.i) { + t = t.i; + while (t.h) { + t = t.h; + } + } else { + if (e) { + return t.o; + } + let s = t.o; + while (s.i === t) { + t = s; + s = t.o; + } + t = s; + } + return t; + } + B() { + let t = this; + if (t.h) { + t = t.h; + while (t.i) { + t = t.i; + } + return t; + } else { + let e = t.o; + while (e.h === t) { + t = e; + e = t.o; + } + if (t.h !== e) { + return e; + } else return t; + } + } + _() { + const t = this.o; + const e = this.h; + const s = e.i; + if (t.o === this) t.o = e; + else if (t.i === this) t.i = e; + else t.h = e; + e.o = t; + e.i = this; + this.o = e; + this.h = s; + if (s) s.o = this; + return e; + } + g() { + const t = this.o; + const e = this.i; + const s = e.h; + if (t.o === this) t.o = e; + else if (t.i === this) t.i = e; + else t.h = e; + e.o = t; + e.h = this; + this.o = e; + this.i = s; + if (s) s.o = this; + return e; + } + }; + var TreeNodeEnableIndex = class extends TreeNode { + constructor() { + super(...arguments); + this.M = 1; + } + _() { + const t = super._(); + this.O(); + t.O(); + return t; + } + g() { + const t = super.g(); + this.O(); + t.O(); + return t; + } + O() { + this.M = 1; + if (this.i) { + this.M += this.i.M; + } + if (this.h) { + this.M += this.h.M; + } + } + }; + var ContainerIterator = class { + constructor(t = 0) { + this.iteratorType = t; + } + equals(t) { + return this.T === t.T; + } + }; + var Base = class { + constructor() { + this.m = 0; + } + get length() { + return this.m; + } + size() { + return this.m; + } + empty() { + return this.m === 0; + } + }; + var Container2 = class extends Base { + }; + function throwIteratorAccessError() { + throw new RangeError("Iterator access denied!"); + } + var TreeContainer = class extends Container2 { + constructor(t = function(t2, e2) { + if (t2 < e2) return -1; + if (t2 > e2) return 1; + return 0; + }, e = false) { + super(); + this.v = void 0; + this.A = t; + this.enableIndex = e; + this.N = e ? TreeNodeEnableIndex : TreeNode; + this.C = new this.N(); + } + R(t, e) { + let s = this.C; + while (t) { + const i = this.A(t.u, e); + if (i < 0) { + t = t.h; + } else if (i > 0) { + s = t; + t = t.i; + } else return t; + } + return s; + } + K(t, e) { + let s = this.C; + while (t) { + const i = this.A(t.u, e); + if (i <= 0) { + t = t.h; + } else { + s = t; + t = t.i; + } + } + return s; + } + L(t, e) { + let s = this.C; + while (t) { + const i = this.A(t.u, e); + if (i < 0) { + s = t; + t = t.h; + } else if (i > 0) { + t = t.i; + } else return t; + } + return s; + } + k(t, e) { + let s = this.C; + while (t) { + const i = this.A(t.u, e); + if (i < 0) { + s = t; + t = t.h; + } else { + t = t.i; + } + } + return s; + } + P(t) { + while (true) { + const e = t.o; + if (e === this.C) return; + if (t.p === 1) { + t.p = 0; + return; + } + if (t === e.i) { + const s = e.h; + if (s.p === 1) { + s.p = 0; + e.p = 1; + if (e === this.v) { + this.v = e._(); + } else e._(); + } else { + if (s.h && s.h.p === 1) { + s.p = e.p; + e.p = 0; + s.h.p = 0; + if (e === this.v) { + this.v = e._(); + } else e._(); + return; + } else if (s.i && s.i.p === 1) { + s.p = 1; + s.i.p = 0; + s.g(); + } else { + s.p = 1; + t = e; + } + } + } else { + const s = e.i; + if (s.p === 1) { + s.p = 0; + e.p = 1; + if (e === this.v) { + this.v = e.g(); + } else e.g(); + } else { + if (s.i && s.i.p === 1) { + s.p = e.p; + e.p = 0; + s.i.p = 0; + if (e === this.v) { + this.v = e.g(); + } else e.g(); + return; + } else if (s.h && s.h.p === 1) { + s.p = 1; + s.h.p = 0; + s._(); + } else { + s.p = 1; + t = e; + } + } + } + } + } + S(t) { + if (this.m === 1) { + this.clear(); + return; + } + let e = t; + while (e.i || e.h) { + if (e.h) { + e = e.h; + while (e.i) e = e.i; + } else { + e = e.i; + } + const s2 = t.u; + t.u = e.u; + e.u = s2; + const i = t.l; + t.l = e.l; + e.l = i; + t = e; + } + if (this.C.i === e) { + this.C.i = e.o; + } else if (this.C.h === e) { + this.C.h = e.o; + } + this.P(e); + let s = e.o; + if (e === s.i) { + s.i = void 0; + } else s.h = void 0; + this.m -= 1; + this.v.p = 0; + if (this.enableIndex) { + while (s !== this.C) { + s.M -= 1; + s = s.o; + } + } + } + U(t) { + const e = typeof t === "number" ? t : void 0; + const s = typeof t === "function" ? t : void 0; + const i = typeof t === "undefined" ? [] : void 0; + let r = 0; + let n = this.v; + const h = []; + while (h.length || n) { + if (n) { + h.push(n); + n = n.i; + } else { + n = h.pop(); + if (r === e) return n; + i && i.push(n); + s && s(n, r, this); + r += 1; + n = n.h; + } + } + return i; + } + j(t) { + while (true) { + const e = t.o; + if (e.p === 0) return; + const s = e.o; + if (e === s.i) { + const i = s.h; + if (i && i.p === 1) { + i.p = e.p = 0; + if (s === this.v) return; + s.p = 1; + t = s; + continue; + } else if (t === e.h) { + t.p = 0; + if (t.i) { + t.i.o = e; + } + if (t.h) { + t.h.o = s; + } + e.h = t.i; + s.i = t.h; + t.i = e; + t.h = s; + if (s === this.v) { + this.v = t; + this.C.o = t; + } else { + const e2 = s.o; + if (e2.i === s) { + e2.i = t; + } else e2.h = t; + } + t.o = s.o; + e.o = t; + s.o = t; + s.p = 1; + } else { + e.p = 0; + if (s === this.v) { + this.v = s.g(); + } else s.g(); + s.p = 1; + return; + } + } else { + const i = s.i; + if (i && i.p === 1) { + i.p = e.p = 0; + if (s === this.v) return; + s.p = 1; + t = s; + continue; + } else if (t === e.i) { + t.p = 0; + if (t.i) { + t.i.o = s; + } + if (t.h) { + t.h.o = e; + } + s.h = t.i; + e.i = t.h; + t.i = s; + t.h = e; + if (s === this.v) { + this.v = t; + this.C.o = t; + } else { + const e2 = s.o; + if (e2.i === s) { + e2.i = t; + } else e2.h = t; + } + t.o = s.o; + e.o = t; + s.o = t; + s.p = 1; + } else { + e.p = 0; + if (s === this.v) { + this.v = s._(); + } else s._(); + s.p = 1; + return; + } + } + if (this.enableIndex) { + e.O(); + s.O(); + t.O(); + } + return; + } + } + q(t, e, s) { + if (this.v === void 0) { + this.m += 1; + this.v = new this.N(t, e, 0); + this.v.o = this.C; + this.C.o = this.C.i = this.C.h = this.v; + return this.m; + } + let i; + const r = this.C.i; + const n = this.A(r.u, t); + if (n === 0) { + r.l = e; + return this.m; + } else if (n > 0) { + r.i = new this.N(t, e); + r.i.o = r; + i = r.i; + this.C.i = i; + } else { + const r2 = this.C.h; + const n2 = this.A(r2.u, t); + if (n2 === 0) { + r2.l = e; + return this.m; + } else if (n2 < 0) { + r2.h = new this.N(t, e); + r2.h.o = r2; + i = r2.h; + this.C.h = i; + } else { + if (s !== void 0) { + const r3 = s.T; + if (r3 !== this.C) { + const s2 = this.A(r3.u, t); + if (s2 === 0) { + r3.l = e; + return this.m; + } else if (s2 > 0) { + const s3 = r3.I(); + const n3 = this.A(s3.u, t); + if (n3 === 0) { + s3.l = e; + return this.m; + } else if (n3 < 0) { + i = new this.N(t, e); + if (s3.h === void 0) { + s3.h = i; + i.o = s3; + } else { + r3.i = i; + i.o = r3; + } + } + } + } + } + if (i === void 0) { + i = this.v; + while (true) { + const s2 = this.A(i.u, t); + if (s2 > 0) { + if (i.i === void 0) { + i.i = new this.N(t, e); + i.i.o = i; + i = i.i; + break; + } + i = i.i; + } else if (s2 < 0) { + if (i.h === void 0) { + i.h = new this.N(t, e); + i.h.o = i; + i = i.h; + break; + } + i = i.h; + } else { + i.l = e; + return this.m; + } + } + } + } + } + if (this.enableIndex) { + let t2 = i.o; + while (t2 !== this.C) { + t2.M += 1; + t2 = t2.o; + } + } + this.j(i); + this.m += 1; + return this.m; + } + H(t, e) { + while (t) { + const s = this.A(t.u, e); + if (s < 0) { + t = t.h; + } else if (s > 0) { + t = t.i; + } else return t; + } + return t || this.C; + } + clear() { + this.m = 0; + this.v = void 0; + this.C.o = void 0; + this.C.i = this.C.h = void 0; + } + updateKeyByIterator(t, e) { + const s = t.T; + if (s === this.C) { + throwIteratorAccessError(); + } + if (this.m === 1) { + s.u = e; + return true; + } + const i = s.B().u; + if (s === this.C.i) { + if (this.A(i, e) > 0) { + s.u = e; + return true; + } + return false; + } + const r = s.I().u; + if (s === this.C.h) { + if (this.A(r, e) < 0) { + s.u = e; + return true; + } + return false; + } + if (this.A(r, e) >= 0 || this.A(i, e) <= 0) return false; + s.u = e; + return true; + } + eraseElementByPos(t) { + if (t < 0 || t > this.m - 1) { + throw new RangeError(); + } + const e = this.U(t); + this.S(e); + return this.m; + } + eraseElementByKey(t) { + if (this.m === 0) return false; + const e = this.H(this.v, t); + if (e === this.C) return false; + this.S(e); + return true; + } + eraseElementByIterator(t) { + const e = t.T; + if (e === this.C) { + throwIteratorAccessError(); + } + const s = e.h === void 0; + const i = t.iteratorType === 0; + if (i) { + if (s) t.next(); + } else { + if (!s || e.i === void 0) t.next(); + } + this.S(e); + return t; + } + getHeight() { + if (this.m === 0) return 0; + function traversal(t) { + if (!t) return 0; + return Math.max(traversal(t.i), traversal(t.h)) + 1; + } + return traversal(this.v); + } + }; + var TreeIterator = class extends ContainerIterator { + constructor(t, e, s) { + super(s); + this.T = t; + this.C = e; + if (this.iteratorType === 0) { + this.pre = function() { + if (this.T === this.C.i) { + throwIteratorAccessError(); + } + this.T = this.T.I(); + return this; + }; + this.next = function() { + if (this.T === this.C) { + throwIteratorAccessError(); + } + this.T = this.T.B(); + return this; + }; + } else { + this.pre = function() { + if (this.T === this.C.h) { + throwIteratorAccessError(); + } + this.T = this.T.B(); + return this; + }; + this.next = function() { + if (this.T === this.C) { + throwIteratorAccessError(); + } + this.T = this.T.I(); + return this; + }; + } + } + get index() { + let t = this.T; + const e = this.C.o; + if (t === this.C) { + if (e) { + return e.M - 1; + } + return 0; + } + let s = 0; + if (t.i) { + s += t.i.M; + } + while (t !== e) { + const e2 = t.o; + if (t === e2.h) { + s += 1; + if (e2.i) { + s += e2.i.M; + } + } + t = e2; + } + return s; + } + isAccessible() { + return this.T !== this.C; + } + }; + var OrderedMapIterator = class _OrderedMapIterator extends TreeIterator { + constructor(t, e, s, i) { + super(t, e, i); + this.container = s; + } + get pointer() { + if (this.T === this.C) { + throwIteratorAccessError(); + } + const t = this; + return new Proxy([], { + get(e, s) { + if (s === "0") return t.T.u; + else if (s === "1") return t.T.l; + e[0] = t.T.u; + e[1] = t.T.l; + return e[s]; + }, + set(e, s, i) { + if (s !== "1") { + throw new TypeError("prop must be 1"); + } + t.T.l = i; + return true; + } + }); + } + copy() { + return new _OrderedMapIterator(this.T, this.C, this.container, this.iteratorType); + } + }; + var OrderedMap = class extends TreeContainer { + constructor(t = [], e, s) { + super(e, s); + const i = this; + t.forEach((function(t2) { + i.setElement(t2[0], t2[1]); + })); + } + begin() { + return new OrderedMapIterator(this.C.i || this.C, this.C, this); + } + end() { + return new OrderedMapIterator(this.C, this.C, this); + } + rBegin() { + return new OrderedMapIterator(this.C.h || this.C, this.C, this, 1); + } + rEnd() { + return new OrderedMapIterator(this.C, this.C, this, 1); + } + front() { + if (this.m === 0) return; + const t = this.C.i; + return [t.u, t.l]; + } + back() { + if (this.m === 0) return; + const t = this.C.h; + return [t.u, t.l]; + } + lowerBound(t) { + const e = this.R(this.v, t); + return new OrderedMapIterator(e, this.C, this); + } + upperBound(t) { + const e = this.K(this.v, t); + return new OrderedMapIterator(e, this.C, this); + } + reverseLowerBound(t) { + const e = this.L(this.v, t); + return new OrderedMapIterator(e, this.C, this); + } + reverseUpperBound(t) { + const e = this.k(this.v, t); + return new OrderedMapIterator(e, this.C, this); + } + forEach(t) { + this.U((function(e, s, i) { + t([e.u, e.l], s, i); + })); + } + setElement(t, e, s) { + return this.q(t, e, s); + } + getElementByPos(t) { + if (t < 0 || t > this.m - 1) { + throw new RangeError(); + } + const e = this.U(t); + return [e.u, e.l]; + } + find(t) { + const e = this.H(this.v, t); + return new OrderedMapIterator(e, this.C, this); + } + getElementByKey(t) { + const e = this.H(this.v, t); + return e.l; + } + union(t) { + const e = this; + t.forEach((function(t2) { + e.setElement(t2[0], t2[1]); + })); + return this.m; + } + *[Symbol.iterator]() { + const t = this.m; + const e = this.U(); + for (let s = 0; s < t; ++s) { + const t2 = e[s]; + yield [t2.u, t2.l]; + } + } + }; + exports2.OrderedMap = OrderedMap; + } +}); + +// node_modules/@grpc/grpc-js/build/src/admin.js +var require_admin = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/admin.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.registerAdminService = registerAdminService; + exports2.addAdminServicesToServer = addAdminServicesToServer; + var registeredAdminServices = []; + function registerAdminService(getServiceDefinition, getHandlers) { + registeredAdminServices.push({ getServiceDefinition, getHandlers }); + } + function addAdminServicesToServer(server) { + for (const { getServiceDefinition, getHandlers } of registeredAdminServices) { + server.addService(getServiceDefinition(), getHandlers()); + } + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/call.js +var require_call = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/call.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ClientDuplexStreamImpl = exports2.ClientWritableStreamImpl = exports2.ClientReadableStreamImpl = exports2.ClientUnaryCallImpl = void 0; + exports2.callErrorFromStatus = callErrorFromStatus; + var events_1 = require("events"); + var stream_1 = require("stream"); + var constants_1 = require_constants7(); + function callErrorFromStatus(status, callerStack) { + const message = `${status.code} ${constants_1.Status[status.code]}: ${status.details}`; + const error2 = new Error(message); + const stack = `${error2.stack} +for call at +${callerStack}`; + return Object.assign(new Error(message), status, { stack }); + } + var ClientUnaryCallImpl = class extends events_1.EventEmitter { + constructor() { + super(); + } + cancel() { + var _a; + (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, "Cancelled on client"); + } + getPeer() { + var _a, _b; + return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : "unknown"; + } + getAuthContext() { + var _a, _b; + return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getAuthContext()) !== null && _b !== void 0 ? _b : null; + } + }; + exports2.ClientUnaryCallImpl = ClientUnaryCallImpl; + var ClientReadableStreamImpl = class extends stream_1.Readable { + constructor(deserialize) { + super({ objectMode: true }); + this.deserialize = deserialize; + } + cancel() { + var _a; + (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, "Cancelled on client"); + } + getPeer() { + var _a, _b; + return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : "unknown"; + } + getAuthContext() { + var _a, _b; + return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getAuthContext()) !== null && _b !== void 0 ? _b : null; + } + _read(_size) { + var _a; + (_a = this.call) === null || _a === void 0 ? void 0 : _a.startRead(); + } + }; + exports2.ClientReadableStreamImpl = ClientReadableStreamImpl; + var ClientWritableStreamImpl = class extends stream_1.Writable { + constructor(serialize) { + super({ objectMode: true }); + this.serialize = serialize; + } + cancel() { + var _a; + (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, "Cancelled on client"); + } + getPeer() { + var _a, _b; + return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : "unknown"; + } + getAuthContext() { + var _a, _b; + return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getAuthContext()) !== null && _b !== void 0 ? _b : null; + } + _write(chunk, encoding, cb) { + var _a; + const context3 = { + callback: cb + }; + const flags = Number(encoding); + if (!Number.isNaN(flags)) { + context3.flags = flags; + } + (_a = this.call) === null || _a === void 0 ? void 0 : _a.sendMessageWithContext(context3, chunk); + } + _final(cb) { + var _a; + (_a = this.call) === null || _a === void 0 ? void 0 : _a.halfClose(); + cb(); + } + }; + exports2.ClientWritableStreamImpl = ClientWritableStreamImpl; + var ClientDuplexStreamImpl = class extends stream_1.Duplex { + constructor(serialize, deserialize) { + super({ objectMode: true }); + this.serialize = serialize; + this.deserialize = deserialize; + } + cancel() { + var _a; + (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, "Cancelled on client"); + } + getPeer() { + var _a, _b; + return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : "unknown"; + } + getAuthContext() { + var _a, _b; + return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getAuthContext()) !== null && _b !== void 0 ? _b : null; + } + _read(_size) { + var _a; + (_a = this.call) === null || _a === void 0 ? void 0 : _a.startRead(); + } + _write(chunk, encoding, cb) { + var _a; + const context3 = { + callback: cb + }; + const flags = Number(encoding); + if (!Number.isNaN(flags)) { + context3.flags = flags; + } + (_a = this.call) === null || _a === void 0 ? void 0 : _a.sendMessageWithContext(context3, chunk); + } + _final(cb) { + var _a; + (_a = this.call) === null || _a === void 0 ? void 0 : _a.halfClose(); + cb(); + } + }; + exports2.ClientDuplexStreamImpl = ClientDuplexStreamImpl; + } +}); + +// node_modules/@grpc/grpc-js/build/src/call-interface.js +var require_call_interface = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/call-interface.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.InterceptingListenerImpl = void 0; + exports2.statusOrFromValue = statusOrFromValue; + exports2.statusOrFromError = statusOrFromError; + exports2.isInterceptingListener = isInterceptingListener; + var metadata_1 = require_metadata(); + function statusOrFromValue(value) { + return { + ok: true, + value + }; + } + function statusOrFromError(error2) { + var _a; + return { + ok: false, + error: Object.assign(Object.assign({}, error2), { metadata: (_a = error2.metadata) !== null && _a !== void 0 ? _a : new metadata_1.Metadata() }) + }; + } + function isInterceptingListener(listener) { + return listener.onReceiveMetadata !== void 0 && listener.onReceiveMetadata.length === 1; + } + var InterceptingListenerImpl = class { + constructor(listener, nextListener) { + this.listener = listener; + this.nextListener = nextListener; + this.processingMetadata = false; + this.hasPendingMessage = false; + this.processingMessage = false; + this.pendingStatus = null; + } + processPendingMessage() { + if (this.hasPendingMessage) { + this.nextListener.onReceiveMessage(this.pendingMessage); + this.pendingMessage = null; + this.hasPendingMessage = false; + } + } + processPendingStatus() { + if (this.pendingStatus) { + this.nextListener.onReceiveStatus(this.pendingStatus); + } + } + onReceiveMetadata(metadata) { + this.processingMetadata = true; + this.listener.onReceiveMetadata(metadata, (metadata2) => { + this.processingMetadata = false; + this.nextListener.onReceiveMetadata(metadata2); + this.processPendingMessage(); + this.processPendingStatus(); + }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onReceiveMessage(message) { + this.processingMessage = true; + this.listener.onReceiveMessage(message, (msg) => { + this.processingMessage = false; + if (this.processingMetadata) { + this.pendingMessage = msg; + this.hasPendingMessage = true; + } else { + this.nextListener.onReceiveMessage(msg); + this.processPendingStatus(); + } + }); + } + onReceiveStatus(status) { + this.listener.onReceiveStatus(status, (processedStatus) => { + if (this.processingMetadata || this.processingMessage) { + this.pendingStatus = processedStatus; + } else { + this.nextListener.onReceiveStatus(processedStatus); + } + }); + } + }; + exports2.InterceptingListenerImpl = InterceptingListenerImpl; + } +}); + +// node_modules/@grpc/grpc-js/build/src/client-interceptors.js +var require_client_interceptors = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/client-interceptors.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.InterceptingCall = exports2.RequesterBuilder = exports2.ListenerBuilder = exports2.InterceptorConfigurationError = void 0; + exports2.getInterceptingCall = getInterceptingCall; + var metadata_1 = require_metadata(); + var call_interface_1 = require_call_interface(); + var constants_1 = require_constants7(); + var error_1 = require_error(); + var InterceptorConfigurationError = class _InterceptorConfigurationError extends Error { + constructor(message) { + super(message); + this.name = "InterceptorConfigurationError"; + Error.captureStackTrace(this, _InterceptorConfigurationError); + } + }; + exports2.InterceptorConfigurationError = InterceptorConfigurationError; + var ListenerBuilder = class { + constructor() { + this.metadata = void 0; + this.message = void 0; + this.status = void 0; + } + withOnReceiveMetadata(onReceiveMetadata) { + this.metadata = onReceiveMetadata; + return this; + } + withOnReceiveMessage(onReceiveMessage) { + this.message = onReceiveMessage; + return this; + } + withOnReceiveStatus(onReceiveStatus) { + this.status = onReceiveStatus; + return this; + } + build() { + return { + onReceiveMetadata: this.metadata, + onReceiveMessage: this.message, + onReceiveStatus: this.status + }; + } + }; + exports2.ListenerBuilder = ListenerBuilder; + var RequesterBuilder = class { + constructor() { + this.start = void 0; + this.message = void 0; + this.halfClose = void 0; + this.cancel = void 0; + } + withStart(start) { + this.start = start; + return this; + } + withSendMessage(sendMessage) { + this.message = sendMessage; + return this; + } + withHalfClose(halfClose) { + this.halfClose = halfClose; + return this; + } + withCancel(cancel) { + this.cancel = cancel; + return this; + } + build() { + return { + start: this.start, + sendMessage: this.message, + halfClose: this.halfClose, + cancel: this.cancel + }; + } + }; + exports2.RequesterBuilder = RequesterBuilder; + var defaultListener = { + onReceiveMetadata: (metadata, next) => { + next(metadata); + }, + onReceiveMessage: (message, next) => { + next(message); + }, + onReceiveStatus: (status, next) => { + next(status); + } + }; + var defaultRequester = { + start: (metadata, listener, next) => { + next(metadata, listener); + }, + sendMessage: (message, next) => { + next(message); + }, + halfClose: (next) => { + next(); + }, + cancel: (next) => { + next(); + } + }; + var InterceptingCall = class { + constructor(nextCall, requester) { + var _a, _b, _c, _d; + this.nextCall = nextCall; + this.processingMetadata = false; + this.pendingMessageContext = null; + this.processingMessage = false; + this.pendingHalfClose = false; + if (requester) { + this.requester = { + start: (_a = requester.start) !== null && _a !== void 0 ? _a : defaultRequester.start, + sendMessage: (_b = requester.sendMessage) !== null && _b !== void 0 ? _b : defaultRequester.sendMessage, + halfClose: (_c = requester.halfClose) !== null && _c !== void 0 ? _c : defaultRequester.halfClose, + cancel: (_d = requester.cancel) !== null && _d !== void 0 ? _d : defaultRequester.cancel + }; + } else { + this.requester = defaultRequester; + } + } + cancelWithStatus(status, details) { + this.requester.cancel(() => { + this.nextCall.cancelWithStatus(status, details); + }); + } + getPeer() { + return this.nextCall.getPeer(); + } + processPendingMessage() { + if (this.pendingMessageContext) { + this.nextCall.sendMessageWithContext(this.pendingMessageContext, this.pendingMessage); + this.pendingMessageContext = null; + this.pendingMessage = null; + } + } + processPendingHalfClose() { + if (this.pendingHalfClose) { + this.nextCall.halfClose(); + } + } + start(metadata, interceptingListener) { + var _a, _b, _c, _d, _e, _f; + const fullInterceptingListener = { + onReceiveMetadata: (_b = (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMetadata) === null || _a === void 0 ? void 0 : _a.bind(interceptingListener)) !== null && _b !== void 0 ? _b : ((metadata2) => { + }), + onReceiveMessage: (_d = (_c = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMessage) === null || _c === void 0 ? void 0 : _c.bind(interceptingListener)) !== null && _d !== void 0 ? _d : ((message) => { + }), + onReceiveStatus: (_f = (_e = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _e === void 0 ? void 0 : _e.bind(interceptingListener)) !== null && _f !== void 0 ? _f : ((status) => { + }) + }; + this.processingMetadata = true; + this.requester.start(metadata, fullInterceptingListener, (md2, listener) => { + var _a2, _b2, _c2; + this.processingMetadata = false; + let finalInterceptingListener; + if ((0, call_interface_1.isInterceptingListener)(listener)) { + finalInterceptingListener = listener; + } else { + const fullListener = { + onReceiveMetadata: (_a2 = listener.onReceiveMetadata) !== null && _a2 !== void 0 ? _a2 : defaultListener.onReceiveMetadata, + onReceiveMessage: (_b2 = listener.onReceiveMessage) !== null && _b2 !== void 0 ? _b2 : defaultListener.onReceiveMessage, + onReceiveStatus: (_c2 = listener.onReceiveStatus) !== null && _c2 !== void 0 ? _c2 : defaultListener.onReceiveStatus + }; + finalInterceptingListener = new call_interface_1.InterceptingListenerImpl(fullListener, fullInterceptingListener); + } + this.nextCall.start(md2, finalInterceptingListener); + this.processPendingMessage(); + this.processPendingHalfClose(); + }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sendMessageWithContext(context3, message) { + this.processingMessage = true; + this.requester.sendMessage(message, (finalMessage) => { + this.processingMessage = false; + if (this.processingMetadata) { + this.pendingMessageContext = context3; + this.pendingMessage = message; + } else { + this.nextCall.sendMessageWithContext(context3, finalMessage); + this.processPendingHalfClose(); + } + }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sendMessage(message) { + this.sendMessageWithContext({}, message); + } + startRead() { + this.nextCall.startRead(); + } + halfClose() { + this.requester.halfClose(() => { + if (this.processingMetadata || this.processingMessage) { + this.pendingHalfClose = true; + } else { + this.nextCall.halfClose(); + } + }); + } + getAuthContext() { + return this.nextCall.getAuthContext(); + } + }; + exports2.InterceptingCall = InterceptingCall; + function getCall(channel, path, options) { + var _a, _b; + const deadline = (_a = options.deadline) !== null && _a !== void 0 ? _a : Infinity; + const host = options.host; + const parent = (_b = options.parent) !== null && _b !== void 0 ? _b : null; + const propagateFlags = options.propagate_flags; + const credentials = options.credentials; + const call = channel.createCall(path, deadline, host, parent, propagateFlags); + if (credentials) { + call.setCredentials(credentials); + } + return call; + } + var BaseInterceptingCall = class { + constructor(call, methodDefinition) { + this.call = call; + this.methodDefinition = methodDefinition; + } + cancelWithStatus(status, details) { + this.call.cancelWithStatus(status, details); + } + getPeer() { + return this.call.getPeer(); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sendMessageWithContext(context3, message) { + let serialized; + try { + serialized = this.methodDefinition.requestSerialize(message); + } catch (e) { + this.call.cancelWithStatus(constants_1.Status.INTERNAL, `Request message serialization failure: ${(0, error_1.getErrorMessage)(e)}`); + return; + } + this.call.sendMessageWithContext(context3, serialized); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sendMessage(message) { + this.sendMessageWithContext({}, message); + } + start(metadata, interceptingListener) { + let readError = null; + this.call.start(metadata, { + onReceiveMetadata: (metadata2) => { + var _a; + (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMetadata) === null || _a === void 0 ? void 0 : _a.call(interceptingListener, metadata2); + }, + onReceiveMessage: (message) => { + var _a; + let deserialized; + try { + deserialized = this.methodDefinition.responseDeserialize(message); + } catch (e) { + readError = { + code: constants_1.Status.INTERNAL, + details: `Response message parsing error: ${(0, error_1.getErrorMessage)(e)}`, + metadata: new metadata_1.Metadata() + }; + this.call.cancelWithStatus(readError.code, readError.details); + return; + } + (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMessage) === null || _a === void 0 ? void 0 : _a.call(interceptingListener, deserialized); + }, + onReceiveStatus: (status) => { + var _a, _b; + if (readError) { + (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _a === void 0 ? void 0 : _a.call(interceptingListener, readError); + } else { + (_b = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _b === void 0 ? void 0 : _b.call(interceptingListener, status); + } + } + }); + } + startRead() { + this.call.startRead(); + } + halfClose() { + this.call.halfClose(); + } + getAuthContext() { + return this.call.getAuthContext(); + } + }; + var BaseUnaryInterceptingCall = class extends BaseInterceptingCall { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + constructor(call, methodDefinition) { + super(call, methodDefinition); + } + start(metadata, listener) { + var _a, _b; + let receivedMessage = false; + const wrapperListener = { + onReceiveMetadata: (_b = (_a = listener === null || listener === void 0 ? void 0 : listener.onReceiveMetadata) === null || _a === void 0 ? void 0 : _a.bind(listener)) !== null && _b !== void 0 ? _b : ((metadata2) => { + }), + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onReceiveMessage: (message) => { + var _a2; + receivedMessage = true; + (_a2 = listener === null || listener === void 0 ? void 0 : listener.onReceiveMessage) === null || _a2 === void 0 ? void 0 : _a2.call(listener, message); + }, + onReceiveStatus: (status) => { + var _a2, _b2; + if (!receivedMessage) { + (_a2 = listener === null || listener === void 0 ? void 0 : listener.onReceiveMessage) === null || _a2 === void 0 ? void 0 : _a2.call(listener, null); + } + (_b2 = listener === null || listener === void 0 ? void 0 : listener.onReceiveStatus) === null || _b2 === void 0 ? void 0 : _b2.call(listener, status); + } + }; + super.start(metadata, wrapperListener); + this.call.startRead(); + } + }; + var BaseStreamingInterceptingCall = class extends BaseInterceptingCall { + }; + function getBottomInterceptingCall(channel, options, methodDefinition) { + const call = getCall(channel, methodDefinition.path, options); + if (methodDefinition.responseStream) { + return new BaseStreamingInterceptingCall(call, methodDefinition); + } else { + return new BaseUnaryInterceptingCall(call, methodDefinition); + } + } + function getInterceptingCall(interceptorArgs, methodDefinition, options, channel) { + if (interceptorArgs.clientInterceptors.length > 0 && interceptorArgs.clientInterceptorProviders.length > 0) { + throw new InterceptorConfigurationError("Both interceptors and interceptor_providers were passed as options to the client constructor. Only one of these is allowed."); + } + if (interceptorArgs.callInterceptors.length > 0 && interceptorArgs.callInterceptorProviders.length > 0) { + throw new InterceptorConfigurationError("Both interceptors and interceptor_providers were passed as call options. Only one of these is allowed."); + } + let interceptors = []; + if (interceptorArgs.callInterceptors.length > 0 || interceptorArgs.callInterceptorProviders.length > 0) { + interceptors = [].concat(interceptorArgs.callInterceptors, interceptorArgs.callInterceptorProviders.map((provider) => provider(methodDefinition))).filter((interceptor) => interceptor); + } else { + interceptors = [].concat(interceptorArgs.clientInterceptors, interceptorArgs.clientInterceptorProviders.map((provider) => provider(methodDefinition))).filter((interceptor) => interceptor); + } + const interceptorOptions = Object.assign({}, options, { + method_definition: methodDefinition + }); + const getCall2 = interceptors.reduceRight((nextCall, nextInterceptor) => { + return (currentOptions) => nextInterceptor(currentOptions, nextCall); + }, (finalOptions) => getBottomInterceptingCall(channel, finalOptions, methodDefinition)); + return getCall2(interceptorOptions); + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/client.js +var require_client3 = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/client.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Client = void 0; + var call_1 = require_call(); + var channel_1 = require_channel(); + var connectivity_state_1 = require_connectivity_state(); + var constants_1 = require_constants7(); + var metadata_1 = require_metadata(); + var client_interceptors_1 = require_client_interceptors(); + var CHANNEL_SYMBOL = /* @__PURE__ */ Symbol(); + var INTERCEPTOR_SYMBOL = /* @__PURE__ */ Symbol(); + var INTERCEPTOR_PROVIDER_SYMBOL = /* @__PURE__ */ Symbol(); + var CALL_INVOCATION_TRANSFORMER_SYMBOL = /* @__PURE__ */ Symbol(); + function isFunction(arg) { + return typeof arg === "function"; + } + function getErrorStackString(error2) { + var _a; + return ((_a = error2.stack) === null || _a === void 0 ? void 0 : _a.split("\n").slice(1).join("\n")) || "no stack trace available"; + } + var Client = class { + constructor(address, credentials, options = {}) { + var _a, _b; + options = Object.assign({}, options); + this[INTERCEPTOR_SYMBOL] = (_a = options.interceptors) !== null && _a !== void 0 ? _a : []; + delete options.interceptors; + this[INTERCEPTOR_PROVIDER_SYMBOL] = (_b = options.interceptor_providers) !== null && _b !== void 0 ? _b : []; + delete options.interceptor_providers; + if (this[INTERCEPTOR_SYMBOL].length > 0 && this[INTERCEPTOR_PROVIDER_SYMBOL].length > 0) { + throw new Error("Both interceptors and interceptor_providers were passed as options to the client constructor. Only one of these is allowed."); + } + this[CALL_INVOCATION_TRANSFORMER_SYMBOL] = options.callInvocationTransformer; + delete options.callInvocationTransformer; + if (options.channelOverride) { + this[CHANNEL_SYMBOL] = options.channelOverride; + } else if (options.channelFactoryOverride) { + const channelFactoryOverride = options.channelFactoryOverride; + delete options.channelFactoryOverride; + this[CHANNEL_SYMBOL] = channelFactoryOverride(address, credentials, options); + } else { + this[CHANNEL_SYMBOL] = new channel_1.ChannelImplementation(address, credentials, options); + } + } + close() { + this[CHANNEL_SYMBOL].close(); + } + getChannel() { + return this[CHANNEL_SYMBOL]; + } + waitForReady(deadline, callback) { + const checkState = (err) => { + if (err) { + callback(new Error("Failed to connect before the deadline")); + return; + } + let newState; + try { + newState = this[CHANNEL_SYMBOL].getConnectivityState(true); + } catch (e) { + callback(new Error("The channel has been closed")); + return; + } + if (newState === connectivity_state_1.ConnectivityState.READY) { + callback(); + } else { + try { + this[CHANNEL_SYMBOL].watchConnectivityState(newState, deadline, checkState); + } catch (e) { + callback(new Error("The channel has been closed")); + } + } + }; + setImmediate(checkState); + } + checkOptionalUnaryResponseArguments(arg1, arg2, arg3) { + if (isFunction(arg1)) { + return { metadata: new metadata_1.Metadata(), options: {}, callback: arg1 }; + } else if (isFunction(arg2)) { + if (arg1 instanceof metadata_1.Metadata) { + return { metadata: arg1, options: {}, callback: arg2 }; + } else { + return { metadata: new metadata_1.Metadata(), options: arg1, callback: arg2 }; + } + } else { + if (!(arg1 instanceof metadata_1.Metadata && arg2 instanceof Object && isFunction(arg3))) { + throw new Error("Incorrect arguments passed"); + } + return { metadata: arg1, options: arg2, callback: arg3 }; + } + } + makeUnaryRequest(method, serialize, deserialize, argument, metadata, options, callback) { + var _a, _b; + const checkedArguments = this.checkOptionalUnaryResponseArguments(metadata, options, callback); + const methodDefinition = { + path: method, + requestStream: false, + responseStream: false, + requestSerialize: serialize, + responseDeserialize: deserialize + }; + let callProperties = { + argument, + metadata: checkedArguments.metadata, + call: new call_1.ClientUnaryCallImpl(), + channel: this[CHANNEL_SYMBOL], + methodDefinition, + callOptions: checkedArguments.options, + callback: checkedArguments.callback + }; + if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { + callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); + } + const emitter = callProperties.call; + const interceptorArgs = { + clientInterceptors: this[INTERCEPTOR_SYMBOL], + clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], + callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [], + callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [] + }; + const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); + emitter.call = call; + let responseMessage = null; + let receivedStatus = false; + let callerStackError = new Error(); + call.start(callProperties.metadata, { + onReceiveMetadata: (metadata2) => { + emitter.emit("metadata", metadata2); + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onReceiveMessage(message) { + if (responseMessage !== null) { + call.cancelWithStatus(constants_1.Status.UNIMPLEMENTED, "Too many responses received"); + } + responseMessage = message; + }, + onReceiveStatus(status) { + if (receivedStatus) { + return; + } + receivedStatus = true; + if (status.code === constants_1.Status.OK) { + if (responseMessage === null) { + const callerStack = getErrorStackString(callerStackError); + callProperties.callback((0, call_1.callErrorFromStatus)({ + code: constants_1.Status.UNIMPLEMENTED, + details: "No message received", + metadata: status.metadata + }, callerStack)); + } else { + callProperties.callback(null, responseMessage); + } + } else { + const callerStack = getErrorStackString(callerStackError); + callProperties.callback((0, call_1.callErrorFromStatus)(status, callerStack)); + } + callerStackError = null; + emitter.emit("status", status); + } + }); + call.sendMessage(argument); + call.halfClose(); + return emitter; + } + makeClientStreamRequest(method, serialize, deserialize, metadata, options, callback) { + var _a, _b; + const checkedArguments = this.checkOptionalUnaryResponseArguments(metadata, options, callback); + const methodDefinition = { + path: method, + requestStream: true, + responseStream: false, + requestSerialize: serialize, + responseDeserialize: deserialize + }; + let callProperties = { + metadata: checkedArguments.metadata, + call: new call_1.ClientWritableStreamImpl(serialize), + channel: this[CHANNEL_SYMBOL], + methodDefinition, + callOptions: checkedArguments.options, + callback: checkedArguments.callback + }; + if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { + callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); + } + const emitter = callProperties.call; + const interceptorArgs = { + clientInterceptors: this[INTERCEPTOR_SYMBOL], + clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], + callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [], + callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [] + }; + const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); + emitter.call = call; + let responseMessage = null; + let receivedStatus = false; + let callerStackError = new Error(); + call.start(callProperties.metadata, { + onReceiveMetadata: (metadata2) => { + emitter.emit("metadata", metadata2); + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onReceiveMessage(message) { + if (responseMessage !== null) { + call.cancelWithStatus(constants_1.Status.UNIMPLEMENTED, "Too many responses received"); + } + responseMessage = message; + call.startRead(); + }, + onReceiveStatus(status) { + if (receivedStatus) { + return; + } + receivedStatus = true; + if (status.code === constants_1.Status.OK) { + if (responseMessage === null) { + const callerStack = getErrorStackString(callerStackError); + callProperties.callback((0, call_1.callErrorFromStatus)({ + code: constants_1.Status.UNIMPLEMENTED, + details: "No message received", + metadata: status.metadata + }, callerStack)); + } else { + callProperties.callback(null, responseMessage); + } + } else { + const callerStack = getErrorStackString(callerStackError); + callProperties.callback((0, call_1.callErrorFromStatus)(status, callerStack)); + } + callerStackError = null; + emitter.emit("status", status); + } + }); + return emitter; + } + checkMetadataAndOptions(arg1, arg2) { + let metadata; + let options; + if (arg1 instanceof metadata_1.Metadata) { + metadata = arg1; + if (arg2) { + options = arg2; + } else { + options = {}; + } + } else { + if (arg1) { + options = arg1; + } else { + options = {}; + } + metadata = new metadata_1.Metadata(); + } + return { metadata, options }; + } + makeServerStreamRequest(method, serialize, deserialize, argument, metadata, options) { + var _a, _b; + const checkedArguments = this.checkMetadataAndOptions(metadata, options); + const methodDefinition = { + path: method, + requestStream: false, + responseStream: true, + requestSerialize: serialize, + responseDeserialize: deserialize + }; + let callProperties = { + argument, + metadata: checkedArguments.metadata, + call: new call_1.ClientReadableStreamImpl(deserialize), + channel: this[CHANNEL_SYMBOL], + methodDefinition, + callOptions: checkedArguments.options + }; + if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { + callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); + } + const stream2 = callProperties.call; + const interceptorArgs = { + clientInterceptors: this[INTERCEPTOR_SYMBOL], + clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], + callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [], + callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [] + }; + const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); + stream2.call = call; + let receivedStatus = false; + let callerStackError = new Error(); + call.start(callProperties.metadata, { + onReceiveMetadata(metadata2) { + stream2.emit("metadata", metadata2); + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onReceiveMessage(message) { + stream2.push(message); + }, + onReceiveStatus(status) { + if (receivedStatus) { + return; + } + receivedStatus = true; + stream2.push(null); + if (status.code !== constants_1.Status.OK) { + const callerStack = getErrorStackString(callerStackError); + stream2.emit("error", (0, call_1.callErrorFromStatus)(status, callerStack)); + } + callerStackError = null; + stream2.emit("status", status); + } + }); + call.sendMessage(argument); + call.halfClose(); + return stream2; + } + makeBidiStreamRequest(method, serialize, deserialize, metadata, options) { + var _a, _b; + const checkedArguments = this.checkMetadataAndOptions(metadata, options); + const methodDefinition = { + path: method, + requestStream: true, + responseStream: true, + requestSerialize: serialize, + responseDeserialize: deserialize + }; + let callProperties = { + metadata: checkedArguments.metadata, + call: new call_1.ClientDuplexStreamImpl(serialize, deserialize), + channel: this[CHANNEL_SYMBOL], + methodDefinition, + callOptions: checkedArguments.options + }; + if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { + callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); + } + const stream2 = callProperties.call; + const interceptorArgs = { + clientInterceptors: this[INTERCEPTOR_SYMBOL], + clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], + callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [], + callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [] + }; + const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); + stream2.call = call; + let receivedStatus = false; + let callerStackError = new Error(); + call.start(callProperties.metadata, { + onReceiveMetadata(metadata2) { + stream2.emit("metadata", metadata2); + }, + onReceiveMessage(message) { + stream2.push(message); + }, + onReceiveStatus(status) { + if (receivedStatus) { + return; + } + receivedStatus = true; + stream2.push(null); + if (status.code !== constants_1.Status.OK) { + const callerStack = getErrorStackString(callerStackError); + stream2.emit("error", (0, call_1.callErrorFromStatus)(status, callerStack)); + } + callerStackError = null; + stream2.emit("status", status); + } + }); + return stream2; + } + }; + exports2.Client = Client; + } +}); + +// node_modules/@grpc/grpc-js/build/src/make-client.js +var require_make_client = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/make-client.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.makeClientConstructor = makeClientConstructor; + exports2.loadPackageDefinition = loadPackageDefinition; + var client_1 = require_client3(); + var requesterFuncs = { + unary: client_1.Client.prototype.makeUnaryRequest, + server_stream: client_1.Client.prototype.makeServerStreamRequest, + client_stream: client_1.Client.prototype.makeClientStreamRequest, + bidi: client_1.Client.prototype.makeBidiStreamRequest + }; + function isPrototypePolluted(key) { + return ["__proto__", "prototype", "constructor"].includes(key); + } + function makeClientConstructor(methods, serviceName, classOptions) { + if (!classOptions) { + classOptions = {}; + } + class ServiceClientImpl extends client_1.Client { + } + Object.keys(methods).forEach((name) => { + if (isPrototypePolluted(name)) { + return; + } + const attrs = methods[name]; + let methodType; + if (typeof name === "string" && name.charAt(0) === "$") { + throw new Error("Method names cannot start with $"); + } + if (attrs.requestStream) { + if (attrs.responseStream) { + methodType = "bidi"; + } else { + methodType = "client_stream"; + } + } else { + if (attrs.responseStream) { + methodType = "server_stream"; + } else { + methodType = "unary"; + } + } + const serialize = attrs.requestSerialize; + const deserialize = attrs.responseDeserialize; + const methodFunc = partial(requesterFuncs[methodType], attrs.path, serialize, deserialize); + ServiceClientImpl.prototype[name] = methodFunc; + Object.assign(ServiceClientImpl.prototype[name], attrs); + if (attrs.originalName && !isPrototypePolluted(attrs.originalName)) { + ServiceClientImpl.prototype[attrs.originalName] = ServiceClientImpl.prototype[name]; + } + }); + ServiceClientImpl.service = methods; + ServiceClientImpl.serviceName = serviceName; + return ServiceClientImpl; + } + function partial(fn, path, serialize, deserialize) { + return function(...args) { + return fn.call(this, path, serialize, deserialize, ...args); + }; + } + function isProtobufTypeDefinition(obj) { + return "format" in obj; + } + function loadPackageDefinition(packageDef) { + const result = {}; + for (const serviceFqn in packageDef) { + if (Object.prototype.hasOwnProperty.call(packageDef, serviceFqn)) { + const service = packageDef[serviceFqn]; + const nameComponents = serviceFqn.split("."); + if (nameComponents.some((comp) => isPrototypePolluted(comp))) { + continue; + } + const serviceName = nameComponents[nameComponents.length - 1]; + let current = result; + for (const packageName of nameComponents.slice(0, -1)) { + if (!current[packageName]) { + current[packageName] = {}; + } + current = current[packageName]; + } + if (isProtobufTypeDefinition(service)) { + current[serviceName] = service; + } else { + current[serviceName] = makeClientConstructor(service, serviceName, {}); + } + } + } + return result; + } + } +}); + +// node_modules/lodash.camelcase/index.js +var require_lodash = __commonJS({ + "node_modules/lodash.camelcase/index.js"(exports2, module2) { + var INFINITY = 1 / 0; + var symbolTag = "[object Symbol]"; + var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; + var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; + var rsAstralRange = "\\ud800-\\udfff"; + var rsComboMarksRange = "\\u0300-\\u036f\\ufe20-\\ufe23"; + var rsComboSymbolsRange = "\\u20d0-\\u20f0"; + var rsDingbatRange = "\\u2700-\\u27bf"; + var rsLowerRange = "a-z\\xdf-\\xf6\\xf8-\\xff"; + var rsMathOpRange = "\\xac\\xb1\\xd7\\xf7"; + var rsNonCharRange = "\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf"; + var rsPunctuationRange = "\\u2000-\\u206f"; + var rsSpaceRange = " \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000"; + var rsUpperRange = "A-Z\\xc0-\\xd6\\xd8-\\xde"; + var rsVarRange = "\\ufe0e\\ufe0f"; + var rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; + var rsApos = "['\u2019]"; + var rsAstral = "[" + rsAstralRange + "]"; + var rsBreak = "[" + rsBreakRange + "]"; + var rsCombo = "[" + rsComboMarksRange + rsComboSymbolsRange + "]"; + var rsDigits = "\\d+"; + var rsDingbat = "[" + rsDingbatRange + "]"; + var rsLower = "[" + rsLowerRange + "]"; + var rsMisc = "[^" + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + "]"; + var rsFitz = "\\ud83c[\\udffb-\\udfff]"; + var rsModifier = "(?:" + rsCombo + "|" + rsFitz + ")"; + var rsNonAstral = "[^" + rsAstralRange + "]"; + var rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}"; + var rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]"; + var rsUpper = "[" + rsUpperRange + "]"; + var rsZWJ = "\\u200d"; + var rsLowerMisc = "(?:" + rsLower + "|" + rsMisc + ")"; + var rsUpperMisc = "(?:" + rsUpper + "|" + rsMisc + ")"; + var rsOptLowerContr = "(?:" + rsApos + "(?:d|ll|m|re|s|t|ve))?"; + var rsOptUpperContr = "(?:" + rsApos + "(?:D|LL|M|RE|S|T|VE))?"; + var reOptMod = rsModifier + "?"; + var rsOptVar = "[" + rsVarRange + "]?"; + var rsOptJoin = "(?:" + rsZWJ + "(?:" + [rsNonAstral, rsRegional, rsSurrPair].join("|") + ")" + rsOptVar + reOptMod + ")*"; + var rsSeq = rsOptVar + reOptMod + rsOptJoin; + var rsEmoji = "(?:" + [rsDingbat, rsRegional, rsSurrPair].join("|") + ")" + rsSeq; + var rsSymbol = "(?:" + [rsNonAstral + rsCombo + "?", rsCombo, rsRegional, rsSurrPair, rsAstral].join("|") + ")"; + var reApos = RegExp(rsApos, "g"); + var reComboMark = RegExp(rsCombo, "g"); + var reUnicode = RegExp(rsFitz + "(?=" + rsFitz + ")|" + rsSymbol + rsSeq, "g"); + var reUnicodeWord = RegExp([ + rsUpper + "?" + rsLower + "+" + rsOptLowerContr + "(?=" + [rsBreak, rsUpper, "$"].join("|") + ")", + rsUpperMisc + "+" + rsOptUpperContr + "(?=" + [rsBreak, rsUpper + rsLowerMisc, "$"].join("|") + ")", + rsUpper + "?" + rsLowerMisc + "+" + rsOptLowerContr, + rsUpper + "+" + rsOptUpperContr, + rsDigits, + rsEmoji + ].join("|"), "g"); + var reHasUnicode = RegExp("[" + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + "]"); + var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; + var deburredLetters = { + // Latin-1 Supplement block. + "\xC0": "A", + "\xC1": "A", + "\xC2": "A", + "\xC3": "A", + "\xC4": "A", + "\xC5": "A", + "\xE0": "a", + "\xE1": "a", + "\xE2": "a", + "\xE3": "a", + "\xE4": "a", + "\xE5": "a", + "\xC7": "C", + "\xE7": "c", + "\xD0": "D", + "\xF0": "d", + "\xC8": "E", + "\xC9": "E", + "\xCA": "E", + "\xCB": "E", + "\xE8": "e", + "\xE9": "e", + "\xEA": "e", + "\xEB": "e", + "\xCC": "I", + "\xCD": "I", + "\xCE": "I", + "\xCF": "I", + "\xEC": "i", + "\xED": "i", + "\xEE": "i", + "\xEF": "i", + "\xD1": "N", + "\xF1": "n", + "\xD2": "O", + "\xD3": "O", + "\xD4": "O", + "\xD5": "O", + "\xD6": "O", + "\xD8": "O", + "\xF2": "o", + "\xF3": "o", + "\xF4": "o", + "\xF5": "o", + "\xF6": "o", + "\xF8": "o", + "\xD9": "U", + "\xDA": "U", + "\xDB": "U", + "\xDC": "U", + "\xF9": "u", + "\xFA": "u", + "\xFB": "u", + "\xFC": "u", + "\xDD": "Y", + "\xFD": "y", + "\xFF": "y", + "\xC6": "Ae", + "\xE6": "ae", + "\xDE": "Th", + "\xFE": "th", + "\xDF": "ss", + // Latin Extended-A block. + "\u0100": "A", + "\u0102": "A", + "\u0104": "A", + "\u0101": "a", + "\u0103": "a", + "\u0105": "a", + "\u0106": "C", + "\u0108": "C", + "\u010A": "C", + "\u010C": "C", + "\u0107": "c", + "\u0109": "c", + "\u010B": "c", + "\u010D": "c", + "\u010E": "D", + "\u0110": "D", + "\u010F": "d", + "\u0111": "d", + "\u0112": "E", + "\u0114": "E", + "\u0116": "E", + "\u0118": "E", + "\u011A": "E", + "\u0113": "e", + "\u0115": "e", + "\u0117": "e", + "\u0119": "e", + "\u011B": "e", + "\u011C": "G", + "\u011E": "G", + "\u0120": "G", + "\u0122": "G", + "\u011D": "g", + "\u011F": "g", + "\u0121": "g", + "\u0123": "g", + "\u0124": "H", + "\u0126": "H", + "\u0125": "h", + "\u0127": "h", + "\u0128": "I", + "\u012A": "I", + "\u012C": "I", + "\u012E": "I", + "\u0130": "I", + "\u0129": "i", + "\u012B": "i", + "\u012D": "i", + "\u012F": "i", + "\u0131": "i", + "\u0134": "J", + "\u0135": "j", + "\u0136": "K", + "\u0137": "k", + "\u0138": "k", + "\u0139": "L", + "\u013B": "L", + "\u013D": "L", + "\u013F": "L", + "\u0141": "L", + "\u013A": "l", + "\u013C": "l", + "\u013E": "l", + "\u0140": "l", + "\u0142": "l", + "\u0143": "N", + "\u0145": "N", + "\u0147": "N", + "\u014A": "N", + "\u0144": "n", + "\u0146": "n", + "\u0148": "n", + "\u014B": "n", + "\u014C": "O", + "\u014E": "O", + "\u0150": "O", + "\u014D": "o", + "\u014F": "o", + "\u0151": "o", + "\u0154": "R", + "\u0156": "R", + "\u0158": "R", + "\u0155": "r", + "\u0157": "r", + "\u0159": "r", + "\u015A": "S", + "\u015C": "S", + "\u015E": "S", + "\u0160": "S", + "\u015B": "s", + "\u015D": "s", + "\u015F": "s", + "\u0161": "s", + "\u0162": "T", + "\u0164": "T", + "\u0166": "T", + "\u0163": "t", + "\u0165": "t", + "\u0167": "t", + "\u0168": "U", + "\u016A": "U", + "\u016C": "U", + "\u016E": "U", + "\u0170": "U", + "\u0172": "U", + "\u0169": "u", + "\u016B": "u", + "\u016D": "u", + "\u016F": "u", + "\u0171": "u", + "\u0173": "u", + "\u0174": "W", + "\u0175": "w", + "\u0176": "Y", + "\u0177": "y", + "\u0178": "Y", + "\u0179": "Z", + "\u017B": "Z", + "\u017D": "Z", + "\u017A": "z", + "\u017C": "z", + "\u017E": "z", + "\u0132": "IJ", + "\u0133": "ij", + "\u0152": "Oe", + "\u0153": "oe", + "\u0149": "'n", + "\u017F": "ss" + }; + var freeGlobal = typeof global == "object" && global && global.Object === Object && global; + var freeSelf = typeof self == "object" && self && self.Object === Object && self; + var root = freeGlobal || freeSelf || Function("return this")(); + function arrayReduce(array, iteratee, accumulator, initAccum) { + var index = -1, length = array ? array.length : 0; + if (initAccum && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); + } + return accumulator; + } + function asciiToArray(string) { + return string.split(""); + } + function asciiWords(string) { + return string.match(reAsciiWord) || []; + } + function basePropertyOf(object) { + return function(key) { + return object == null ? void 0 : object[key]; + }; + } + var deburrLetter = basePropertyOf(deburredLetters); + function hasUnicode(string) { + return reHasUnicode.test(string); + } + function hasUnicodeWord(string) { + return reHasUnicodeWord.test(string); + } + function stringToArray(string) { + return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string); + } + function unicodeToArray(string) { + return string.match(reUnicode) || []; + } + function unicodeWords(string) { + return string.match(reUnicodeWord) || []; + } + var objectProto = Object.prototype; + var objectToString = objectProto.toString; + var Symbol2 = root.Symbol; + var symbolProto = Symbol2 ? Symbol2.prototype : void 0; + var symbolToString = symbolProto ? symbolProto.toString : void 0; + function baseSlice(array, start, end) { + var index = -1, length = array.length; + if (start < 0) { + start = -start > length ? 0 : length + start; + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : end - start >>> 0; + start >>>= 0; + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; + } + function baseToString(value) { + if (typeof value == "string") { + return value; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ""; + } + var result = value + ""; + return result == "0" && 1 / value == -INFINITY ? "-0" : result; + } + function castSlice(array, start, end) { + var length = array.length; + end = end === void 0 ? length : end; + return !start && end >= length ? array : baseSlice(array, start, end); + } + function createCaseFirst(methodName) { + return function(string) { + string = toString(string); + var strSymbols = hasUnicode(string) ? stringToArray(string) : void 0; + var chr = strSymbols ? strSymbols[0] : string.charAt(0); + var trailing = strSymbols ? castSlice(strSymbols, 1).join("") : string.slice(1); + return chr[methodName]() + trailing; + }; + } + function createCompounder(callback) { + return function(string) { + return arrayReduce(words(deburr(string).replace(reApos, "")), callback, ""); + }; + } + function isObjectLike(value) { + return !!value && typeof value == "object"; + } + function isSymbol(value) { + return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag; + } + function toString(value) { + return value == null ? "" : baseToString(value); + } + var camelCase = createCompounder(function(result, word, index) { + word = word.toLowerCase(); + return result + (index ? capitalize(word) : word); + }); + function capitalize(string) { + return upperFirst(toString(string).toLowerCase()); + } + function deburr(string) { + string = toString(string); + return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ""); + } + var upperFirst = createCaseFirst("toUpperCase"); + function words(string, pattern, guard) { + string = toString(string); + pattern = guard ? void 0 : pattern; + if (pattern === void 0) { + return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string); + } + return string.match(pattern) || []; + } + module2.exports = camelCase; + } +}); + +// node_modules/@protobufjs/aspromise/index.js +var require_aspromise = __commonJS({ + "node_modules/@protobufjs/aspromise/index.js"(exports2, module2) { + "use strict"; + module2.exports = asPromise; + function asPromise(fn, ctx) { + var params = new Array(arguments.length - 1), offset = 0, index = 2, pending = true; + while (index < arguments.length) + params[offset++] = arguments[index++]; + return new Promise(function executor(resolve, reject) { + params[offset] = function callback(err) { + if (pending) { + pending = false; + if (err) + reject(err); + else { + var params2 = new Array(arguments.length - 1), offset2 = 0; + while (offset2 < params2.length) + params2[offset2++] = arguments[offset2]; + resolve.apply(null, params2); + } + } + }; + try { + fn.apply(ctx || null, params); + } catch (err) { + if (pending) { + pending = false; + reject(err); + } + } + }); + } + } +}); + +// node_modules/@protobufjs/base64/index.js +var require_base64 = __commonJS({ + "node_modules/@protobufjs/base64/index.js"(exports2) { + "use strict"; + var base64 = exports2; + base64.length = function length(string) { + var p = string.length; + if (!p) + return 0; + var n = 0; + while (--p % 4 > 1 && string.charAt(p) === "=") + ++n; + return Math.ceil(string.length * 3) / 4 - n; + }; + var b64 = new Array(64); + var s64 = new Array(123); + for (i = 0; i < 64; ) + s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++; + var i; + base64.encode = function encode(buffer, start, end) { + var parts = null, chunk = []; + var i2 = 0, j = 0, t; + while (start < end) { + var b = buffer[start++]; + switch (j) { + case 0: + chunk[i2++] = b64[b >> 2]; + t = (b & 3) << 4; + j = 1; + break; + case 1: + chunk[i2++] = b64[t | b >> 4]; + t = (b & 15) << 2; + j = 2; + break; + case 2: + chunk[i2++] = b64[t | b >> 6]; + chunk[i2++] = b64[b & 63]; + j = 0; + break; + } + if (i2 > 8191) { + (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); + i2 = 0; + } + } + if (j) { + chunk[i2++] = b64[t]; + chunk[i2++] = 61; + if (j === 1) + chunk[i2++] = 61; + } + if (parts) { + if (i2) + parts.push(String.fromCharCode.apply(String, chunk.slice(0, i2))); + return parts.join(""); + } + return String.fromCharCode.apply(String, chunk.slice(0, i2)); + }; + var invalidEncoding = "invalid encoding"; + base64.decode = function decode(string, buffer, offset) { + var start = offset; + var j = 0, t; + for (var i2 = 0; i2 < string.length; ) { + var c = string.charCodeAt(i2++); + if (c === 61 && j > 1) + break; + if ((c = s64[c]) === void 0) + throw Error(invalidEncoding); + switch (j) { + case 0: + t = c; + j = 1; + break; + case 1: + buffer[offset++] = t << 2 | (c & 48) >> 4; + t = c; + j = 2; + break; + case 2: + buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2; + t = c; + j = 3; + break; + case 3: + buffer[offset++] = (t & 3) << 6 | c; + j = 0; + break; + } + } + if (j === 1) + throw Error(invalidEncoding); + return offset - start; + }; + base64.test = function test(string) { + return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string); + }; + } +}); + +// node_modules/@protobufjs/eventemitter/index.js +var require_eventemitter = __commonJS({ + "node_modules/@protobufjs/eventemitter/index.js"(exports2, module2) { + "use strict"; + module2.exports = EventEmitter; + function EventEmitter() { + this._listeners = {}; + } + EventEmitter.prototype.on = function on(evt, fn, ctx) { + (this._listeners[evt] || (this._listeners[evt] = [])).push({ + fn, + ctx: ctx || this + }); + return this; + }; + EventEmitter.prototype.off = function off(evt, fn) { + if (evt === void 0) + this._listeners = {}; + else { + if (fn === void 0) + this._listeners[evt] = []; + else { + var listeners = this._listeners[evt]; + for (var i = 0; i < listeners.length; ) + if (listeners[i].fn === fn) + listeners.splice(i, 1); + else + ++i; + } + } + return this; + }; + EventEmitter.prototype.emit = function emit(evt) { + var listeners = this._listeners[evt]; + if (listeners) { + var args = [], i = 1; + for (; i < arguments.length; ) + args.push(arguments[i++]); + for (i = 0; i < listeners.length; ) + listeners[i].fn.apply(listeners[i++].ctx, args); + } + return this; + }; + } +}); + +// node_modules/@protobufjs/float/index.js +var require_float = __commonJS({ + "node_modules/@protobufjs/float/index.js"(exports2, module2) { + "use strict"; + module2.exports = factory(factory); + function factory(exports3) { + if (typeof Float32Array !== "undefined") (function() { + var f32 = new Float32Array([-0]), f8b = new Uint8Array(f32.buffer), le = f8b[3] === 128; + function writeFloat_f32_cpy(val, buf, pos) { + f32[0] = val; + buf[pos] = f8b[0]; + buf[pos + 1] = f8b[1]; + buf[pos + 2] = f8b[2]; + buf[pos + 3] = f8b[3]; + } + function writeFloat_f32_rev(val, buf, pos) { + f32[0] = val; + buf[pos] = f8b[3]; + buf[pos + 1] = f8b[2]; + buf[pos + 2] = f8b[1]; + buf[pos + 3] = f8b[0]; + } + exports3.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev; + exports3.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy; + function readFloat_f32_cpy(buf, pos) { + f8b[0] = buf[pos]; + f8b[1] = buf[pos + 1]; + f8b[2] = buf[pos + 2]; + f8b[3] = buf[pos + 3]; + return f32[0]; + } + function readFloat_f32_rev(buf, pos) { + f8b[3] = buf[pos]; + f8b[2] = buf[pos + 1]; + f8b[1] = buf[pos + 2]; + f8b[0] = buf[pos + 3]; + return f32[0]; + } + exports3.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev; + exports3.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy; + })(); + else (function() { + function writeFloat_ieee754(writeUint, val, buf, pos) { + var sign = val < 0 ? 1 : 0; + if (sign) + val = -val; + if (val === 0) + writeUint(1 / val > 0 ? ( + /* positive */ + 0 + ) : ( + /* negative 0 */ + 2147483648 + ), buf, pos); + else if (isNaN(val)) + writeUint(2143289344, buf, pos); + else if (val > 34028234663852886e22) + writeUint((sign << 31 | 2139095040) >>> 0, buf, pos); + else if (val < 11754943508222875e-54) + writeUint((sign << 31 | Math.round(val / 1401298464324817e-60)) >>> 0, buf, pos); + else { + var exponent = Math.floor(Math.log(val) / Math.LN2), mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607; + writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos); + } + } + exports3.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE); + exports3.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE); + function readFloat_ieee754(readUint, buf, pos) { + var uint = readUint(buf, pos), sign = (uint >> 31) * 2 + 1, exponent = uint >>> 23 & 255, mantissa = uint & 8388607; + return exponent === 255 ? mantissa ? NaN : sign * Infinity : exponent === 0 ? sign * 1401298464324817e-60 * mantissa : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608); + } + exports3.readFloatLE = readFloat_ieee754.bind(null, readUintLE); + exports3.readFloatBE = readFloat_ieee754.bind(null, readUintBE); + })(); + if (typeof Float64Array !== "undefined") (function() { + var f64 = new Float64Array([-0]), f8b = new Uint8Array(f64.buffer), le = f8b[7] === 128; + function writeDouble_f64_cpy(val, buf, pos) { + f64[0] = val; + buf[pos] = f8b[0]; + buf[pos + 1] = f8b[1]; + buf[pos + 2] = f8b[2]; + buf[pos + 3] = f8b[3]; + buf[pos + 4] = f8b[4]; + buf[pos + 5] = f8b[5]; + buf[pos + 6] = f8b[6]; + buf[pos + 7] = f8b[7]; + } + function writeDouble_f64_rev(val, buf, pos) { + f64[0] = val; + buf[pos] = f8b[7]; + buf[pos + 1] = f8b[6]; + buf[pos + 2] = f8b[5]; + buf[pos + 3] = f8b[4]; + buf[pos + 4] = f8b[3]; + buf[pos + 5] = f8b[2]; + buf[pos + 6] = f8b[1]; + buf[pos + 7] = f8b[0]; + } + exports3.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev; + exports3.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy; + function readDouble_f64_cpy(buf, pos) { + f8b[0] = buf[pos]; + f8b[1] = buf[pos + 1]; + f8b[2] = buf[pos + 2]; + f8b[3] = buf[pos + 3]; + f8b[4] = buf[pos + 4]; + f8b[5] = buf[pos + 5]; + f8b[6] = buf[pos + 6]; + f8b[7] = buf[pos + 7]; + return f64[0]; + } + function readDouble_f64_rev(buf, pos) { + f8b[7] = buf[pos]; + f8b[6] = buf[pos + 1]; + f8b[5] = buf[pos + 2]; + f8b[4] = buf[pos + 3]; + f8b[3] = buf[pos + 4]; + f8b[2] = buf[pos + 5]; + f8b[1] = buf[pos + 6]; + f8b[0] = buf[pos + 7]; + return f64[0]; + } + exports3.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev; + exports3.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy; + })(); + else (function() { + function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) { + var sign = val < 0 ? 1 : 0; + if (sign) + val = -val; + if (val === 0) { + writeUint(0, buf, pos + off0); + writeUint(1 / val > 0 ? ( + /* positive */ + 0 + ) : ( + /* negative 0 */ + 2147483648 + ), buf, pos + off1); + } else if (isNaN(val)) { + writeUint(0, buf, pos + off0); + writeUint(2146959360, buf, pos + off1); + } else if (val > 17976931348623157e292) { + writeUint(0, buf, pos + off0); + writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1); + } else { + var mantissa; + if (val < 22250738585072014e-324) { + mantissa = val / 5e-324; + writeUint(mantissa >>> 0, buf, pos + off0); + writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1); + } else { + var exponent = Math.floor(Math.log(val) / Math.LN2); + if (exponent === 1024) + exponent = 1023; + mantissa = val * Math.pow(2, -exponent); + writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0); + writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1); + } + } + } + exports3.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4); + exports3.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0); + function readDouble_ieee754(readUint, off0, off1, buf, pos) { + var lo = readUint(buf, pos + off0), hi = readUint(buf, pos + off1); + var sign = (hi >> 31) * 2 + 1, exponent = hi >>> 20 & 2047, mantissa = 4294967296 * (hi & 1048575) + lo; + return exponent === 2047 ? mantissa ? NaN : sign * Infinity : exponent === 0 ? sign * 5e-324 * mantissa : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496); + } + exports3.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4); + exports3.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0); + })(); + return exports3; + } + function writeUintLE(val, buf, pos) { + buf[pos] = val & 255; + buf[pos + 1] = val >>> 8 & 255; + buf[pos + 2] = val >>> 16 & 255; + buf[pos + 3] = val >>> 24; + } + function writeUintBE(val, buf, pos) { + buf[pos] = val >>> 24; + buf[pos + 1] = val >>> 16 & 255; + buf[pos + 2] = val >>> 8 & 255; + buf[pos + 3] = val & 255; + } + function readUintLE(buf, pos) { + return (buf[pos] | buf[pos + 1] << 8 | buf[pos + 2] << 16 | buf[pos + 3] << 24) >>> 0; + } + function readUintBE(buf, pos) { + return (buf[pos] << 24 | buf[pos + 1] << 16 | buf[pos + 2] << 8 | buf[pos + 3]) >>> 0; + } + } +}); + +// node_modules/@protobufjs/inquire/index.js +var require_inquire = __commonJS({ + "node_modules/@protobufjs/inquire/index.js"(exports2, module2) { + "use strict"; + module2.exports = inquire; + function inquire(moduleName) { + try { + if (typeof require !== "function") { + return null; + } + var mod = require(moduleName); + if (mod && (mod.length || Object.keys(mod).length)) return mod; + return null; + } catch (err) { + return null; + } + } + } +}); + +// node_modules/@protobufjs/utf8/index.js +var require_utf8 = __commonJS({ + "node_modules/@protobufjs/utf8/index.js"(exports2) { + "use strict"; + var utf8 = exports2; + var replacementChar = "\uFFFD"; + utf8.length = function utf8_length(string) { + var len = 0, c = 0; + for (var i = 0; i < string.length; ++i) { + c = string.charCodeAt(i); + if (c < 128) + len += 1; + else if (c < 2048) + len += 2; + else if ((c & 64512) === 55296 && (string.charCodeAt(i + 1) & 64512) === 56320) { + ++i; + len += 4; + } else + len += 3; + } + return len; + }; + utf8.read = function utf8_read(buffer, start, end) { + if (end - start < 1) { + return ""; + } + var str = ""; + for (var i = start; i < end; ) { + var t = buffer[i++]; + if (t <= 127) { + str += String.fromCharCode(t); + } else if (t >= 192 && t < 224) { + var c2 = (t & 31) << 6 | buffer[i++] & 63; + str += c2 >= 128 ? String.fromCharCode(c2) : replacementChar; + } else if (t >= 224 && t < 240) { + var c3 = (t & 15) << 12 | (buffer[i++] & 63) << 6 | buffer[i++] & 63; + str += c3 >= 2048 ? String.fromCharCode(c3) : replacementChar; + } else if (t >= 240) { + var t2 = (t & 7) << 18 | (buffer[i++] & 63) << 12 | (buffer[i++] & 63) << 6 | buffer[i++] & 63; + if (t2 < 65536 || t2 > 1114111) + str += replacementChar; + else { + t2 -= 65536; + str += String.fromCharCode(55296 + (t2 >> 10)); + str += String.fromCharCode(56320 + (t2 & 1023)); + } + } + } + return str; + }; + utf8.write = function utf8_write(string, buffer, offset) { + var start = offset, c1, c2; + for (var i = 0; i < string.length; ++i) { + c1 = string.charCodeAt(i); + if (c1 < 128) { + buffer[offset++] = c1; + } else if (c1 < 2048) { + buffer[offset++] = c1 >> 6 | 192; + buffer[offset++] = c1 & 63 | 128; + } else if ((c1 & 64512) === 55296 && ((c2 = string.charCodeAt(i + 1)) & 64512) === 56320) { + c1 = 65536 + ((c1 & 1023) << 10) + (c2 & 1023); + ++i; + buffer[offset++] = c1 >> 18 | 240; + buffer[offset++] = c1 >> 12 & 63 | 128; + buffer[offset++] = c1 >> 6 & 63 | 128; + buffer[offset++] = c1 & 63 | 128; + } else { + buffer[offset++] = c1 >> 12 | 224; + buffer[offset++] = c1 >> 6 & 63 | 128; + buffer[offset++] = c1 & 63 | 128; + } + } + return offset - start; + }; + } +}); + +// node_modules/@protobufjs/pool/index.js +var require_pool2 = __commonJS({ + "node_modules/@protobufjs/pool/index.js"(exports2, module2) { + "use strict"; + module2.exports = pool; + function pool(alloc, slice, size) { + var SIZE = size || 8192; + var MAX = SIZE >>> 1; + var slab = null; + var offset = SIZE; + return function pool_alloc(size2) { + if (size2 < 1 || size2 > MAX) + return alloc(size2); + if (offset + size2 > SIZE) { + slab = alloc(SIZE); + offset = 0; + } + var buf = slice.call(slab, offset, offset += size2); + if (offset & 7) + offset = (offset | 7) + 1; + return buf; + }; + } + } +}); + +// node_modules/protobufjs/src/util/longbits.js +var require_longbits = __commonJS({ + "node_modules/protobufjs/src/util/longbits.js"(exports2, module2) { + "use strict"; + module2.exports = LongBits; + var util = require_minimal(); + function LongBits(lo, hi) { + this.lo = lo >>> 0; + this.hi = hi >>> 0; + } + var zero = LongBits.zero = new LongBits(0, 0); + zero.toNumber = function() { + return 0; + }; + zero.zzEncode = zero.zzDecode = function() { + return this; + }; + zero.length = function() { + return 1; + }; + var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0"; + LongBits.fromNumber = function fromNumber(value) { + if (value === 0) + return zero; + var sign = value < 0; + if (sign) + value = -value; + var lo = value >>> 0, hi = (value - lo) / 4294967296 >>> 0; + if (sign) { + hi = ~hi >>> 0; + lo = ~lo >>> 0; + if (++lo > 4294967295) { + lo = 0; + if (++hi > 4294967295) + hi = 0; + } + } + return new LongBits(lo, hi); + }; + LongBits.from = function from(value) { + if (typeof value === "number") + return LongBits.fromNumber(value); + if (util.isString(value)) { + if (util.Long) + value = util.Long.fromString(value); + else + return LongBits.fromNumber(parseInt(value, 10)); + } + return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero; + }; + LongBits.prototype.toNumber = function toNumber(unsigned) { + if (!unsigned && this.hi >>> 31) { + var lo = ~this.lo + 1 >>> 0, hi = ~this.hi >>> 0; + if (!lo) + hi = hi + 1 >>> 0; + return -(lo + hi * 4294967296); + } + return this.lo + this.hi * 4294967296; + }; + LongBits.prototype.toLong = function toLong(unsigned) { + return util.Long ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned)) : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) }; + }; + var charCodeAt = String.prototype.charCodeAt; + LongBits.fromHash = function fromHash(hash) { + if (hash === zeroHash) + return zero; + return new LongBits( + (charCodeAt.call(hash, 0) | charCodeAt.call(hash, 1) << 8 | charCodeAt.call(hash, 2) << 16 | charCodeAt.call(hash, 3) << 24) >>> 0, + (charCodeAt.call(hash, 4) | charCodeAt.call(hash, 5) << 8 | charCodeAt.call(hash, 6) << 16 | charCodeAt.call(hash, 7) << 24) >>> 0 + ); + }; + LongBits.prototype.toHash = function toHash() { + return String.fromCharCode( + this.lo & 255, + this.lo >>> 8 & 255, + this.lo >>> 16 & 255, + this.lo >>> 24, + this.hi & 255, + this.hi >>> 8 & 255, + this.hi >>> 16 & 255, + this.hi >>> 24 + ); + }; + LongBits.prototype.zzEncode = function zzEncode() { + var mask = this.hi >> 31; + this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0; + this.lo = (this.lo << 1 ^ mask) >>> 0; + return this; + }; + LongBits.prototype.zzDecode = function zzDecode() { + var mask = -(this.lo & 1); + this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0; + this.hi = (this.hi >>> 1 ^ mask) >>> 0; + return this; + }; + LongBits.prototype.length = function length() { + var part0 = this.lo, part1 = (this.lo >>> 28 | this.hi << 4) >>> 0, part2 = this.hi >>> 24; + return part2 === 0 ? part1 === 0 ? part0 < 16384 ? part0 < 128 ? 1 : 2 : part0 < 2097152 ? 3 : 4 : part1 < 16384 ? part1 < 128 ? 5 : 6 : part1 < 2097152 ? 7 : 8 : part2 < 128 ? 9 : 10; + }; + } +}); + +// node_modules/protobufjs/src/util/minimal.js +var require_minimal = __commonJS({ + "node_modules/protobufjs/src/util/minimal.js"(exports2) { + "use strict"; + var util = exports2; + util.asPromise = require_aspromise(); + util.base64 = require_base64(); + util.EventEmitter = require_eventemitter(); + util.float = require_float(); + util.inquire = require_inquire(); + util.utf8 = require_utf8(); + util.pool = require_pool2(); + util.LongBits = require_longbits(); + util.isNode = Boolean(typeof global !== "undefined" && global && global.process && global.process.versions && global.process.versions.node); + util.global = util.isNode && global || typeof window !== "undefined" && window || typeof self !== "undefined" && self || exports2; + util.emptyArray = Object.freeze ? Object.freeze([]) : ( + /* istanbul ignore next */ + [] + ); + util.emptyObject = Object.freeze ? Object.freeze({}) : ( + /* istanbul ignore next */ + {} + ); + util.isInteger = Number.isInteger || /* istanbul ignore next */ + function isInteger(value) { + return typeof value === "number" && isFinite(value) && Math.floor(value) === value; + }; + util.isString = function isString(value) { + return typeof value === "string" || value instanceof String; + }; + util.isObject = function isObject(value) { + return value && typeof value === "object"; + }; + util.isset = /** + * Checks if a property on a message is considered to be present. + * @param {Object} obj Plain object or message instance + * @param {string} prop Property name + * @returns {boolean} `true` if considered to be present, otherwise `false` + */ + util.isSet = function isSet(obj, prop) { + var value = obj[prop]; + if (value != null && obj.hasOwnProperty(prop)) + return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0; + return false; + }; + util.Buffer = (function() { + try { + var Buffer2 = util.inquire("buffer").Buffer; + return Buffer2.prototype.utf8Write ? Buffer2 : ( + /* istanbul ignore next */ + null + ); + } catch (e) { + return null; + } + })(); + util._Buffer_from = null; + util._Buffer_allocUnsafe = null; + util.newBuffer = function newBuffer(sizeOrArray) { + return typeof sizeOrArray === "number" ? util.Buffer ? util._Buffer_allocUnsafe(sizeOrArray) : new util.Array(sizeOrArray) : util.Buffer ? util._Buffer_from(sizeOrArray) : typeof Uint8Array === "undefined" ? sizeOrArray : new Uint8Array(sizeOrArray); + }; + util.Array = typeof Uint8Array !== "undefined" ? Uint8Array : Array; + util.Long = /* istanbul ignore next */ + util.global.dcodeIO && /* istanbul ignore next */ + util.global.dcodeIO.Long || /* istanbul ignore next */ + util.global.Long || util.inquire("long"); + util.key2Re = /^true|false|0|1$/; + util.key32Re = /^-?(?:0|[1-9][0-9]*)$/; + util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/; + util.longToHash = function longToHash(value) { + return value ? util.LongBits.from(value).toHash() : util.LongBits.zeroHash; + }; + util.longFromHash = function longFromHash(hash, unsigned) { + var bits = util.LongBits.fromHash(hash); + if (util.Long) + return util.Long.fromBits(bits.lo, bits.hi, unsigned); + return bits.toNumber(Boolean(unsigned)); + }; + function merge2(dst, src, ifNotSet) { + for (var keys = Object.keys(src), i = 0; i < keys.length; ++i) + if (dst[keys[i]] === void 0 || !ifNotSet) { + if (keys[i] !== "__proto__") + dst[keys[i]] = src[keys[i]]; + } + return dst; + } + util.merge = merge2; + util.recursionLimit = 100; + util.makeProp = function makeProp(obj, key) { + Object.defineProperty(obj, key, { + enumerable: true, + configurable: true, + writable: true + }); + }; + util.lcFirst = function lcFirst(str) { + return str.charAt(0).toLowerCase() + str.substring(1); + }; + function newError(name) { + function CustomError(message, properties) { + if (!(this instanceof CustomError)) + return new CustomError(message, properties); + Object.defineProperty(this, "message", { get: function() { + return message; + } }); + if (Error.captureStackTrace) + Error.captureStackTrace(this, CustomError); + else + Object.defineProperty(this, "stack", { value: new Error().stack || "" }); + if (properties) + merge2(this, properties); + } + CustomError.prototype = Object.create(Error.prototype, { + constructor: { + value: CustomError, + writable: true, + enumerable: false, + configurable: true + }, + name: { + get: function get() { + return name; + }, + set: void 0, + enumerable: false, + // configurable: false would accurately preserve the behavior of + // the original, but I'm guessing that was not intentional. + // For an actual error subclass, this property would + // be configurable. + configurable: true + }, + toString: { + value: function value() { + return this.name + ": " + this.message; + }, + writable: true, + enumerable: false, + configurable: true + } + }); + return CustomError; + } + util.newError = newError; + util.ProtocolError = newError("ProtocolError"); + util.oneOfGetter = function getOneOf(fieldNames) { + var fieldMap = {}; + for (var i = 0; i < fieldNames.length; ++i) + fieldMap[fieldNames[i]] = 1; + return function() { + for (var keys = Object.keys(this), i2 = keys.length - 1; i2 > -1; --i2) + if (fieldMap[keys[i2]] === 1 && this[keys[i2]] !== void 0 && this[keys[i2]] !== null) + return keys[i2]; + }; + }; + util.oneOfSetter = function setOneOf(fieldNames) { + return function(name) { + for (var i = 0; i < fieldNames.length; ++i) + if (fieldNames[i] !== name) + delete this[fieldNames[i]]; + }; + }; + util.toJSONOptions = { + longs: String, + enums: String, + bytes: String, + json: true + }; + util._configure = function() { + var Buffer2 = util.Buffer; + if (!Buffer2) { + util._Buffer_from = util._Buffer_allocUnsafe = null; + return; + } + util._Buffer_from = Buffer2.from !== Uint8Array.from && Buffer2.from || /* istanbul ignore next */ + function Buffer_from(value, encoding) { + return new Buffer2(value, encoding); + }; + util._Buffer_allocUnsafe = Buffer2.allocUnsafe || /* istanbul ignore next */ + function Buffer_allocUnsafe(size) { + return new Buffer2(size); + }; + }; + } +}); + +// node_modules/protobufjs/src/writer.js +var require_writer2 = __commonJS({ + "node_modules/protobufjs/src/writer.js"(exports2, module2) { + "use strict"; + module2.exports = Writer; + var util = require_minimal(); + var BufferWriter; + var LongBits = util.LongBits; + var base64 = util.base64; + var utf8 = util.utf8; + function Op(fn, len, val) { + this.fn = fn; + this.len = len; + this.next = void 0; + this.val = val; + } + function noop3() { + } + function State(writer) { + this.head = writer.head; + this.tail = writer.tail; + this.len = writer.len; + this.next = writer.states; + } + function Writer() { + this.len = 0; + this.head = new Op(noop3, 0, 0); + this.tail = this.head; + this.states = null; + } + var create = function create2() { + return util.Buffer ? function create_buffer_setup() { + return (Writer.create = function create_buffer() { + return new BufferWriter(); + })(); + } : function create_array() { + return new Writer(); + }; + }; + Writer.create = create(); + Writer.alloc = function alloc(size) { + return new util.Array(size); + }; + if (util.Array !== Array) + Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray); + Writer.prototype._push = function push(fn, len, val) { + this.tail = this.tail.next = new Op(fn, len, val); + this.len += len; + return this; + }; + function writeByte(val, buf, pos) { + buf[pos] = val & 255; + } + function writeVarint32(val, buf, pos) { + while (val > 127) { + buf[pos++] = val & 127 | 128; + val >>>= 7; + } + buf[pos] = val; + } + function VarintOp(len, val) { + this.len = len; + this.next = void 0; + this.val = val; + } + VarintOp.prototype = Object.create(Op.prototype); + VarintOp.prototype.fn = writeVarint32; + Writer.prototype.uint32 = function write_uint32(value) { + this.len += (this.tail = this.tail.next = new VarintOp( + (value = value >>> 0) < 128 ? 1 : value < 16384 ? 2 : value < 2097152 ? 3 : value < 268435456 ? 4 : 5, + value + )).len; + return this; + }; + Writer.prototype.int32 = function write_int32(value) { + return value < 0 ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) : this.uint32(value); + }; + Writer.prototype.sint32 = function write_sint32(value) { + return this.uint32((value << 1 ^ value >> 31) >>> 0); + }; + function writeVarint64(val, buf, pos) { + while (val.hi) { + buf[pos++] = val.lo & 127 | 128; + val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0; + val.hi >>>= 7; + } + while (val.lo > 127) { + buf[pos++] = val.lo & 127 | 128; + val.lo = val.lo >>> 7; + } + buf[pos++] = val.lo; + } + Writer.prototype.uint64 = function write_uint64(value) { + var bits = LongBits.from(value); + return this._push(writeVarint64, bits.length(), bits); + }; + Writer.prototype.int64 = Writer.prototype.uint64; + Writer.prototype.sint64 = function write_sint64(value) { + var bits = LongBits.from(value).zzEncode(); + return this._push(writeVarint64, bits.length(), bits); + }; + Writer.prototype.bool = function write_bool(value) { + return this._push(writeByte, 1, value ? 1 : 0); + }; + function writeFixed32(val, buf, pos) { + buf[pos] = val & 255; + buf[pos + 1] = val >>> 8 & 255; + buf[pos + 2] = val >>> 16 & 255; + buf[pos + 3] = val >>> 24; + } + Writer.prototype.fixed32 = function write_fixed32(value) { + return this._push(writeFixed32, 4, value >>> 0); + }; + Writer.prototype.sfixed32 = Writer.prototype.fixed32; + Writer.prototype.fixed64 = function write_fixed64(value) { + var bits = LongBits.from(value); + return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi); + }; + Writer.prototype.sfixed64 = Writer.prototype.fixed64; + Writer.prototype.float = function write_float(value) { + return this._push(util.float.writeFloatLE, 4, value); + }; + Writer.prototype.double = function write_double(value) { + return this._push(util.float.writeDoubleLE, 8, value); + }; + var writeBytes = util.Array.prototype.set ? function writeBytes_set(val, buf, pos) { + buf.set(val, pos); + } : function writeBytes_for(val, buf, pos) { + for (var i = 0; i < val.length; ++i) + buf[pos + i] = val[i]; + }; + Writer.prototype.bytes = function write_bytes(value) { + var len = value.length >>> 0; + if (!len) + return this._push(writeByte, 1, 0); + if (util.isString(value)) { + var buf = Writer.alloc(len = base64.length(value)); + base64.decode(value, buf, 0); + value = buf; + } + return this.uint32(len)._push(writeBytes, len, value); + }; + Writer.prototype.string = function write_string(value) { + var len = utf8.length(value); + return len ? this.uint32(len)._push(utf8.write, len, value) : this._push(writeByte, 1, 0); + }; + Writer.prototype.fork = function fork() { + this.states = new State(this); + this.head = this.tail = new Op(noop3, 0, 0); + this.len = 0; + return this; + }; + Writer.prototype.reset = function reset() { + if (this.states) { + this.head = this.states.head; + this.tail = this.states.tail; + this.len = this.states.len; + this.states = this.states.next; + } else { + this.head = this.tail = new Op(noop3, 0, 0); + this.len = 0; + } + return this; + }; + Writer.prototype.ldelim = function ldelim() { + var head = this.head, tail = this.tail, len = this.len; + this.reset().uint32(len); + if (len) { + this.tail.next = head.next; + this.tail = tail; + this.len += len; + } + return this; + }; + Writer.prototype.finish = function finish() { + var head = this.head.next, buf = this.constructor.alloc(this.len), pos = 0; + while (head) { + head.fn(head.val, buf, pos); + pos += head.len; + head = head.next; + } + return buf; + }; + Writer._configure = function(BufferWriter_) { + BufferWriter = BufferWriter_; + Writer.create = create(); + BufferWriter._configure(); + }; + } +}); + +// node_modules/protobufjs/src/writer_buffer.js +var require_writer_buffer = __commonJS({ + "node_modules/protobufjs/src/writer_buffer.js"(exports2, module2) { + "use strict"; + module2.exports = BufferWriter; + var Writer = require_writer2(); + (BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter; + var util = require_minimal(); + function BufferWriter() { + Writer.call(this); + } + BufferWriter._configure = function() { + BufferWriter.alloc = util._Buffer_allocUnsafe; + BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === "set" ? function writeBytesBuffer_set(val, buf, pos) { + buf.set(val, pos); + } : function writeBytesBuffer_copy(val, buf, pos) { + if (val.copy) + val.copy(buf, pos, 0, val.length); + else for (var i = 0; i < val.length; ) + buf[pos++] = val[i++]; + }; + }; + BufferWriter.prototype.bytes = function write_bytes_buffer(value) { + if (util.isString(value)) + value = util._Buffer_from(value, "base64"); + var len = value.length >>> 0; + this.uint32(len); + if (len) + this._push(BufferWriter.writeBytesBuffer, len, value); + return this; + }; + function writeStringBuffer(val, buf, pos) { + if (val.length < 40) + util.utf8.write(val, buf, pos); + else if (buf.utf8Write) + buf.utf8Write(val, pos); + else + buf.write(val, pos); + } + BufferWriter.prototype.string = function write_string_buffer(value) { + var len = util.Buffer.byteLength(value); + this.uint32(len); + if (len) + this._push(writeStringBuffer, len, value); + return this; + }; + BufferWriter._configure(); + } +}); + +// node_modules/protobufjs/src/reader.js +var require_reader2 = __commonJS({ + "node_modules/protobufjs/src/reader.js"(exports2, module2) { + "use strict"; + module2.exports = Reader; + var util = require_minimal(); + var BufferReader; + var LongBits = util.LongBits; + var utf8 = util.utf8; + function indexOutOfRange(reader, writeLength) { + return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len); + } + function Reader(buffer) { + this.buf = buffer; + this.pos = 0; + this.len = buffer.length; + } + var create_array = typeof Uint8Array !== "undefined" ? function create_typed_array(buffer) { + if (buffer instanceof Uint8Array || Array.isArray(buffer)) + return new Reader(buffer); + throw Error("illegal buffer"); + } : function create_array2(buffer) { + if (Array.isArray(buffer)) + return new Reader(buffer); + throw Error("illegal buffer"); + }; + var create = function create2() { + return util.Buffer ? function create_buffer_setup(buffer) { + return (Reader.create = function create_buffer(buffer2) { + return util.Buffer.isBuffer(buffer2) ? new BufferReader(buffer2) : create_array(buffer2); + })(buffer); + } : create_array; + }; + Reader.create = create(); + Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ + util.Array.prototype.slice; + Reader.prototype.uint32 = /* @__PURE__ */ (function read_uint32_setup() { + var value = 4294967295; + return function read_uint32() { + value = (this.buf[this.pos] & 127) >>> 0; + if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; + if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; + if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; + if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; + if (this.buf[this.pos++] < 128) return value; + if ((this.pos += 5) > this.len) { + this.pos = this.len; + throw indexOutOfRange(this, 10); + } + return value; + }; + })(); + Reader.prototype.int32 = function read_int32() { + return this.uint32() | 0; + }; + Reader.prototype.sint32 = function read_sint32() { + var value = this.uint32(); + return value >>> 1 ^ -(value & 1) | 0; + }; + function readLongVarint() { + var bits = new LongBits(0, 0); + var i = 0; + if (this.len - this.pos > 4) { + for (; i < 4; ++i) { + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0; + bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + i = 0; + } else { + for (; i < 3; ++i) { + if (this.pos >= this.len) + throw indexOutOfRange(this); + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0; + return bits; + } + if (this.len - this.pos > 4) { + for (; i < 5; ++i) { + bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + } else { + for (; i < 5; ++i) { + if (this.pos >= this.len) + throw indexOutOfRange(this); + bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + } + throw Error("invalid varint encoding"); + } + Reader.prototype.bool = function read_bool() { + return this.uint32() !== 0; + }; + function readFixed32_end(buf, end) { + return (buf[end - 4] | buf[end - 3] << 8 | buf[end - 2] << 16 | buf[end - 1] << 24) >>> 0; + } + Reader.prototype.fixed32 = function read_fixed32() { + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + return readFixed32_end(this.buf, this.pos += 4); + }; + Reader.prototype.sfixed32 = function read_sfixed32() { + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + return readFixed32_end(this.buf, this.pos += 4) | 0; + }; + function readFixed64() { + if (this.pos + 8 > this.len) + throw indexOutOfRange(this, 8); + return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4)); + } + Reader.prototype.float = function read_float() { + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + var value = util.float.readFloatLE(this.buf, this.pos); + this.pos += 4; + return value; + }; + Reader.prototype.double = function read_double() { + if (this.pos + 8 > this.len) + throw indexOutOfRange(this, 4); + var value = util.float.readDoubleLE(this.buf, this.pos); + this.pos += 8; + return value; + }; + Reader.prototype.bytes = function read_bytes() { + var length = this.uint32(), start = this.pos, end = this.pos + length; + if (end > this.len) + throw indexOutOfRange(this, length); + this.pos += length; + if (Array.isArray(this.buf)) + return this.buf.slice(start, end); + if (start === end) { + var nativeBuffer = util.Buffer; + return nativeBuffer ? nativeBuffer.alloc(0) : new this.buf.constructor(0); + } + return this._slice.call(this.buf, start, end); + }; + Reader.prototype.string = function read_string() { + var bytes = this.bytes(); + return utf8.read(bytes, 0, bytes.length); + }; + Reader.prototype.skip = function skip(length) { + if (typeof length === "number") { + if (this.pos + length > this.len) + throw indexOutOfRange(this, length); + this.pos += length; + } else { + do { + if (this.pos >= this.len) + throw indexOutOfRange(this); + } while (this.buf[this.pos++] & 128); + } + return this; + }; + Reader.recursionLimit = util.recursionLimit; + Reader.prototype.skipType = function(wireType, depth) { + if (depth === void 0) depth = 0; + if (depth > Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + switch (wireType) { + case 0: + this.skip(); + break; + case 1: + this.skip(8); + break; + case 2: + this.skip(this.uint32()); + break; + case 3: + while ((wireType = this.uint32() & 7) !== 4) { + this.skipType(wireType, depth + 1); + } + break; + case 5: + this.skip(4); + break; + /* istanbul ignore next */ + default: + throw Error("invalid wire type " + wireType + " at offset " + this.pos); + } + return this; + }; + Reader._configure = function(BufferReader_) { + BufferReader = BufferReader_; + Reader.create = create(); + BufferReader._configure(); + var fn = util.Long ? "toLong" : ( + /* istanbul ignore next */ + "toNumber" + ); + util.merge(Reader.prototype, { + int64: function read_int64() { + return readLongVarint.call(this)[fn](false); + }, + uint64: function read_uint64() { + return readLongVarint.call(this)[fn](true); + }, + sint64: function read_sint64() { + return readLongVarint.call(this).zzDecode()[fn](false); + }, + fixed64: function read_fixed64() { + return readFixed64.call(this)[fn](true); + }, + sfixed64: function read_sfixed64() { + return readFixed64.call(this)[fn](false); + } + }); + }; + } +}); + +// node_modules/protobufjs/src/reader_buffer.js +var require_reader_buffer = __commonJS({ + "node_modules/protobufjs/src/reader_buffer.js"(exports2, module2) { + "use strict"; + module2.exports = BufferReader; + var Reader = require_reader2(); + (BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader; + var util = require_minimal(); + function BufferReader(buffer) { + Reader.call(this, buffer); + } + BufferReader._configure = function() { + if (util.Buffer) + BufferReader.prototype._slice = util.Buffer.prototype.slice; + }; + BufferReader.prototype.string = function read_string_buffer() { + var len = this.uint32(); + return this.buf.utf8Slice ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len)) : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + len, this.len)); + }; + BufferReader._configure(); + } +}); + +// node_modules/protobufjs/src/rpc/service.js +var require_service2 = __commonJS({ + "node_modules/protobufjs/src/rpc/service.js"(exports2, module2) { + "use strict"; + module2.exports = Service; + var util = require_minimal(); + (Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service; + function Service(rpcImpl, requestDelimited, responseDelimited) { + if (typeof rpcImpl !== "function") + throw TypeError("rpcImpl must be a function"); + util.EventEmitter.call(this); + this.rpcImpl = rpcImpl; + this.requestDelimited = Boolean(requestDelimited); + this.responseDelimited = Boolean(responseDelimited); + } + Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request2, callback) { + if (!request2) + throw TypeError("request must be specified"); + var self2 = this; + if (!callback) + return util.asPromise(rpcCall, self2, method, requestCtor, responseCtor, request2); + if (!self2.rpcImpl) { + setTimeout(function() { + callback(Error("already ended")); + }, 0); + return void 0; + } + try { + return self2.rpcImpl( + method, + requestCtor[self2.requestDelimited ? "encodeDelimited" : "encode"](request2).finish(), + function rpcCallback(err, response) { + if (err) { + self2.emit("error", err, method); + return callback(err); + } + if (response === null) { + self2.end( + /* endedByRPC */ + true + ); + return void 0; + } + if (!(response instanceof responseCtor)) { + try { + response = responseCtor[self2.responseDelimited ? "decodeDelimited" : "decode"](response); + } catch (err2) { + self2.emit("error", err2, method); + return callback(err2); + } + } + self2.emit("data", response, method); + return callback(null, response); + } + ); + } catch (err) { + self2.emit("error", err, method); + setTimeout(function() { + callback(err); + }, 0); + return void 0; + } + }; + Service.prototype.end = function end(endedByRPC) { + if (this.rpcImpl) { + if (!endedByRPC) + this.rpcImpl(null, null, null); + this.rpcImpl = null; + this.emit("end").off(); + } + return this; + }; + } +}); + +// node_modules/protobufjs/src/rpc.js +var require_rpc = __commonJS({ + "node_modules/protobufjs/src/rpc.js"(exports2) { + "use strict"; + var rpc = exports2; + rpc.Service = require_service2(); + } +}); + +// node_modules/protobufjs/src/roots.js +var require_roots = __commonJS({ + "node_modules/protobufjs/src/roots.js"(exports2, module2) { + "use strict"; + module2.exports = {}; + } +}); + +// node_modules/protobufjs/src/index-minimal.js +var require_index_minimal = __commonJS({ + "node_modules/protobufjs/src/index-minimal.js"(exports2) { + "use strict"; + var protobuf = exports2; + protobuf.build = "minimal"; + protobuf.Writer = require_writer2(); + protobuf.BufferWriter = require_writer_buffer(); + protobuf.Reader = require_reader2(); + protobuf.BufferReader = require_reader_buffer(); + protobuf.util = require_minimal(); + protobuf.rpc = require_rpc(); + protobuf.roots = require_roots(); + protobuf.configure = configure; + function configure() { + protobuf.util._configure(); + protobuf.Writer._configure(protobuf.BufferWriter); + protobuf.Reader._configure(protobuf.BufferReader); + } + configure(); + } +}); + +// node_modules/@protobufjs/codegen/index.js +var require_codegen = __commonJS({ + "node_modules/@protobufjs/codegen/index.js"(exports2, module2) { + "use strict"; + module2.exports = codegen; + var reservedRe = /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/; + function codegen(functionParams, functionName) { + if (typeof functionParams === "string") { + functionName = functionParams; + functionParams = void 0; + } + var body = []; + function Codegen(formatStringOrScope) { + if (typeof formatStringOrScope !== "string") { + var source = toString(); + if (codegen.verbose) + console.log("codegen: " + source); + source = "return " + source; + if (formatStringOrScope) { + var scopeKeys = Object.keys(formatStringOrScope), scopeParams = new Array(scopeKeys.length + 1), scopeValues = new Array(scopeKeys.length), scopeOffset = 0; + while (scopeOffset < scopeKeys.length) { + scopeParams[scopeOffset] = scopeKeys[scopeOffset]; + scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]]; + } + scopeParams[scopeOffset] = source; + return Function.apply(null, scopeParams).apply(null, scopeValues); + } + return Function(source)(); + } + var formatParams = new Array(arguments.length - 1), formatOffset = 0; + while (formatOffset < formatParams.length) + formatParams[formatOffset] = arguments[++formatOffset]; + formatOffset = 0; + formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, function replace($0, $1) { + var value = formatParams[formatOffset++]; + switch ($1) { + case "d": + case "f": + return String(Number(value)); + case "i": + return String(Math.floor(value)); + case "j": + return JSON.stringify(value); + case "s": + return String(value); + } + return "%"; + }); + if (formatOffset !== formatParams.length) + throw Error("parameter count mismatch"); + body.push(formatStringOrScope); + return Codegen; + } + function toString(functionNameOverride) { + return "function " + safeFunctionName(functionNameOverride || functionName) + "(" + (functionParams && functionParams.join(",") || "") + "){\n " + body.join("\n ") + "\n}"; + } + Codegen.toString = toString; + return Codegen; + } + codegen.verbose = false; + function safeFunctionName(name) { + if (!name) + return ""; + name = String(name).replace(/[^\w$]/g, ""); + if (!name) + return ""; + if (/^\d/.test(name)) + name = "_" + name; + return reservedRe.test(name) ? name + "_" : name; + } + } +}); + +// node_modules/@protobufjs/fetch/index.js +var require_fetch2 = __commonJS({ + "node_modules/@protobufjs/fetch/index.js"(exports2, module2) { + "use strict"; + module2.exports = fetch3; + var asPromise = require_aspromise(); + var inquire = require_inquire(); + var fs4 = inquire("fs"); + function fetch3(filename, options, callback) { + if (typeof options === "function") { + callback = options; + options = {}; + } else if (!options) + options = {}; + if (!callback) + return asPromise(fetch3, this, filename, options); + if (!options.xhr && fs4 && fs4.readFile) + return fs4.readFile(filename, function fetchReadFileCallback(err, contents) { + return err && typeof XMLHttpRequest !== "undefined" ? fetch3.xhr(filename, options, callback) : err ? callback(err) : callback(null, options.binary ? contents : contents.toString("utf8")); + }); + return fetch3.xhr(filename, options, callback); + } + fetch3.xhr = function fetch_xhr(filename, options, callback) { + var xhr = new XMLHttpRequest(); + xhr.onreadystatechange = function fetchOnReadyStateChange() { + if (xhr.readyState !== 4) + return void 0; + if (xhr.status !== 0 && xhr.status !== 200) + return callback(Error("status " + xhr.status)); + if (options.binary) { + var buffer = xhr.response; + if (!buffer) { + buffer = []; + for (var i = 0; i < xhr.responseText.length; ++i) + buffer.push(xhr.responseText.charCodeAt(i) & 255); + } + return callback(null, typeof Uint8Array !== "undefined" ? new Uint8Array(buffer) : buffer); + } + return callback(null, xhr.responseText); + }; + if (options.binary) { + if ("overrideMimeType" in xhr) + xhr.overrideMimeType("text/plain; charset=x-user-defined"); + xhr.responseType = "arraybuffer"; + } + xhr.open("GET", filename); + xhr.send(); + }; + } +}); + +// node_modules/@protobufjs/path/index.js +var require_path = __commonJS({ + "node_modules/@protobufjs/path/index.js"(exports2) { + "use strict"; + var path = exports2; + var isAbsolute = ( + /** + * Tests if the specified path is absolute. + * @param {string} path Path to test + * @returns {boolean} `true` if path is absolute + */ + path.isAbsolute = function isAbsolute2(path2) { + return /^(?:\/|\w+:)/.test(path2); + } + ); + var normalize = ( + /** + * Normalizes the specified path. + * @param {string} path Path to normalize + * @returns {string} Normalized path + */ + path.normalize = function normalize2(path2) { + path2 = path2.replace(/\\/g, "/").replace(/\/{2,}/g, "/"); + var parts = path2.split("/"), absolute = isAbsolute(path2), prefix = ""; + if (absolute) + prefix = parts.shift() + "/"; + for (var i = 0; i < parts.length; ) { + if (parts[i] === "..") { + if (i > 0 && parts[i - 1] !== "..") + parts.splice(--i, 2); + else if (absolute) + parts.splice(i, 1); + else + ++i; + } else if (parts[i] === ".") + parts.splice(i, 1); + else + ++i; + } + return prefix + parts.join("/"); + } + ); + path.resolve = function resolve(originPath, includePath, alreadyNormalized) { + if (!alreadyNormalized) + includePath = normalize(includePath); + if (isAbsolute(includePath)) + return includePath; + if (!alreadyNormalized) + originPath = normalize(originPath); + return (originPath = originPath.replace(/(?:\/|^)[^/]+$/, "")).length ? normalize(originPath + "/" + includePath) : includePath; + }; + } +}); + +// node_modules/protobufjs/src/util/patterns.js +var require_patterns = __commonJS({ + "node_modules/protobufjs/src/util/patterns.js"(exports2) { + "use strict"; + var patterns = exports2; + patterns.numberRe = /^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/; + patterns.typeRefRe = /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/; + patterns.reservedRe = /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/; + patterns.unsafePropertyRe = /^(?:__proto__|prototype|constructor)$/; + } +}); + +// node_modules/protobufjs/src/namespace.js +var require_namespace = __commonJS({ + "node_modules/protobufjs/src/namespace.js"(exports2, module2) { + "use strict"; + module2.exports = Namespace; + var ReflectionObject = require_object(); + ((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = "Namespace"; + var Field = require_field(); + var util = require_util10(); + var OneOf = require_oneof(); + var Type; + var Service; + var Enum; + Namespace.fromJSON = function fromJSON(name, json) { + return new Namespace(name, json.options).addJSON(json.nested); + }; + function arrayToJSON(array, toJSONOptions) { + if (!(array && array.length)) + return void 0; + var obj = {}; + for (var i = 0; i < array.length; ++i) + obj[array[i].name] = array[i].toJSON(toJSONOptions); + return obj; + } + Namespace.arrayToJSON = arrayToJSON; + Namespace.isReservedId = function isReservedId(reserved, id) { + if (reserved) { + for (var i = 0; i < reserved.length; ++i) + if (typeof reserved[i] !== "string" && reserved[i][0] <= id && reserved[i][1] > id) + return true; + } + return false; + }; + Namespace.isReservedName = function isReservedName(reserved, name) { + if (reserved) { + for (var i = 0; i < reserved.length; ++i) + if (reserved[i] === name) + return true; + } + return false; + }; + function Namespace(name, options) { + ReflectionObject.call(this, name, options); + this.nested = void 0; + this._nestedArray = null; + this._lookupCache = /* @__PURE__ */ Object.create(null); + this._needsRecursiveFeatureResolution = true; + this._needsRecursiveResolve = true; + } + function clearCache(namespace) { + namespace._nestedArray = null; + namespace._lookupCache = /* @__PURE__ */ Object.create(null); + var parent = namespace; + while (parent = parent.parent) { + parent._lookupCache = /* @__PURE__ */ Object.create(null); + } + return namespace; + } + Object.defineProperty(Namespace.prototype, "nestedArray", { + get: function() { + return this._nestedArray || (this._nestedArray = util.toArray(this.nested)); + } + }); + Namespace.prototype.toJSON = function toJSON(toJSONOptions) { + return util.toObject([ + "options", + this.options, + "nested", + arrayToJSON(this.nestedArray, toJSONOptions) + ]); + }; + Namespace.prototype.addJSON = function addJSON(nestedJson) { + var ns = this; + if (nestedJson) { + for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) { + nested = nestedJson[names[i]]; + ns.add( + // most to least likely + (nested.fields !== void 0 ? Type.fromJSON : nested.values !== void 0 ? Enum.fromJSON : nested.methods !== void 0 ? Service.fromJSON : nested.id !== void 0 ? Field.fromJSON : Namespace.fromJSON)(names[i], nested) + ); + } + } + return this; + }; + Namespace.prototype.get = function get(name) { + return this.nested && Object.prototype.hasOwnProperty.call(this.nested, name) ? this.nested[name] : null; + }; + Namespace.prototype.getEnum = function getEnum(name) { + if (this.nested && Object.prototype.hasOwnProperty.call(this.nested, name) && this.nested[name] instanceof Enum) + return this.nested[name].values; + throw Error("no such enum: " + name); + }; + Namespace.prototype.add = function add(object) { + if (!(object instanceof Field && object.extend !== void 0 || object instanceof Type || object instanceof OneOf || object instanceof Enum || object instanceof Service || object instanceof Namespace)) + throw TypeError("object must be a valid nested object"); + if (object.name === "__proto__") + return this; + if (!this.nested) + this.nested = {}; + else { + var prev = this.get(object.name); + if (prev) { + if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) { + var nested = prev.nestedArray; + for (var i = 0; i < nested.length; ++i) + object.add(nested[i]); + this.remove(prev); + if (!this.nested) + this.nested = {}; + object.setOptions(prev.options, true); + } else + throw Error("duplicate name '" + object.name + "' in " + this); + } + } + this.nested[object.name] = object; + if (!(this instanceof Type || this instanceof Service || this instanceof Enum || this instanceof Field)) { + if (!object._edition) { + object._edition = object._defaultEdition; + } + } + this._needsRecursiveFeatureResolution = true; + this._needsRecursiveResolve = true; + var parent = this; + while (parent = parent.parent) { + parent._needsRecursiveFeatureResolution = true; + parent._needsRecursiveResolve = true; + } + object.onAdd(this); + return clearCache(this); + }; + Namespace.prototype.remove = function remove(object) { + if (!(object instanceof ReflectionObject)) + throw TypeError("object must be a ReflectionObject"); + if (object.parent !== this) + throw Error(object + " is not a member of " + this); + delete this.nested[object.name]; + if (!Object.keys(this.nested).length) + this.nested = void 0; + object.onRemove(this); + return clearCache(this); + }; + Namespace.prototype.define = function define2(path, json) { + if (util.isString(path)) + path = path.split("."); + else if (!Array.isArray(path)) + throw TypeError("illegal path"); + if (path && path.length && path[0] === "") + throw Error("path must be relative"); + var ptr = this; + while (path.length > 0) { + var part = path.shift(); + if (ptr.nested && ptr.nested[part]) { + ptr = ptr.nested[part]; + if (!(ptr instanceof Namespace)) + throw Error("path conflicts with non-namespace objects"); + } else + ptr.add(ptr = new Namespace(part)); + } + if (json) + ptr.addJSON(json); + return ptr; + }; + Namespace.prototype.resolveAll = function resolveAll() { + if (!this._needsRecursiveResolve) return this; + this._resolveFeaturesRecursive(this._edition); + var nested = this.nestedArray, i = 0; + this.resolve(); + while (i < nested.length) + if (nested[i] instanceof Namespace) + nested[i++].resolveAll(); + else + nested[i++].resolve(); + this._needsRecursiveResolve = false; + return this; + }; + Namespace.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) { + if (!this._needsRecursiveFeatureResolution) return this; + this._needsRecursiveFeatureResolution = false; + edition = this._edition || edition; + ReflectionObject.prototype._resolveFeaturesRecursive.call(this, edition); + this.nestedArray.forEach((nested) => { + nested._resolveFeaturesRecursive(edition); + }); + return this; + }; + Namespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChecked) { + if (typeof filterTypes === "boolean") { + parentAlreadyChecked = filterTypes; + filterTypes = void 0; + } else if (filterTypes && !Array.isArray(filterTypes)) + filterTypes = [filterTypes]; + if (util.isString(path) && path.length) { + if (path === ".") + return this.root; + path = path.split("."); + } else if (!path.length) + return this; + var flatPath = path.join("."); + if (path[0] === "") + return this.root.lookup(path.slice(1), filterTypes); + var found = this.root._fullyQualifiedObjects && this.root._fullyQualifiedObjects["." + flatPath]; + if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) { + return found; + } + found = this._lookupImpl(path, flatPath); + if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) { + return found; + } + if (parentAlreadyChecked) + return null; + var current = this; + while (current.parent) { + found = current.parent._lookupImpl(path, flatPath); + if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) { + return found; + } + current = current.parent; + } + return null; + }; + Namespace.prototype._lookupImpl = function lookup(path, flatPath) { + if (Object.prototype.hasOwnProperty.call(this._lookupCache, flatPath)) { + return this._lookupCache[flatPath]; + } + var found = this.get(path[0]); + var exact = null; + if (found) { + if (path.length === 1) { + exact = found; + } else if (found instanceof Namespace) { + path = path.slice(1); + exact = found._lookupImpl(path, path.join(".")); + } + } else { + for (var i = 0; i < this.nestedArray.length; ++i) + if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i]._lookupImpl(path, flatPath))) + exact = found; + } + this._lookupCache[flatPath] = exact; + return exact; + }; + Namespace.prototype.lookupType = function lookupType(path) { + var found = this.lookup(path, [Type]); + if (!found) + throw Error("no such type: " + path); + return found; + }; + Namespace.prototype.lookupEnum = function lookupEnum(path) { + var found = this.lookup(path, [Enum]); + if (!found) + throw Error("no such Enum '" + path + "' in " + this); + return found; + }; + Namespace.prototype.lookupTypeOrEnum = function lookupTypeOrEnum(path) { + var found = this.lookup(path, [Type, Enum]); + if (!found) + throw Error("no such Type or Enum '" + path + "' in " + this); + return found; + }; + Namespace.prototype.lookupService = function lookupService(path) { + var found = this.lookup(path, [Service]); + if (!found) + throw Error("no such Service '" + path + "' in " + this); + return found; + }; + Namespace._configure = function(Type_, Service_, Enum_) { + Type = Type_; + Service = Service_; + Enum = Enum_; + }; + } +}); + +// node_modules/protobufjs/src/mapfield.js +var require_mapfield = __commonJS({ + "node_modules/protobufjs/src/mapfield.js"(exports2, module2) { + "use strict"; + module2.exports = MapField; + var Field = require_field(); + ((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = "MapField"; + var types = require_types2(); + var util = require_util10(); + function MapField(name, id, keyType, type, options, comment) { + Field.call(this, name, id, type, void 0, void 0, options, comment); + if (!util.isString(keyType)) + throw TypeError("keyType must be a string"); + this.keyType = keyType; + this.resolvedKeyType = null; + this.map = true; + } + MapField.fromJSON = function fromJSON(name, json) { + return new MapField(name, json.id, json.keyType, json.type, json.options, json.comment); + }; + MapField.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "keyType", + this.keyType, + "type", + this.type, + "id", + this.id, + "extend", + this.extend, + "options", + this.options, + "comment", + keepComments ? this.comment : void 0 + ]); + }; + MapField.prototype.resolve = function resolve() { + if (this.resolved) + return this; + if (types.mapKey[this.keyType] === void 0) + throw Error("invalid key type: " + this.keyType); + return Field.prototype.resolve.call(this); + }; + MapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) { + if (typeof fieldValueType === "function") + fieldValueType = util.decorateType(fieldValueType).name; + else if (fieldValueType && typeof fieldValueType === "object") + fieldValueType = util.decorateEnum(fieldValueType).name; + return function mapFieldDecorator(prototype, fieldName) { + util.decorateType(prototype.constructor).add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType)); + }; + }; + } +}); + +// node_modules/protobufjs/src/method.js +var require_method = __commonJS({ + "node_modules/protobufjs/src/method.js"(exports2, module2) { + "use strict"; + module2.exports = Method; + var ReflectionObject = require_object(); + ((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = "Method"; + var util = require_util10(); + function Method(name, type, requestType, responseType, requestStream, responseStream, options, comment, parsedOptions) { + if (util.isObject(requestStream)) { + options = requestStream; + requestStream = responseStream = void 0; + } else if (util.isObject(responseStream)) { + options = responseStream; + responseStream = void 0; + } + if (!(type === void 0 || util.isString(type))) + throw TypeError("type must be a string"); + if (!util.isString(requestType)) + throw TypeError("requestType must be a string"); + if (!util.isString(responseType)) + throw TypeError("responseType must be a string"); + ReflectionObject.call(this, name, options); + this.type = type || "rpc"; + this.requestType = requestType; + this.requestStream = requestStream ? true : void 0; + this.responseType = responseType; + this.responseStream = responseStream ? true : void 0; + this.resolvedRequestType = null; + this.resolvedResponseType = null; + this.comment = comment; + this.parsedOptions = parsedOptions; + } + Method.fromJSON = function fromJSON(name, json) { + return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options, json.comment, json.parsedOptions); + }; + Method.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "type", + this.type !== "rpc" && /* istanbul ignore next */ + this.type || void 0, + "requestType", + this.requestType, + "requestStream", + this.requestStream, + "responseType", + this.responseType, + "responseStream", + this.responseStream, + "options", + this.options, + "comment", + keepComments ? this.comment : void 0, + "parsedOptions", + this.parsedOptions + ]); + }; + Method.prototype.resolve = function resolve() { + if (this.resolved) + return this; + this.resolvedRequestType = this.parent.lookupType(this.requestType); + this.resolvedResponseType = this.parent.lookupType(this.responseType); + return ReflectionObject.prototype.resolve.call(this); + }; + } +}); + +// node_modules/protobufjs/src/service.js +var require_service3 = __commonJS({ + "node_modules/protobufjs/src/service.js"(exports2, module2) { + "use strict"; + module2.exports = Service; + var Namespace = require_namespace(); + ((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = "Service"; + var Method = require_method(); + var util = require_util10(); + var rpc = require_rpc(); + var reservedRe = util.patterns.reservedRe; + function Service(name, options) { + Namespace.call(this, name, options); + this.methods = {}; + this._methodsArray = null; + } + Service.fromJSON = function fromJSON(name, json) { + var service = new Service(name, json.options); + if (json.methods) + for (var names = Object.keys(json.methods), i = 0; i < names.length; ++i) + service.add(Method.fromJSON(names[i], json.methods[names[i]])); + if (json.nested) + service.addJSON(json.nested); + if (json.edition) + service._edition = json.edition; + service.comment = json.comment; + service._defaultEdition = "proto3"; + return service; + }; + Service.prototype.toJSON = function toJSON(toJSONOptions) { + var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions); + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "edition", + this._editionToJSON(), + "options", + inherited && inherited.options || void 0, + "methods", + Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || /* istanbul ignore next */ + {}, + "nested", + inherited && inherited.nested || void 0, + "comment", + keepComments ? this.comment : void 0 + ]); + }; + Object.defineProperty(Service.prototype, "methodsArray", { + get: function() { + return this._methodsArray || (this._methodsArray = util.toArray(this.methods)); + } + }); + function clearCache(service) { + service._methodsArray = null; + return service; + } + Service.prototype.get = function get(name) { + return Object.prototype.hasOwnProperty.call(this.methods, name) ? this.methods[name] : Namespace.prototype.get.call(this, name); + }; + Service.prototype.resolveAll = function resolveAll() { + if (!this._needsRecursiveResolve) return this; + Namespace.prototype.resolve.call(this); + var methods = this.methodsArray; + for (var i = 0; i < methods.length; ++i) + methods[i].resolve(); + return this; + }; + Service.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) { + if (!this._needsRecursiveFeatureResolution) return this; + edition = this._edition || edition; + Namespace.prototype._resolveFeaturesRecursive.call(this, edition); + this.methodsArray.forEach((method) => { + method._resolveFeaturesRecursive(edition); + }); + return this; + }; + Service.prototype.add = function add(object) { + if (this.get(object.name)) + throw Error("duplicate name '" + object.name + "' in " + this); + if (object instanceof Method) { + if (object.name === "__proto__") + return this; + this.methods[object.name] = object; + object.parent = this; + return clearCache(this); + } + return Namespace.prototype.add.call(this, object); + }; + Service.prototype.remove = function remove(object) { + if (object instanceof Method) { + if (this.methods[object.name] !== object) + throw Error(object + " is not a member of " + this); + delete this.methods[object.name]; + object.parent = null; + return clearCache(this); + } + return Namespace.prototype.remove.call(this, object); + }; + Service.prototype.create = function create(rpcImpl, requestDelimited, responseDelimited) { + var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited); + for (var i = 0, method; i < /* initializes */ + this.methodsArray.length; ++i) { + var methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\w_]/g, ""); + rpcService[methodName] = util.codegen(["r", "c"], reservedRe.test(methodName) ? methodName + "_" : methodName)("return this.rpcCall(m,q,s,r,c)")({ + m: method, + q: method.resolvedRequestType.ctor, + s: method.resolvedResponseType.ctor + }); + } + return rpcService; + }; + } +}); + +// node_modules/protobufjs/src/message.js +var require_message = __commonJS({ + "node_modules/protobufjs/src/message.js"(exports2, module2) { + "use strict"; + module2.exports = Message; + var util = require_minimal(); + function Message(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (key === "__proto__") + continue; + this[key] = properties[key]; + } + } + Message.create = function create(properties) { + return this.$type.create(properties); + }; + Message.encode = function encode(message, writer) { + return this.$type.encode(message, writer); + }; + Message.encodeDelimited = function encodeDelimited(message, writer) { + return this.$type.encodeDelimited(message, writer); + }; + Message.decode = function decode(reader) { + return this.$type.decode(reader); + }; + Message.decodeDelimited = function decodeDelimited(reader) { + return this.$type.decodeDelimited(reader); + }; + Message.verify = function verify(message) { + return this.$type.verify(message); + }; + Message.fromObject = function fromObject(object) { + return this.$type.fromObject(object); + }; + Message.toObject = function toObject(message, options) { + return this.$type.toObject(message, options); + }; + Message.prototype.toJSON = function toJSON() { + return this.$type.toObject(this, util.toJSONOptions); + }; + } +}); + +// node_modules/protobufjs/src/decoder.js +var require_decoder = __commonJS({ + "node_modules/protobufjs/src/decoder.js"(exports2, module2) { + "use strict"; + module2.exports = decoder; + var Enum = require_enum(); + var types = require_types2(); + var util = require_util10(); + function missing(field) { + return "missing required '" + field.name + "'"; + } + function decoder(mtype) { + var gen = util.codegen(["r", "l", "e", "n"], mtype.name + "$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("if(n===undefined)n=0")("if(n>Reader.recursionLimit)")('throw Error("maximum nesting depth exceeded")')("var c=l===undefined?r.len:r.pos+l,m=new this.ctor" + (mtype.fieldsArray.filter(function(field2) { + return field2.map; + }).length ? ",k,value" : ""))("while(r.pos>>3){"); + var i = 0; + for (; i < /* initializes */ + mtype.fieldsArray.length; ++i) { + var field = mtype._fieldsArray[i].resolve(), type = field.resolvedType instanceof Enum ? "int32" : field.type, ref = "m" + util.safeProp(field.name); + gen("case %i: {", field.id); + if (field.map) { + gen("if(%s===util.emptyObject)", ref)("%s={}", ref)("var c2 = r.uint32()+r.pos"); + if (types.defaults[field.keyType] !== void 0) gen("k=%j", types.defaults[field.keyType]); + else gen("k=null"); + if (types.defaults[type] !== void 0) gen("value=%j", types.defaults[type]); + else gen("value=null"); + gen("while(r.pos>>3){")("case 1: k=r.%s(); break", field.keyType)("case 2:"); + if (types.basic[type] === void 0) gen("value=types[%i].decode(r,r.uint32(),undefined,n+1)", i); + else gen("value=r.%s()", type); + gen("break")("default:")("r.skipType(tag2&7,n)")("break")("}")("}"); + if (types.long[field.keyType] !== void 0) gen('%s[typeof k==="object"?util.longToHash(k):k]=value', ref); + else { + if (field.keyType === "string") gen('if(k==="__proto__")')("util.makeProp(%s,k)", ref); + gen("%s[k]=value", ref); + } + } else if (field.repeated) { + gen("if(!(%s&&%s.length))", ref, ref)("%s=[]", ref); + if (types.packed[type] !== void 0) gen("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.posutil.recursionLimit)")("return%j", "maximum nesting depth exceeded"); + var oneofs = mtype.oneofsArray, seenFirstField = {}; + if (oneofs.length) gen("var p={}"); + for (var i = 0; i < /* initializes */ + mtype.fieldsArray.length; ++i) { + var field = mtype._fieldsArray[i].resolve(), ref = "m" + util.safeProp(field.name); + if (field.optional) gen("if(%s!=null&&m.hasOwnProperty(%j)){", ref, field.name); + if (field.map) { + gen("if(!util.isObject(%s))", ref)("return%j", invalid(field, "object"))("var k=Object.keys(%s)", ref)("for(var i=0;i>>0", prop, prop); + break; + case "int32": + case "sint32": + case "sfixed32": + gen("m%s=d%s|0", prop, prop); + break; + case "uint64": + isUnsigned = true; + // eslint-disable-next-line no-fallthrough + case "int64": + case "sint64": + case "fixed64": + case "sfixed64": + gen("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j", prop, prop, isUnsigned)('else if(typeof d%s==="string")', prop)("m%s=parseInt(d%s,10)", prop, prop)('else if(typeof d%s==="number")', prop)("m%s=d%s", prop, prop)('else if(typeof d%s==="object")', prop)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)", prop, prop, prop, isUnsigned ? "true" : ""); + break; + case "bytes": + gen('if(typeof d%s==="string")', prop)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)", prop, prop, prop)("else if(d%s.length >= 0)", prop)("m%s=d%s", prop, prop); + break; + case "string": + gen("m%s=String(d%s)", prop, prop); + break; + case "bool": + gen("m%s=Boolean(d%s)", prop, prop); + break; + } + } + return gen; + } + converter.fromObject = function fromObject(mtype) { + var fields = mtype.fieldsArray; + var gen = util.codegen(["d", "n"], mtype.name + "$fromObject")("if(d instanceof this.ctor)")("return d")("if(n===undefined)n=0")("if(n>util.recursionLimit)")('throw Error("maximum nesting depth exceeded")'); + if (!fields.length) return gen("return new this.ctor"); + gen("var m=new this.ctor"); + for (var i = 0; i < fields.length; ++i) { + var field = fields[i].resolve(), prop = util.safeProp(field.name); + if (field.map) { + gen("if(d%s){", prop)('if(typeof d%s!=="object")', prop)("throw TypeError(%j)", field.fullName + ": object expected")("m%s={}", prop)("for(var ks=Object.keys(d%s),i=0;i>>0,m%s.high>>>0).toNumber(%s):m%s", prop, prop, prop, prop, isUnsigned ? "true" : "", prop); + break; + case "bytes": + gen("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s", prop, prop, prop, prop, prop); + break; + default: + gen("d%s=m%s", prop, prop); + break; + } + } + return gen; + } + converter.toObject = function toObject(mtype) { + var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById); + if (!fields.length) + return util.codegen()("return {}"); + var gen = util.codegen(["m", "o"], mtype.name + "$toObject")("if(!o)")("o={}")("var d={}"); + var repeatedFields = [], mapFields = [], normalFields = [], i = 0; + for (; i < fields.length; ++i) + if (!fields[i].partOf) + (fields[i].resolve().repeated ? repeatedFields : fields[i].map ? mapFields : normalFields).push(fields[i]); + if (repeatedFields.length) { + gen("if(o.arrays||o.defaults){"); + for (i = 0; i < repeatedFields.length; ++i) gen("d%s=[]", util.safeProp(repeatedFields[i].name)); + gen("}"); + } + if (mapFields.length) { + gen("if(o.objects||o.defaults){"); + for (i = 0; i < mapFields.length; ++i) gen("d%s={}", util.safeProp(mapFields[i].name)); + gen("}"); + } + if (normalFields.length) { + gen("if(o.defaults){"); + for (i = 0; i < normalFields.length; ++i) { + var field = normalFields[i], prop = util.safeProp(field.name); + if (field.resolvedType instanceof Enum) gen("d%s=o.enums===String?%j:%j", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault); + else if (field.long) gen("if(util.Long){")("var n=new util.Long(%i,%i,%j)", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned)("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n", prop)("}else")("d%s=o.longs===String?%j:%i", prop, field.typeDefault.toString(), field.typeDefault.toNumber()); + else if (field.bytes) { + var arrayDefault = Array.prototype.slice.call(field.typeDefault); + gen("if(o.bytes===String)d%s=%j", prop, String.fromCharCode.apply(String, field.typeDefault))("else{")("d%s=%j", prop, arrayDefault)("if(o.bytes!==Array)d%s=util.newBuffer(d%s)", prop, prop)("}"); + } else gen("d%s=%j", prop, field.typeDefault); + } + gen("}"); + } + var hasKs2 = false; + for (i = 0; i < fields.length; ++i) { + var field = fields[i], index = mtype._fieldsArray.indexOf(field), prop = util.safeProp(field.name); + if (field.map) { + if (!hasKs2) { + hasKs2 = true; + gen("var ks2"); + } + gen("if(m%s&&(ks2=Object.keys(m%s)).length){", prop, prop)("d%s={}", prop)("for(var j=0;j} + * @readonly + */ + fieldsById: { + get: function() { + if (this._fieldsById) + return this._fieldsById; + this._fieldsById = {}; + for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) { + var field = this.fields[names[i]], id = field.id; + if (this._fieldsById[id]) + throw Error("duplicate id " + id + " in " + this); + this._fieldsById[id] = field; + } + return this._fieldsById; + } + }, + /** + * Fields of this message as an array for iteration. + * @name Type#fieldsArray + * @type {Field[]} + * @readonly + */ + fieldsArray: { + get: function() { + return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields)); + } + }, + /** + * Oneofs of this message as an array for iteration. + * @name Type#oneofsArray + * @type {OneOf[]} + * @readonly + */ + oneofsArray: { + get: function() { + return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs)); + } + }, + /** + * The registered constructor, if any registered, otherwise a generic constructor. + * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor. + * @name Type#ctor + * @type {Constructor<{}>} + */ + ctor: { + get: function() { + return this._ctor || (this.ctor = Type.generateConstructor(this)()); + }, + set: function(ctor) { + var prototype = ctor.prototype; + if (!(prototype instanceof Message)) { + (ctor.prototype = new Message()).constructor = ctor; + util.merge(ctor.prototype, prototype); + } + ctor.$type = ctor.prototype.$type = this; + util.merge(ctor, Message, true); + this._ctor = ctor; + var i = 0; + for (; i < /* initializes */ + this.fieldsArray.length; ++i) + this._fieldsArray[i].resolve(); + var ctorProperties = {}; + for (i = 0; i < /* initializes */ + this.oneofsArray.length; ++i) + ctorProperties[this._oneofsArray[i].resolve().name] = { + get: util.oneOfGetter(this._oneofsArray[i].oneof), + set: util.oneOfSetter(this._oneofsArray[i].oneof) + }; + if (i) + Object.defineProperties(ctor.prototype, ctorProperties); + } + } + }); + Type.generateConstructor = function generateConstructor(mtype) { + var gen = util.codegen(["p"], mtype.name); + for (var i = 0, field; i < mtype.fieldsArray.length; ++i) + if ((field = mtype._fieldsArray[i]).map) gen("this%s={}", util.safeProp(field.name)); + else if (field.repeated) gen("this%s=[]", util.safeProp(field.name)); + return gen('if(p)for(var ks=Object.keys(p),i=0;i { + oneof._resolveFeatures(edition); + }); + this.fieldsArray.forEach((field) => { + field._resolveFeatures(edition); + }); + return this; + }; + Type.prototype.get = function get(name) { + if (Object.prototype.hasOwnProperty.call(this.fields, name)) + return this.fields[name]; + if (this.oneofs && Object.prototype.hasOwnProperty.call(this.oneofs, name)) + return this.oneofs[name]; + if (this.nested && Object.prototype.hasOwnProperty.call(this.nested, name)) + return this.nested[name]; + return null; + }; + Type.prototype.add = function add(object) { + if (this.get(object.name)) + throw Error("duplicate name '" + object.name + "' in " + this); + if (object instanceof Field && object.extend === void 0) { + if (this._fieldsById ? ( + /* istanbul ignore next */ + this._fieldsById[object.id] + ) : this.fieldsById[object.id]) + throw Error("duplicate id " + object.id + " in " + this); + if (this.isReservedId(object.id)) + throw Error("id " + object.id + " is reserved in " + this); + if (this.isReservedName(object.name)) + throw Error("name '" + object.name + "' is reserved in " + this); + if (object.name === "__proto__") + return this; + if (object.parent) + object.parent.remove(object); + this.fields[object.name] = object; + object.message = this; + object.onAdd(this); + return clearCache(this); + } + if (object instanceof OneOf) { + if (object.name === "__proto__") + return this; + if (!this.oneofs) + this.oneofs = {}; + this.oneofs[object.name] = object; + object.onAdd(this); + return clearCache(this); + } + return Namespace.prototype.add.call(this, object); + }; + Type.prototype.remove = function remove(object) { + if (object instanceof Field && object.extend === void 0) { + if (!this.fields || this.fields[object.name] !== object) + throw Error(object + " is not a member of " + this); + delete this.fields[object.name]; + object.parent = null; + object.onRemove(this); + return clearCache(this); + } + if (object instanceof OneOf) { + if (!this.oneofs || this.oneofs[object.name] !== object) + throw Error(object + " is not a member of " + this); + delete this.oneofs[object.name]; + object.parent = null; + object.onRemove(this); + return clearCache(this); + } + return Namespace.prototype.remove.call(this, object); + }; + Type.prototype.isReservedId = function isReservedId(id) { + return Namespace.isReservedId(this.reserved, id); + }; + Type.prototype.isReservedName = function isReservedName(name) { + return Namespace.isReservedName(this.reserved, name); + }; + Type.prototype.create = function create(properties) { + return new this.ctor(properties); + }; + Type.prototype.setup = function setup() { + var fullName = this.fullName, types = []; + for (var i = 0; i < /* initializes */ + this.fieldsArray.length; ++i) + types.push(this._fieldsArray[i].resolve().resolvedType); + this.encode = encoder(this)({ + Writer, + types, + util + }); + this.decode = decoder(this)({ + Reader, + types, + util + }); + this.verify = verifier(this)({ + types, + util + }); + this.fromObject = converter.fromObject(this)({ + types, + util + }); + this.toObject = converter.toObject(this)({ + types, + util + }); + var wrapper = wrappers[fullName]; + if (wrapper) { + var originalThis = Object.create(this); + originalThis.fromObject = this.fromObject; + this.fromObject = wrapper.fromObject.bind(originalThis); + originalThis.toObject = this.toObject; + this.toObject = wrapper.toObject.bind(originalThis); + } + return this; + }; + Type.prototype.encode = function encode_setup(message, writer) { + return this.setup().encode(message, writer); + }; + Type.prototype.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim(); + }; + Type.prototype.decode = function decode_setup(reader, length, end, depth) { + return this.setup().decode(reader, length, end, depth); + }; + Type.prototype.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof Reader)) + reader = Reader.create(reader); + return this.decode(reader, reader.uint32()); + }; + Type.prototype.verify = function verify_setup(message, depth) { + return this.setup().verify(message, depth); + }; + Type.prototype.fromObject = function fromObject(object, depth) { + return this.setup().fromObject(object, depth); + }; + Type.prototype.toObject = function toObject(message, options) { + return this.setup().toObject(message, options); + }; + Type.d = function decorateType(typeName) { + return function typeDecorator(target) { + util.decorateType(target, typeName); + }; + }; + } +}); + +// node_modules/protobufjs/src/root.js +var require_root = __commonJS({ + "node_modules/protobufjs/src/root.js"(exports2, module2) { + "use strict"; + module2.exports = Root; + var Namespace = require_namespace(); + ((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = "Root"; + var Field = require_field(); + var Enum = require_enum(); + var OneOf = require_oneof(); + var util = require_util10(); + var Type; + var parse3; + var common; + function Root(options) { + Namespace.call(this, "", options); + this.deferred = []; + this.files = []; + this._edition = "proto2"; + this._fullyQualifiedObjects = {}; + } + Root.fromJSON = function fromJSON(json, root) { + if (!root) + root = new Root(); + if (json.options) + root.setOptions(json.options); + return root.addJSON(json.nested).resolveAll(); + }; + Root.prototype.resolvePath = util.path.resolve; + Root.prototype.fetch = util.fetch; + function SYNC() { + } + Root.prototype.load = function load(filename, options, callback) { + if (typeof options === "function") { + callback = options; + options = void 0; + } + var self2 = this; + if (!callback) { + return util.asPromise(load, self2, filename, options); + } + var sync = callback === SYNC; + function finish(err, root) { + if (!callback) { + return; + } + if (sync) { + throw err; + } + if (root) { + root.resolveAll(); + } + var cb = callback; + callback = null; + cb(err, root); + } + function getBundledFileName(filename2) { + var idx = filename2.lastIndexOf("google/protobuf/"); + if (idx > -1) { + var altname = filename2.substring(idx); + if (altname in common) return altname; + } + return null; + } + function process2(filename2, source) { + try { + if (util.isString(source) && source.charAt(0) === "{") + source = JSON.parse(source); + if (!util.isString(source)) + self2.setOptions(source.options).addJSON(source.nested); + else { + parse3.filename = filename2; + var parsed = parse3(source, self2, options), resolved2, i2 = 0; + if (parsed.imports) { + for (; i2 < parsed.imports.length; ++i2) + if (resolved2 = getBundledFileName(parsed.imports[i2]) || self2.resolvePath(filename2, parsed.imports[i2])) + fetch3(resolved2); + } + if (parsed.weakImports) { + for (i2 = 0; i2 < parsed.weakImports.length; ++i2) + if (resolved2 = getBundledFileName(parsed.weakImports[i2]) || self2.resolvePath(filename2, parsed.weakImports[i2])) + fetch3(resolved2, true); + } + } + } catch (err) { + finish(err); + } + if (!sync && !queued) { + finish(null, self2); + } + } + function fetch3(filename2, weak) { + filename2 = getBundledFileName(filename2) || filename2; + if (self2.files.indexOf(filename2) > -1) { + return; + } + self2.files.push(filename2); + if (filename2 in common) { + if (sync) { + process2(filename2, common[filename2]); + } else { + ++queued; + setTimeout(function() { + --queued; + process2(filename2, common[filename2]); + }); + } + return; + } + if (sync) { + var source; + try { + source = util.fs.readFileSync(filename2).toString("utf8"); + } catch (err) { + if (!weak) + finish(err); + return; + } + process2(filename2, source); + } else { + ++queued; + self2.fetch(filename2, function(err, source2) { + --queued; + if (!callback) { + return; + } + if (err) { + if (!weak) + finish(err); + else if (!queued) + finish(null, self2); + return; + } + process2(filename2, source2); + }); + } + } + var queued = 0; + if (util.isString(filename)) { + filename = [filename]; + } + for (var i = 0, resolved; i < filename.length; ++i) + if (resolved = self2.resolvePath("", filename[i])) + fetch3(resolved); + if (sync) { + self2.resolveAll(); + return self2; + } + if (!queued) { + finish(null, self2); + } + return self2; + }; + Root.prototype.loadSync = function loadSync(filename, options) { + if (!util.isNode) + throw Error("not supported"); + return this.load(filename, options, SYNC); + }; + Root.prototype.resolveAll = function resolveAll() { + if (!this._needsRecursiveResolve) return this; + if (this.deferred.length) + throw Error("unresolvable extensions: " + this.deferred.map(function(field) { + return "'extend " + field.extend + "' in " + field.parent.fullName; + }).join(", ")); + return Namespace.prototype.resolveAll.call(this); + }; + var exposeRe = /^[A-Z]/; + function tryHandleExtension(root, field) { + var extendedType = field.parent.lookup(field.extend); + if (extendedType) { + var sisterField = new Field(field.fullName, field.id, field.type, field.rule, void 0, field.options); + if (extendedType.get(sisterField.name)) { + return true; + } + sisterField.declaringField = field; + field.extensionField = sisterField; + extendedType.add(sisterField); + return true; + } + return false; + } + Root.prototype._handleAdd = function _handleAdd(object) { + if (object instanceof Field) { + if ( + /* an extension field (implies not part of a oneof) */ + object.extend !== void 0 && /* not already handled */ + !object.extensionField + ) { + if (!tryHandleExtension(this, object)) + this.deferred.push(object); + } + } else if (object instanceof Enum) { + if (exposeRe.test(object.name)) + object.parent[object.name] = object.values; + } else if (!(object instanceof OneOf)) { + if (object instanceof Type) + for (var i = 0; i < this.deferred.length; ) + if (tryHandleExtension(this, this.deferred[i])) + this.deferred.splice(i, 1); + else + ++i; + for (var j = 0; j < /* initializes */ + object.nestedArray.length; ++j) + this._handleAdd(object._nestedArray[j]); + if (exposeRe.test(object.name)) + object.parent[object.name] = object; + } + if (object instanceof Type || object instanceof Enum || object instanceof Field) { + this._fullyQualifiedObjects[object.fullName] = object; + } + }; + Root.prototype._handleRemove = function _handleRemove(object) { + if (object instanceof Field) { + if ( + /* an extension field */ + object.extend !== void 0 + ) { + if ( + /* already handled */ + object.extensionField + ) { + object.extensionField.parent.remove(object.extensionField); + object.extensionField = null; + } else { + var index = this.deferred.indexOf(object); + if (index > -1) + this.deferred.splice(index, 1); + } + } + } else if (object instanceof Enum) { + if (exposeRe.test(object.name)) + delete object.parent[object.name]; + } else if (object instanceof Namespace) { + for (var i = 0; i < /* initializes */ + object.nestedArray.length; ++i) + this._handleRemove(object._nestedArray[i]); + if (exposeRe.test(object.name)) + delete object.parent[object.name]; + } + delete this._fullyQualifiedObjects[object.fullName]; + }; + Root._configure = function(Type_, parse_, common_) { + Type = Type_; + parse3 = parse_; + common = common_; + }; + } +}); + +// node_modules/protobufjs/src/util.js +var require_util10 = __commonJS({ + "node_modules/protobufjs/src/util.js"(exports2, module2) { + "use strict"; + var util = module2.exports = require_minimal(); + var roots = require_roots(); + var Type; + var Enum; + util.codegen = require_codegen(); + util.fetch = require_fetch2(); + util.path = require_path(); + util.patterns = require_patterns(); + var reservedRe = util.patterns.reservedRe; + var unsafePropertyRe = util.patterns.unsafePropertyRe; + util.fs = util.inquire("fs"); + util.toArray = function toArray(object) { + if (object) { + var keys = Object.keys(object), array = new Array(keys.length), index = 0; + while (index < keys.length) + array[index] = object[keys[index++]]; + return array; + } + return []; + }; + util.toObject = function toObject(array) { + var object = {}, index = 0; + while (index < array.length) { + var key = array[index++], val = array[index++]; + if (val !== void 0) + object[key] = val; + } + return object; + }; + util.isReserved = function isReserved(name) { + return reservedRe.test(name); + }; + util.safeProp = function safeProp(prop) { + if (!/^[$\w_]+$/.test(prop) || reservedRe.test(prop)) + return "[" + JSON.stringify(prop) + "]"; + return "." + prop; + }; + util.ucFirst = function ucFirst(str) { + return str.charAt(0).toUpperCase() + str.substring(1); + }; + var camelCaseRe = /_([a-z])/g; + util.camelCase = function camelCase(str) { + return str.substring(0, 1) + str.substring(1).replace(camelCaseRe, function($0, $1) { + return $1.toUpperCase(); + }); + }; + util.compareFieldsById = function compareFieldsById(a, b) { + return a.id - b.id; + }; + util.decorateType = function decorateType(ctor, typeName) { + if (ctor.$type) { + if (typeName && ctor.$type.name !== typeName) { + util.decorateRoot.remove(ctor.$type); + ctor.$type.name = typeName; + util.decorateRoot.add(ctor.$type); + } + return ctor.$type; + } + if (!Type) + Type = require_type(); + var type = new Type(typeName || ctor.name); + util.decorateRoot.add(type); + type.ctor = ctor; + Object.defineProperty(ctor, "$type", { value: type, enumerable: false }); + Object.defineProperty(ctor.prototype, "$type", { value: type, enumerable: false }); + return type; + }; + var decorateEnumIndex = 0; + util.decorateEnum = function decorateEnum(object) { + if (object.$type) + return object.$type; + if (!Enum) + Enum = require_enum(); + var enm = new Enum("Enum" + decorateEnumIndex++, object); + util.decorateRoot.add(enm); + Object.defineProperty(object, "$type", { value: enm, enumerable: false }); + return enm; + }; + util.setProperty = function setProperty(dst, path, value, ifNotSet) { + function setProp(dst2, path2, value2) { + var part = path2.shift(); + if (unsafePropertyRe.test(part)) + return dst2; + if (path2.length > 0) { + dst2[part] = setProp(dst2[part] || {}, path2, value2); + } else { + var prevValue = dst2[part]; + if (prevValue && ifNotSet) + return dst2; + if (prevValue) + value2 = [].concat(prevValue).concat(value2); + dst2[part] = value2; + } + return dst2; + } + if (typeof dst !== "object") + throw TypeError("dst must be an object"); + if (!path) + throw TypeError("path must be specified"); + path = path.split("."); + return setProp(dst, path, value); + }; + Object.defineProperty(util, "decorateRoot", { + get: function() { + return roots["decorated"] || (roots["decorated"] = new (require_root())()); + } + }); + } +}); + +// node_modules/protobufjs/src/types.js +var require_types2 = __commonJS({ + "node_modules/protobufjs/src/types.js"(exports2) { + "use strict"; + var types = exports2; + var util = require_util10(); + var s = [ + "double", + // 0 + "float", + // 1 + "int32", + // 2 + "uint32", + // 3 + "sint32", + // 4 + "fixed32", + // 5 + "sfixed32", + // 6 + "int64", + // 7 + "uint64", + // 8 + "sint64", + // 9 + "fixed64", + // 10 + "sfixed64", + // 11 + "bool", + // 12 + "string", + // 13 + "bytes" + // 14 + ]; + function bake(values, offset) { + var i = 0, o = /* @__PURE__ */ Object.create(null); + offset |= 0; + while (i < values.length) o[s[i + offset]] = values[i++]; + return o; + } + types.basic = bake([ + /* double */ + 1, + /* float */ + 5, + /* int32 */ + 0, + /* uint32 */ + 0, + /* sint32 */ + 0, + /* fixed32 */ + 5, + /* sfixed32 */ + 5, + /* int64 */ + 0, + /* uint64 */ + 0, + /* sint64 */ + 0, + /* fixed64 */ + 1, + /* sfixed64 */ + 1, + /* bool */ + 0, + /* string */ + 2, + /* bytes */ + 2 + ]); + types.defaults = bake([ + /* double */ + 0, + /* float */ + 0, + /* int32 */ + 0, + /* uint32 */ + 0, + /* sint32 */ + 0, + /* fixed32 */ + 0, + /* sfixed32 */ + 0, + /* int64 */ + 0, + /* uint64 */ + 0, + /* sint64 */ + 0, + /* fixed64 */ + 0, + /* sfixed64 */ + 0, + /* bool */ + false, + /* string */ + "", + /* bytes */ + util.emptyArray, + /* message */ + null + ]); + types.long = bake([ + /* int64 */ + 0, + /* uint64 */ + 0, + /* sint64 */ + 0, + /* fixed64 */ + 1, + /* sfixed64 */ + 1 + ], 7); + types.mapKey = bake([ + /* int32 */ + 0, + /* uint32 */ + 0, + /* sint32 */ + 0, + /* fixed32 */ + 5, + /* sfixed32 */ + 5, + /* int64 */ + 0, + /* uint64 */ + 0, + /* sint64 */ + 0, + /* fixed64 */ + 1, + /* sfixed64 */ + 1, + /* bool */ + 0, + /* string */ + 2 + ], 2); + types.packed = bake([ + /* double */ + 1, + /* float */ + 5, + /* int32 */ + 0, + /* uint32 */ + 0, + /* sint32 */ + 0, + /* fixed32 */ + 5, + /* sfixed32 */ + 5, + /* int64 */ + 0, + /* uint64 */ + 0, + /* sint64 */ + 0, + /* fixed64 */ + 1, + /* sfixed64 */ + 1, + /* bool */ + 0 + ]); + } +}); + +// node_modules/protobufjs/src/field.js +var require_field = __commonJS({ + "node_modules/protobufjs/src/field.js"(exports2, module2) { + "use strict"; + module2.exports = Field; + var ReflectionObject = require_object(); + ((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = "Field"; + var Enum = require_enum(); + var types = require_types2(); + var util = require_util10(); + var Type; + var ruleRe = /^required|optional|repeated$/; + Field.fromJSON = function fromJSON(name, json) { + var field = new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment); + if (json.edition) + field._edition = json.edition; + field._defaultEdition = "proto3"; + return field; + }; + function Field(name, id, type, rule, extend, options, comment) { + if (util.isObject(rule)) { + comment = extend; + options = rule; + rule = extend = void 0; + } else if (util.isObject(extend)) { + comment = options; + options = extend; + extend = void 0; + } + ReflectionObject.call(this, name, options); + if (!util.isInteger(id) || id < 0) + throw TypeError("id must be a non-negative integer"); + if (!util.isString(type)) + throw TypeError("type must be a string"); + if (rule !== void 0 && !ruleRe.test(rule = rule.toString().toLowerCase())) + throw TypeError("rule must be a string rule"); + if (extend !== void 0 && !util.isString(extend)) + throw TypeError("extend must be a string"); + if (rule === "proto3_optional") { + rule = "optional"; + } + this.rule = rule && rule !== "optional" ? rule : void 0; + this.type = type; + this.id = id; + this.extend = extend || void 0; + this.repeated = rule === "repeated"; + this.map = false; + this.message = null; + this.partOf = null; + this.typeDefault = null; + this.defaultValue = null; + this.long = util.Long ? types.long[type] !== void 0 : ( + /* istanbul ignore next */ + false + ); + this.bytes = type === "bytes"; + this.resolvedType = null; + this.extensionField = null; + this.declaringField = null; + this.comment = comment; + } + Object.defineProperty(Field.prototype, "required", { + get: function() { + return this._features.field_presence === "LEGACY_REQUIRED"; + } + }); + Object.defineProperty(Field.prototype, "optional", { + get: function() { + return !this.required; + } + }); + Object.defineProperty(Field.prototype, "delimited", { + get: function() { + return this.resolvedType instanceof Type && this._features.message_encoding === "DELIMITED"; + } + }); + Object.defineProperty(Field.prototype, "packed", { + get: function() { + return this._features.repeated_field_encoding === "PACKED"; + } + }); + Object.defineProperty(Field.prototype, "hasPresence", { + get: function() { + if (this.repeated || this.map) { + return false; + } + return this.partOf || // oneofs + this.declaringField || this.extensionField || // extensions + this._features.field_presence !== "IMPLICIT"; + } + }); + Field.prototype.setOption = function setOption(name, value, ifNotSet) { + return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet); + }; + Field.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "edition", + this._editionToJSON(), + "rule", + this.rule !== "optional" && this.rule || void 0, + "type", + this.type, + "id", + this.id, + "extend", + this.extend, + "options", + this.options, + "comment", + keepComments ? this.comment : void 0 + ]); + }; + Field.prototype.resolve = function resolve() { + if (this.resolved) + return this; + if ((this.typeDefault = types.defaults[this.type]) === void 0) { + this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type); + if (this.resolvedType instanceof Type) + this.typeDefault = null; + else + this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; + } else if (this.options && this.options.proto3_optional) { + this.typeDefault = null; + } + if (this.options && this.options["default"] != null) { + this.typeDefault = this.options["default"]; + if (this.resolvedType instanceof Enum && typeof this.typeDefault === "string") + this.typeDefault = this.resolvedType.values[this.typeDefault]; + } + if (this.options) { + if (this.options.packed !== void 0 && this.resolvedType && !(this.resolvedType instanceof Enum)) + delete this.options.packed; + if (!Object.keys(this.options).length) + this.options = void 0; + } + if (this.long) { + this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type.charAt(0) === "u"); + if (Object.freeze) + Object.freeze(this.typeDefault); + } else if (this.bytes && typeof this.typeDefault === "string") { + var buf; + if (util.base64.test(this.typeDefault)) + util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0); + else + util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0); + this.typeDefault = buf; + } + if (this.map) + this.defaultValue = util.emptyObject; + else if (this.repeated) + this.defaultValue = util.emptyArray; + else + this.defaultValue = this.typeDefault; + if (this.parent instanceof Type) + this.parent.ctor.prototype[this.name] = this.defaultValue; + return ReflectionObject.prototype.resolve.call(this); + }; + Field.prototype._inferLegacyProtoFeatures = function _inferLegacyProtoFeatures(edition) { + if (edition !== "proto2" && edition !== "proto3") { + return {}; + } + var features = {}; + if (this.rule === "required") { + features.field_presence = "LEGACY_REQUIRED"; + } + if (this.parent && types.defaults[this.type] === void 0) { + var type = this.parent.get(this.type.split(".").pop()); + if (type && type instanceof Type && type.group) { + features.message_encoding = "DELIMITED"; + } + } + if (this.getOption("packed") === true) { + features.repeated_field_encoding = "PACKED"; + } else if (this.getOption("packed") === false) { + features.repeated_field_encoding = "EXPANDED"; + } + return features; + }; + Field.prototype._resolveFeatures = function _resolveFeatures(edition) { + return ReflectionObject.prototype._resolveFeatures.call(this, this._edition || edition); + }; + Field.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) { + if (typeof fieldType === "function") + fieldType = util.decorateType(fieldType).name; + else if (fieldType && typeof fieldType === "object") + fieldType = util.decorateEnum(fieldType).name; + return function fieldDecorator(prototype, fieldName) { + util.decorateType(prototype.constructor).add(new Field(fieldName, fieldId, fieldType, fieldRule, { "default": defaultValue })); + }; + }; + Field._configure = function configure(Type_) { + Type = Type_; + }; + } +}); + +// node_modules/protobufjs/src/oneof.js +var require_oneof = __commonJS({ + "node_modules/protobufjs/src/oneof.js"(exports2, module2) { + "use strict"; + module2.exports = OneOf; + var ReflectionObject = require_object(); + ((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = "OneOf"; + var Field = require_field(); + var util = require_util10(); + function OneOf(name, fieldNames, options, comment) { + if (!Array.isArray(fieldNames)) { + options = fieldNames; + fieldNames = void 0; + } + ReflectionObject.call(this, name, options); + if (!(fieldNames === void 0 || Array.isArray(fieldNames))) + throw TypeError("fieldNames must be an Array"); + this.oneof = fieldNames || []; + this.fieldsArray = []; + this.comment = comment; + } + OneOf.fromJSON = function fromJSON(name, json) { + return new OneOf(name, json.oneof, json.options, json.comment); + }; + OneOf.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "options", + this.options, + "oneof", + this.oneof, + "comment", + keepComments ? this.comment : void 0 + ]); + }; + function addFieldsToParent(oneof) { + if (oneof.parent) { + for (var i = 0; i < oneof.fieldsArray.length; ++i) + if (!oneof.fieldsArray[i].parent) + oneof.parent.add(oneof.fieldsArray[i]); + } + } + OneOf.prototype.add = function add(field) { + if (!(field instanceof Field)) + throw TypeError("field must be a Field"); + if (field.parent && field.parent !== this.parent) + field.parent.remove(field); + this.oneof.push(field.name); + this.fieldsArray.push(field); + field.partOf = this; + addFieldsToParent(this); + return this; + }; + OneOf.prototype.remove = function remove(field) { + if (!(field instanceof Field)) + throw TypeError("field must be a Field"); + var index = this.fieldsArray.indexOf(field); + if (index < 0) + throw Error(field + " is not a member of " + this); + this.fieldsArray.splice(index, 1); + index = this.oneof.indexOf(field.name); + if (index > -1) + this.oneof.splice(index, 1); + field.partOf = null; + return this; + }; + OneOf.prototype.onAdd = function onAdd(parent) { + ReflectionObject.prototype.onAdd.call(this, parent); + var self2 = this; + for (var i = 0; i < this.oneof.length; ++i) { + var field = parent.get(this.oneof[i]); + if (field && !field.partOf) { + field.partOf = self2; + self2.fieldsArray.push(field); + } + } + addFieldsToParent(this); + }; + OneOf.prototype.onRemove = function onRemove(parent) { + for (var i = 0, field; i < this.fieldsArray.length; ++i) + if ((field = this.fieldsArray[i]).parent) + field.parent.remove(field); + ReflectionObject.prototype.onRemove.call(this, parent); + }; + Object.defineProperty(OneOf.prototype, "isProto3Optional", { + get: function() { + if (this.fieldsArray == null || this.fieldsArray.length !== 1) { + return false; + } + var field = this.fieldsArray[0]; + return field.options != null && field.options["proto3_optional"] === true; + } + }); + OneOf.d = function decorateOneOf() { + var fieldNames = new Array(arguments.length), index = 0; + while (index < arguments.length) + fieldNames[index] = arguments[index++]; + return function oneOfDecorator(prototype, oneofName) { + util.decorateType(prototype.constructor).add(new OneOf(oneofName, fieldNames)); + Object.defineProperty(prototype, oneofName, { + get: util.oneOfGetter(fieldNames), + set: util.oneOfSetter(fieldNames) + }); + }; + }; + } +}); + +// node_modules/protobufjs/src/object.js +var require_object = __commonJS({ + "node_modules/protobufjs/src/object.js"(exports2, module2) { + "use strict"; + module2.exports = ReflectionObject; + ReflectionObject.className = "ReflectionObject"; + var OneOf = require_oneof(); + var util = require_util10(); + var Root; + var editions2023Defaults = { enum_type: "OPEN", field_presence: "EXPLICIT", json_format: "ALLOW", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "PACKED", utf8_validation: "VERIFY" }; + var proto2Defaults = { enum_type: "CLOSED", field_presence: "EXPLICIT", json_format: "LEGACY_BEST_EFFORT", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "EXPANDED", utf8_validation: "NONE" }; + var proto3Defaults = { enum_type: "OPEN", field_presence: "IMPLICIT", json_format: "ALLOW", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "PACKED", utf8_validation: "VERIFY" }; + function ReflectionObject(name, options) { + if (!util.isString(name)) + throw TypeError("name must be a string"); + if (options && !util.isObject(options)) + throw TypeError("options must be an object"); + this.options = options; + this.parsedOptions = null; + this.name = name; + this._edition = null; + this._defaultEdition = "proto2"; + this._features = {}; + this._featuresResolved = false; + this.parent = null; + this.resolved = false; + this.comment = null; + this.filename = null; + } + Object.defineProperties(ReflectionObject.prototype, { + /** + * Reference to the root namespace. + * @name ReflectionObject#root + * @type {Root} + * @readonly + */ + root: { + get: function() { + var ptr = this; + while (ptr.parent !== null) + ptr = ptr.parent; + return ptr; + } + }, + /** + * Full name including leading dot. + * @name ReflectionObject#fullName + * @type {string} + * @readonly + */ + fullName: { + get: function() { + var path = [this.name], ptr = this.parent; + while (ptr) { + path.unshift(ptr.name); + ptr = ptr.parent; + } + return path.join("."); + } + } + }); + ReflectionObject.prototype.toJSON = /* istanbul ignore next */ + function toJSON() { + throw Error(); + }; + ReflectionObject.prototype.onAdd = function onAdd(parent) { + if (this.parent && this.parent !== parent) + this.parent.remove(this); + this.parent = parent; + this.resolved = false; + var root = parent.root; + if (root instanceof Root) + root._handleAdd(this); + }; + ReflectionObject.prototype.onRemove = function onRemove(parent) { + var root = parent.root; + if (root instanceof Root) + root._handleRemove(this); + this.parent = null; + this.resolved = false; + }; + ReflectionObject.prototype.resolve = function resolve() { + if (this.resolved) + return this; + if (this.root instanceof Root) + this.resolved = true; + return this; + }; + ReflectionObject.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) { + return this._resolveFeatures(this._edition || edition); + }; + ReflectionObject.prototype._resolveFeatures = function _resolveFeatures(edition) { + if (this._featuresResolved) { + return; + } + var defaults2 = {}; + if (!edition) { + throw new Error("Unknown edition for " + this.fullName); + } + var protoFeatures = Object.assign( + this.options ? Object.assign({}, this.options.features) : {}, + this._inferLegacyProtoFeatures(edition) + ); + if (this._edition) { + if (edition === "proto2") { + defaults2 = Object.assign({}, proto2Defaults); + } else if (edition === "proto3") { + defaults2 = Object.assign({}, proto3Defaults); + } else if (edition === "2023") { + defaults2 = Object.assign({}, editions2023Defaults); + } else { + throw new Error("Unknown edition: " + edition); + } + this._features = Object.assign(defaults2, protoFeatures || {}); + this._featuresResolved = true; + return; + } + if (this.partOf instanceof OneOf) { + var lexicalParentFeaturesCopy = Object.assign({}, this.partOf._features); + this._features = Object.assign(lexicalParentFeaturesCopy, protoFeatures || {}); + } else if (this.declaringField) { + } else if (this.parent) { + var parentFeaturesCopy = Object.assign({}, this.parent._features); + this._features = Object.assign(parentFeaturesCopy, protoFeatures || {}); + } else { + throw new Error("Unable to find a parent for " + this.fullName); + } + if (this.extensionField) { + this.extensionField._features = this._features; + } + this._featuresResolved = true; + }; + ReflectionObject.prototype._inferLegacyProtoFeatures = function _inferLegacyProtoFeatures() { + return {}; + }; + ReflectionObject.prototype.getOption = function getOption(name) { + if (this.options) + return this.options[name]; + return void 0; + }; + ReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) { + if (name === "__proto__") + return this; + if (!this.options) + this.options = {}; + if (/^features\./.test(name)) { + util.setProperty(this.options, name, value, ifNotSet); + } else if (!ifNotSet || this.options[name] === void 0) { + if (this.getOption(name) !== value) this.resolved = false; + this.options[name] = value; + } + return this; + }; + ReflectionObject.prototype.setParsedOption = function setParsedOption(name, value, propName) { + if (name === "__proto__") + return this; + if (!this.parsedOptions) { + this.parsedOptions = []; + } + var parsedOptions = this.parsedOptions; + if (propName) { + var opt = parsedOptions.find(function(opt2) { + return Object.prototype.hasOwnProperty.call(opt2, name); + }); + if (opt) { + var newValue = opt[name]; + util.setProperty(newValue, propName, value); + } else { + opt = {}; + opt[name] = util.setProperty({}, propName, value); + parsedOptions.push(opt); + } + } else { + var newOpt = {}; + newOpt[name] = value; + parsedOptions.push(newOpt); + } + return this; + }; + ReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) { + if (options) + for (var keys = Object.keys(options), i = 0; i < keys.length; ++i) + this.setOption(keys[i], options[keys[i]], ifNotSet); + return this; + }; + ReflectionObject.prototype.toString = function toString() { + var className = this.constructor.className, fullName = this.fullName; + if (fullName.length) + return className + " " + fullName; + return className; + }; + ReflectionObject.prototype._editionToJSON = function _editionToJSON() { + if (!this._edition || this._edition === "proto3") { + return void 0; + } + return this._edition; + }; + ReflectionObject._configure = function(Root_) { + Root = Root_; + }; + } +}); + +// node_modules/protobufjs/src/enum.js +var require_enum = __commonJS({ + "node_modules/protobufjs/src/enum.js"(exports2, module2) { + "use strict"; + module2.exports = Enum; + var ReflectionObject = require_object(); + ((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = "Enum"; + var Namespace = require_namespace(); + var util = require_util10(); + function Enum(name, values, options, comment, comments, valuesOptions) { + ReflectionObject.call(this, name, options); + if (values && typeof values !== "object") + throw TypeError("values must be an object"); + this.valuesById = {}; + this.values = Object.create(this.valuesById); + this.comment = comment; + this.comments = comments || {}; + this.valuesOptions = valuesOptions; + this._valuesFeatures = {}; + this.reserved = void 0; + if (values) { + for (var keys = Object.keys(values), i = 0; i < keys.length; ++i) + if (keys[i] !== "__proto__" && typeof values[keys[i]] === "number") + this.valuesById[this.values[keys[i]] = values[keys[i]]] = keys[i]; + } + } + Enum.prototype._resolveFeatures = function _resolveFeatures(edition) { + edition = this._edition || edition; + ReflectionObject.prototype._resolveFeatures.call(this, edition); + Object.keys(this.values).forEach((key) => { + var parentFeaturesCopy = Object.assign({}, this._features); + this._valuesFeatures[key] = Object.assign(parentFeaturesCopy, this.valuesOptions && this.valuesOptions[key] && this.valuesOptions[key].features); + }); + return this; + }; + Enum.fromJSON = function fromJSON(name, json) { + var enm = new Enum(name, json.values, json.options, json.comment, json.comments); + enm.reserved = json.reserved; + if (json.edition) + enm._edition = json.edition; + enm._defaultEdition = "proto3"; + return enm; + }; + Enum.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "edition", + this._editionToJSON(), + "options", + this.options, + "valuesOptions", + this.valuesOptions, + "values", + this.values, + "reserved", + this.reserved && this.reserved.length ? this.reserved : void 0, + "comment", + keepComments ? this.comment : void 0, + "comments", + keepComments ? this.comments : void 0 + ]); + }; + Enum.prototype.add = function add(name, id, comment, options) { + if (!util.isString(name)) + throw TypeError("name must be a string"); + if (!util.isInteger(id)) + throw TypeError("id must be an integer"); + if (name === "__proto__") + return this; + if (this.values[name] !== void 0) + throw Error("duplicate name '" + name + "' in " + this); + if (this.isReservedId(id)) + throw Error("id " + id + " is reserved in " + this); + if (this.isReservedName(name)) + throw Error("name '" + name + "' is reserved in " + this); + if (this.valuesById[id] !== void 0) { + if (!(this.options && this.options.allow_alias)) + throw Error("duplicate id " + id + " in " + this); + this.values[name] = id; + } else + this.valuesById[this.values[name] = id] = name; + if (options) { + if (this.valuesOptions === void 0) + this.valuesOptions = {}; + this.valuesOptions[name] = options || null; + } + this.comments[name] = comment || null; + return this; + }; + Enum.prototype.remove = function remove(name) { + if (!util.isString(name)) + throw TypeError("name must be a string"); + var val = this.values[name]; + if (val == null) + throw Error("name '" + name + "' does not exist in " + this); + delete this.valuesById[val]; + delete this.values[name]; + delete this.comments[name]; + if (this.valuesOptions) + delete this.valuesOptions[name]; + return this; + }; + Enum.prototype.isReservedId = function isReservedId(id) { + return Namespace.isReservedId(this.reserved, id); + }; + Enum.prototype.isReservedName = function isReservedName(name) { + return Namespace.isReservedName(this.reserved, name); + }; + } +}); + +// node_modules/protobufjs/src/encoder.js +var require_encoder = __commonJS({ + "node_modules/protobufjs/src/encoder.js"(exports2, module2) { + "use strict"; + module2.exports = encoder; + var Enum = require_enum(); + var types = require_types2(); + var util = require_util10(); + function genTypePartial(gen, field, fieldIndex, ref) { + return field.delimited ? gen("types[%i].encode(%s,w.uint32(%i)).uint32(%i)", fieldIndex, ref, (field.id << 3 | 3) >>> 0, (field.id << 3 | 4) >>> 0) : gen("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()", fieldIndex, ref, (field.id << 3 | 2) >>> 0); + } + function encoder(mtype) { + var gen = util.codegen(["m", "w"], mtype.name + "$encode")("if(!w)")("w=Writer.create()"); + var i, ref; + var fields = ( + /* initializes */ + mtype.fieldsArray.slice().sort(util.compareFieldsById) + ); + for (var i = 0; i < fields.length; ++i) { + var field = fields[i].resolve(), index = mtype._fieldsArray.indexOf(field), type = field.resolvedType instanceof Enum ? "int32" : field.type, wireType = types.basic[type]; + ref = "m" + util.safeProp(field.name); + if (field.map) { + gen("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){", ref, field.name)("for(var ks=Object.keys(%s),i=0;i>> 0, 8 | types.mapKey[field.keyType], field.keyType); + if (wireType === void 0) gen("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()", index, ref); + else gen(".uint32(%i).%s(%s[ks[i]]).ldelim()", 16 | wireType, type, ref); + gen("}")("}"); + } else if (field.repeated) { + gen("if(%s!=null&&%s.length){", ref, ref); + if (field.packed && types.packed[type] !== void 0) { + gen("w.uint32(%i).fork()", (field.id << 3 | 2) >>> 0)("for(var i=0;i<%s.length;++i)", ref)("w.%s(%s[i])", type, ref)("w.ldelim()"); + } else { + gen("for(var i=0;i<%s.length;++i)", ref); + if (wireType === void 0) + genTypePartial(gen, field, index, ref + "[i]"); + else gen("w.uint32(%i).%s(%s[i])", (field.id << 3 | wireType) >>> 0, type, ref); + } + gen("}"); + } else { + if (field.optional) gen("if(%s!=null&&Object.hasOwnProperty.call(m,%j))", ref, field.name); + if (wireType === void 0) + genTypePartial(gen, field, index, ref); + else gen("w.uint32(%i).%s(%s)", (field.id << 3 | wireType) >>> 0, type, ref); + } + } + return gen("return w"); + } + } +}); + +// node_modules/protobufjs/src/index-light.js +var require_index_light = __commonJS({ + "node_modules/protobufjs/src/index-light.js"(exports2, module2) { + "use strict"; + var protobuf = module2.exports = require_index_minimal(); + protobuf.build = "light"; + function load(filename, root, callback) { + if (typeof root === "function") { + callback = root; + root = new protobuf.Root(); + } else if (!root) + root = new protobuf.Root(); + return root.load(filename, callback); + } + protobuf.load = load; + function loadSync(filename, root) { + if (!root) + root = new protobuf.Root(); + return root.loadSync(filename); + } + protobuf.loadSync = loadSync; + protobuf.encoder = require_encoder(); + protobuf.decoder = require_decoder(); + protobuf.verifier = require_verifier(); + protobuf.converter = require_converter(); + protobuf.ReflectionObject = require_object(); + protobuf.Namespace = require_namespace(); + protobuf.Root = require_root(); + protobuf.Enum = require_enum(); + protobuf.Type = require_type(); + protobuf.Field = require_field(); + protobuf.OneOf = require_oneof(); + protobuf.MapField = require_mapfield(); + protobuf.Service = require_service3(); + protobuf.Method = require_method(); + protobuf.Message = require_message(); + protobuf.wrappers = require_wrappers(); + protobuf.types = require_types2(); + protobuf.util = require_util10(); + protobuf.ReflectionObject._configure(protobuf.Root); + protobuf.Namespace._configure(protobuf.Type, protobuf.Service, protobuf.Enum); + protobuf.Root._configure(protobuf.Type); + protobuf.Field._configure(protobuf.Type); + } +}); + +// node_modules/protobufjs/src/tokenize.js +var require_tokenize = __commonJS({ + "node_modules/protobufjs/src/tokenize.js"(exports2, module2) { + "use strict"; + module2.exports = tokenize; + var delimRe = /[\s{}=;:[\],'"()<>]/g; + var stringDoubleRe = /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g; + var stringSingleRe = /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g; + var setCommentRe = /^ *[*/]+ */; + var setCommentAltRe = /^\s*\*?\/*/; + var setCommentSplitRe = /\n/g; + var whitespaceRe = /\s/; + var unescapeRe = /\\(.?)/g; + var unescapeMap = { + "0": "\0", + "r": "\r", + "n": "\n", + "t": " " + }; + function unescape2(str) { + return str.replace(unescapeRe, function($0, $1) { + switch ($1) { + case "\\": + case "": + return $1; + default: + return unescapeMap[$1] || ""; + } + }); + } + tokenize.unescape = unescape2; + function tokenize(source, alternateCommentMode) { + source = source.toString(); + var offset = 0, length = source.length, line = 1, lastCommentLine = 0, comments = {}; + var stack = []; + var stringDelim = null; + function illegal(subject) { + return Error("illegal " + subject + " (line " + line + ")"); + } + function readString() { + var re = stringDelim === "'" ? stringSingleRe : stringDoubleRe; + re.lastIndex = offset - 1; + var match = re.exec(source); + if (!match) + throw illegal("string"); + offset = re.lastIndex; + push(stringDelim); + stringDelim = null; + return unescape2(match[1]); + } + function charAt(pos) { + return source.charAt(pos); + } + function setComment(start, end, isLeading) { + var comment = { + type: source.charAt(start++), + lineEmpty: false, + leading: isLeading + }; + var lookback; + if (alternateCommentMode) { + lookback = 2; + } else { + lookback = 3; + } + var commentOffset = start - lookback, c; + do { + if (--commentOffset < 0 || (c = source.charAt(commentOffset)) === "\n") { + comment.lineEmpty = true; + break; + } + } while (c === " " || c === " "); + var lines = source.substring(start, end).split(setCommentSplitRe); + for (var i = 0; i < lines.length; ++i) + lines[i] = lines[i].replace(alternateCommentMode ? setCommentAltRe : setCommentRe, "").trim(); + comment.text = lines.join("\n").trim(); + comments[line] = comment; + lastCommentLine = line; + } + function isDoubleSlashCommentLine(startOffset) { + var endOffset = findEndOfLine(startOffset); + var lineText = source.substring(startOffset, endOffset); + var isComment = /^\s*\/\//.test(lineText); + return isComment; + } + function findEndOfLine(cursor) { + var endOffset = cursor; + while (endOffset < length && charAt(endOffset) !== "\n") { + endOffset++; + } + return endOffset; + } + function next() { + if (stack.length > 0) + return stack.shift(); + if (stringDelim) + return readString(); + var repeat, prev, curr, start, isDoc, isLeadingComment = offset === 0; + do { + if (offset === length) + return null; + repeat = false; + while (whitespaceRe.test(curr = charAt(offset))) { + if (curr === "\n") { + isLeadingComment = true; + ++line; + } + if (++offset === length) + return null; + } + if (charAt(offset) === "/") { + if (++offset === length) { + throw illegal("comment"); + } + if (charAt(offset) === "/") { + if (!alternateCommentMode) { + isDoc = charAt(start = offset + 1) === "/"; + while (charAt(++offset) !== "\n") { + if (offset === length) { + return null; + } + } + ++offset; + if (isDoc) { + setComment(start, offset - 1, isLeadingComment); + isLeadingComment = true; + } + ++line; + repeat = true; + } else { + start = offset; + isDoc = false; + if (isDoubleSlashCommentLine(offset - 1)) { + isDoc = true; + do { + offset = findEndOfLine(offset); + if (offset === length) { + break; + } + offset++; + if (!isLeadingComment) { + break; + } + } while (isDoubleSlashCommentLine(offset)); + } else { + offset = Math.min(length, findEndOfLine(offset) + 1); + } + if (isDoc) { + setComment(start, offset, isLeadingComment); + isLeadingComment = true; + } + line++; + repeat = true; + } + } else if ((curr = charAt(offset)) === "*") { + start = offset + 1; + isDoc = alternateCommentMode || charAt(start) === "*"; + do { + if (curr === "\n") { + ++line; + } + if (++offset === length) { + throw illegal("comment"); + } + prev = curr; + curr = charAt(offset); + } while (prev !== "*" || curr !== "/"); + ++offset; + if (isDoc) { + setComment(start, offset - 2, isLeadingComment); + isLeadingComment = true; + } + repeat = true; + } else { + return "/"; + } + } + } while (repeat); + var end = offset; + delimRe.lastIndex = 0; + var delim = delimRe.test(charAt(end++)); + if (!delim) + while (end < length && !delimRe.test(charAt(end))) + ++end; + var token = source.substring(offset, offset = end); + if (token === '"' || token === "'") + stringDelim = token; + return token; + } + function push(token) { + stack.push(token); + } + function peek() { + if (!stack.length) { + var token = next(); + if (token === null) + return null; + push(token); + } + return stack[0]; + } + function skip(expected, optional) { + var actual = peek(), equals = actual === expected; + if (equals) { + next(); + return true; + } + if (!optional) + throw illegal("token '" + actual + "', '" + expected + "' expected"); + return false; + } + function cmnt(trailingLine) { + var ret = null; + var comment; + if (trailingLine === void 0) { + comment = comments[line - 1]; + delete comments[line - 1]; + if (comment && (alternateCommentMode || comment.type === "*" || comment.lineEmpty)) { + ret = comment.leading ? comment.text : null; + } + } else { + if (lastCommentLine < trailingLine) { + peek(); + } + comment = comments[trailingLine]; + delete comments[trailingLine]; + if (comment && !comment.lineEmpty && (alternateCommentMode || comment.type === "/")) { + ret = comment.leading ? null : comment.text; + } + } + return ret; + } + return Object.defineProperty({ + next, + peek, + push, + skip, + cmnt + }, "line", { + get: function() { + return line; + } + }); + } + } +}); + +// node_modules/protobufjs/src/parse.js +var require_parse2 = __commonJS({ + "node_modules/protobufjs/src/parse.js"(exports2, module2) { + "use strict"; + module2.exports = parse3; + parse3.filename = null; + parse3.defaults = { keepCase: false }; + var tokenize = require_tokenize(); + var Root = require_root(); + var Type = require_type(); + var Field = require_field(); + var MapField = require_mapfield(); + var OneOf = require_oneof(); + var Enum = require_enum(); + var Service = require_service3(); + var Method = require_method(); + var ReflectionObject = require_object(); + var types = require_types2(); + var util = require_util10(); + var base10Re = /^[1-9][0-9]*$/; + var base10NegRe = /^-?[1-9][0-9]*$/; + var base16Re = /^0[x][0-9a-fA-F]+$/; + var base16NegRe = /^-?0[x][0-9a-fA-F]+$/; + var base8Re = /^0[0-7]+$/; + var base8NegRe = /^-?0[0-7]+$/; + var numberRe = util.patterns.numberRe; + var nameRe = /^[a-zA-Z_][a-zA-Z_0-9]*$/; + var typeRefRe = util.patterns.typeRefRe; + function parse3(source, root, options) { + if (!(root instanceof Root)) { + options = root; + root = new Root(); + } + if (!options) + options = parse3.defaults; + var preferTrailingComment = options.preferTrailingComment || false; + var tn = tokenize(source, options.alternateCommentMode || false), next = tn.next, push = tn.push, peek = tn.peek, skip = tn.skip, cmnt = tn.cmnt; + var head = true, pkg, imports, weakImports, edition = "proto2"; + var ptr = root; + var topLevelObjects = []; + var topLevelOptions = {}; + var applyCase = options.keepCase ? function(name) { + return name; + } : util.camelCase; + function resolveFileFeatures() { + topLevelObjects.forEach((obj) => { + obj._edition = edition; + Object.keys(topLevelOptions).forEach((opt) => { + if (obj.getOption(opt) !== void 0) return; + obj.setOption(opt, topLevelOptions[opt], true); + }); + }); + } + function illegal(token2, name, insideTryCatch) { + var filename = parse3.filename; + if (!insideTryCatch) + parse3.filename = null; + return Error("illegal " + (name || "token") + " '" + token2 + "' (" + (filename ? filename + ", " : "") + "line " + tn.line + ")"); + } + function readString() { + var values = [], token2; + do { + if ((token2 = next()) !== '"' && token2 !== "'") + throw illegal(token2); + values.push(next()); + skip(token2); + token2 = peek(); + } while (token2 === '"' || token2 === "'"); + return values.join(""); + } + function readValue(acceptTypeRef) { + var token2 = next(); + switch (token2) { + case "'": + case '"': + push(token2); + return readString(); + case "true": + case "TRUE": + return true; + case "false": + case "FALSE": + return false; + } + try { + return parseNumber( + token2, + /* insideTryCatch */ + true + ); + } catch (e) { + if (acceptTypeRef && typeRefRe.test(token2)) + return token2; + throw illegal(token2, "value"); + } + } + function readRanges(target, acceptStrings) { + var token2, start; + do { + if (acceptStrings && ((token2 = peek()) === '"' || token2 === "'")) { + var str = readString(); + target.push(str); + if (edition >= 2023) { + throw illegal(str, "id"); + } + } else { + try { + target.push([start = parseId(next()), skip("to", true) ? parseId(next()) : start]); + } catch (err) { + if (acceptStrings && typeRefRe.test(token2) && edition >= 2023) { + target.push(token2); + } else { + throw err; + } + } + } + } while (skip(",", true)); + var dummy = { options: void 0 }; + dummy.setOption = function(name, value) { + if (this.options === void 0) this.options = {}; + this.options[name] = value; + }; + ifBlock( + dummy, + function parseRange_block(token3) { + if (token3 === "option") { + parseOption(dummy, token3); + skip(";"); + } else + throw illegal(token3); + }, + function parseRange_line() { + parseInlineOptions(dummy); + } + ); + } + function parseNumber(token2, insideTryCatch) { + var sign = 1; + if (token2.charAt(0) === "-") { + sign = -1; + token2 = token2.substring(1); + } + switch (token2) { + case "inf": + case "INF": + case "Inf": + return sign * Infinity; + case "nan": + case "NAN": + case "Nan": + case "NaN": + return NaN; + case "0": + return 0; + } + if (base10Re.test(token2)) + return sign * parseInt(token2, 10); + if (base16Re.test(token2)) + return sign * parseInt(token2, 16); + if (base8Re.test(token2)) + return sign * parseInt(token2, 8); + if (numberRe.test(token2)) + return sign * parseFloat(token2); + throw illegal(token2, "number", insideTryCatch); + } + function parseId(token2, acceptNegative) { + switch (token2) { + case "max": + case "MAX": + case "Max": + return 536870911; + case "0": + return 0; + } + if (!acceptNegative && token2.charAt(0) === "-") + throw illegal(token2, "id"); + if (base10NegRe.test(token2)) + return parseInt(token2, 10); + if (base16NegRe.test(token2)) + return parseInt(token2, 16); + if (base8NegRe.test(token2)) + return parseInt(token2, 8); + throw illegal(token2, "id"); + } + function parsePackage() { + if (pkg !== void 0) + throw illegal("package"); + pkg = next(); + if (!typeRefRe.test(pkg)) + throw illegal(pkg, "name"); + ptr = ptr.define(pkg); + skip(";"); + } + function parseImport() { + var token2 = peek(); + var whichImports; + switch (token2) { + case "weak": + whichImports = weakImports || (weakImports = []); + next(); + break; + case "public": + next(); + // eslint-disable-next-line no-fallthrough + default: + whichImports = imports || (imports = []); + break; + } + token2 = readString(); + skip(";"); + whichImports.push(token2); + } + function parseSyntax() { + skip("="); + edition = readString(); + if (edition < 2023) + throw illegal(edition, "syntax"); + skip(";"); + } + function parseEdition() { + skip("="); + edition = readString(); + const supportedEditions = ["2023"]; + if (!supportedEditions.includes(edition)) + throw illegal(edition, "edition"); + skip(";"); + } + function parseCommon(parent, token2) { + switch (token2) { + case "option": + parseOption(parent, token2); + skip(";"); + return true; + case "message": + parseType(parent, token2); + return true; + case "enum": + parseEnum(parent, token2); + return true; + case "service": + parseService(parent, token2); + return true; + case "extend": + parseExtension(parent, token2); + return true; + } + return false; + } + function ifBlock(obj, fnIf, fnElse) { + var trailingLine = tn.line; + if (obj) { + if (typeof obj.comment !== "string") { + obj.comment = cmnt(); + } + obj.filename = parse3.filename; + } + if (skip("{", true)) { + var token2; + while ((token2 = next()) !== "}") + fnIf(token2); + skip(";", true); + } else { + if (fnElse) + fnElse(); + skip(";"); + if (obj && (typeof obj.comment !== "string" || preferTrailingComment)) + obj.comment = cmnt(trailingLine) || obj.comment; + } + } + function parseType(parent, token2) { + if (!nameRe.test(token2 = next())) + throw illegal(token2, "type name"); + var type = new Type(token2); + ifBlock(type, function parseType_block(token3) { + if (parseCommon(type, token3)) + return; + switch (token3) { + case "map": + parseMapField(type, token3); + break; + case "required": + if (edition !== "proto2") + throw illegal(token3); + /* eslint-disable no-fallthrough */ + case "repeated": + parseField(type, token3); + break; + case "optional": + if (edition === "proto3") { + parseField(type, "proto3_optional"); + } else if (edition !== "proto2") { + throw illegal(token3); + } else { + parseField(type, "optional"); + } + break; + case "oneof": + parseOneOf(type, token3); + break; + case "extensions": + readRanges(type.extensions || (type.extensions = [])); + break; + case "reserved": + readRanges(type.reserved || (type.reserved = []), true); + break; + default: + if (edition === "proto2" || !typeRefRe.test(token3)) { + throw illegal(token3); + } + push(token3); + parseField(type, "optional"); + break; + } + }); + parent.add(type); + if (parent === ptr) { + topLevelObjects.push(type); + } + } + function parseField(parent, rule, extend) { + var type = next(); + if (type === "group") { + parseGroup(parent, rule); + return; + } + while (type.endsWith(".") || peek().startsWith(".")) { + type += next(); + } + if (!typeRefRe.test(type)) + throw illegal(type, "type"); + var name = next(); + if (!nameRe.test(name)) + throw illegal(name, "name"); + name = applyCase(name); + skip("="); + var field = new Field(name, parseId(next()), type, rule, extend); + ifBlock(field, function parseField_block(token2) { + if (token2 === "option") { + parseOption(field, token2); + skip(";"); + } else + throw illegal(token2); + }, function parseField_line() { + parseInlineOptions(field); + }); + if (rule === "proto3_optional") { + var oneof = new OneOf("_" + name); + field.setOption("proto3_optional", true); + oneof.add(field); + parent.add(oneof); + } else { + parent.add(field); + } + if (parent === ptr) { + topLevelObjects.push(field); + } + } + function parseGroup(parent, rule) { + if (edition >= 2023) { + throw illegal("group"); + } + var name = next(); + if (!nameRe.test(name)) + throw illegal(name, "name"); + var fieldName = util.lcFirst(name); + if (name === fieldName) + name = util.ucFirst(name); + skip("="); + var id = parseId(next()); + var type = new Type(name); + type.group = true; + var field = new Field(fieldName, id, name, rule); + field.filename = parse3.filename; + ifBlock(type, function parseGroup_block(token2) { + switch (token2) { + case "option": + parseOption(type, token2); + skip(";"); + break; + case "required": + case "repeated": + parseField(type, token2); + break; + case "optional": + if (edition === "proto3") { + parseField(type, "proto3_optional"); + } else { + parseField(type, "optional"); + } + break; + case "message": + parseType(type, token2); + break; + case "enum": + parseEnum(type, token2); + break; + case "reserved": + readRanges(type.reserved || (type.reserved = []), true); + break; + /* istanbul ignore next */ + default: + throw illegal(token2); + } + }); + parent.add(type).add(field); + } + function parseMapField(parent) { + skip("<"); + var keyType = next(); + if (types.mapKey[keyType] === void 0) + throw illegal(keyType, "type"); + skip(","); + var valueType = next(); + if (!typeRefRe.test(valueType)) + throw illegal(valueType, "type"); + skip(">"); + var name = next(); + if (!nameRe.test(name)) + throw illegal(name, "name"); + skip("="); + var field = new MapField(applyCase(name), parseId(next()), keyType, valueType); + ifBlock(field, function parseMapField_block(token2) { + if (token2 === "option") { + parseOption(field, token2); + skip(";"); + } else + throw illegal(token2); + }, function parseMapField_line() { + parseInlineOptions(field); + }); + parent.add(field); + } + function parseOneOf(parent, token2) { + if (!nameRe.test(token2 = next())) + throw illegal(token2, "name"); + var oneof = new OneOf(applyCase(token2)); + ifBlock(oneof, function parseOneOf_block(token3) { + if (token3 === "option") { + parseOption(oneof, token3); + skip(";"); + } else { + push(token3); + parseField(oneof, "optional"); + } + }); + parent.add(oneof); + } + function parseEnum(parent, token2) { + if (!nameRe.test(token2 = next())) + throw illegal(token2, "name"); + var enm = new Enum(token2); + ifBlock(enm, function parseEnum_block(token3) { + switch (token3) { + case "option": + parseOption(enm, token3); + skip(";"); + break; + case "reserved": + readRanges(enm.reserved || (enm.reserved = []), true); + if (enm.reserved === void 0) enm.reserved = []; + break; + default: + parseEnumValue(enm, token3); + } + }); + parent.add(enm); + if (parent === ptr) { + topLevelObjects.push(enm); + } + } + function parseEnumValue(parent, token2) { + if (!nameRe.test(token2)) + throw illegal(token2, "name"); + skip("="); + var value = parseId(next(), true), dummy = { + options: void 0 + }; + dummy.getOption = function(name) { + return this.options[name]; + }; + dummy.setOption = function(name, value2) { + ReflectionObject.prototype.setOption.call(dummy, name, value2); + }; + dummy.setParsedOption = function() { + return void 0; + }; + ifBlock(dummy, function parseEnumValue_block(token3) { + if (token3 === "option") { + parseOption(dummy, token3); + skip(";"); + } else + throw illegal(token3); + }, function parseEnumValue_line() { + parseInlineOptions(dummy); + }); + parent.add(token2, value, dummy.comment, dummy.parsedOptions || dummy.options); + } + function parseOption(parent, token2) { + var option; + var propName; + var isOption = true; + if (token2 === "option") { + token2 = next(); + } + while (token2 !== "=") { + if (token2 === "(") { + var parensValue = next(); + skip(")"); + token2 = "(" + parensValue + ")"; + } + if (isOption) { + isOption = false; + if (token2.includes(".") && !token2.includes("(")) { + var tokens = token2.split("."); + option = tokens[0] + "."; + token2 = tokens[1]; + continue; + } + option = token2; + } else { + propName = propName ? propName += token2 : token2; + } + token2 = next(); + } + var name = propName ? option.concat(propName) : option; + var optionValue = parseOptionValue(parent, name); + propName = propName && propName[0] === "." ? propName.slice(1) : propName; + option = option && option[option.length - 1] === "." ? option.slice(0, -1) : option; + setParsedOption(parent, option, optionValue, propName); + } + function parseOptionValue(parent, name) { + if (skip("{", true)) { + var objectResult = {}; + while (!skip("}", true)) { + if (!nameRe.test(token = next())) { + throw illegal(token, "name"); + } + if (token === null) { + throw illegal(token, "end of input"); + } + var value; + var propName = token; + skip(":", true); + if (peek() === "{") { + value = parseOptionValue(parent, name + "." + token); + } else if (peek() === "[") { + value = []; + var lastValue; + if (skip("[", true)) { + do { + lastValue = readValue(true); + value.push(lastValue); + } while (skip(",", true)); + skip("]"); + if (typeof lastValue !== "undefined") { + setOption(parent, name + "." + token, lastValue); + } + } + } else { + value = readValue(true); + setOption(parent, name + "." + token, value); + } + var prevValue = objectResult[propName]; + if (prevValue) + value = [].concat(prevValue).concat(value); + if (propName !== "__proto__") + objectResult[propName] = value; + skip(",", true); + skip(";", true); + } + return objectResult; + } + var simpleValue = readValue(true); + setOption(parent, name, simpleValue); + return simpleValue; + } + function setOption(parent, name, value) { + if (ptr === parent && /^features\./.test(name)) { + topLevelOptions[name] = value; + return; + } + if (parent.setOption) + parent.setOption(name, value); + } + function setParsedOption(parent, name, value, propName) { + if (parent.setParsedOption) + parent.setParsedOption(name, value, propName); + } + function parseInlineOptions(parent) { + if (skip("[", true)) { + do { + parseOption(parent, "option"); + } while (skip(",", true)); + skip("]"); + } + return parent; + } + function parseService(parent, token2) { + if (!nameRe.test(token2 = next())) + throw illegal(token2, "service name"); + var service = new Service(token2); + ifBlock(service, function parseService_block(token3) { + if (parseCommon(service, token3)) { + return; + } + if (token3 === "rpc") + parseMethod(service, token3); + else + throw illegal(token3); + }); + parent.add(service); + if (parent === ptr) { + topLevelObjects.push(service); + } + } + function parseMethod(parent, token2) { + var commentText = cmnt(); + var type = token2; + if (!nameRe.test(token2 = next())) + throw illegal(token2, "name"); + var name = token2, requestType, requestStream, responseType, responseStream; + skip("("); + if (skip("stream", true)) + requestStream = true; + if (!typeRefRe.test(token2 = next())) + throw illegal(token2); + requestType = token2; + skip(")"); + skip("returns"); + skip("("); + if (skip("stream", true)) + responseStream = true; + if (!typeRefRe.test(token2 = next())) + throw illegal(token2); + responseType = token2; + skip(")"); + var method = new Method(name, type, requestType, responseType, requestStream, responseStream); + method.comment = commentText; + ifBlock(method, function parseMethod_block(token3) { + if (token3 === "option") { + parseOption(method, token3); + skip(";"); + } else + throw illegal(token3); + }); + parent.add(method); + } + function parseExtension(parent, token2) { + if (!typeRefRe.test(token2 = next())) + throw illegal(token2, "reference"); + var reference = token2; + ifBlock(null, function parseExtension_block(token3) { + switch (token3) { + case "required": + case "repeated": + parseField(parent, token3, reference); + break; + case "optional": + if (edition === "proto3") { + parseField(parent, "proto3_optional", reference); + } else { + parseField(parent, "optional", reference); + } + break; + default: + if (edition === "proto2" || !typeRefRe.test(token3)) + throw illegal(token3); + push(token3); + parseField(parent, "optional", reference); + break; + } + }); + } + var token; + while ((token = next()) !== null) { + switch (token) { + case "package": + if (!head) + throw illegal(token); + parsePackage(); + break; + case "import": + if (!head) + throw illegal(token); + parseImport(); + break; + case "syntax": + if (!head) + throw illegal(token); + parseSyntax(); + break; + case "edition": + if (!head) + throw illegal(token); + parseEdition(); + break; + case "option": + parseOption(ptr, token); + skip(";", true); + break; + default: + if (parseCommon(ptr, token)) { + head = false; + continue; + } + throw illegal(token); + } + } + resolveFileFeatures(); + parse3.filename = null; + return { + "package": pkg, + "imports": imports, + weakImports, + root + }; + } + } +}); + +// node_modules/protobufjs/src/common.js +var require_common2 = __commonJS({ + "node_modules/protobufjs/src/common.js"(exports2, module2) { + "use strict"; + module2.exports = common; + var commonRe = /\/|\./; + function common(name, json) { + if (!commonRe.test(name)) { + name = "google/protobuf/" + name + ".proto"; + json = { nested: { google: { nested: { protobuf: { nested: json } } } } }; + } + common[name] = json; + } + common("any", { + /** + * Properties of a google.protobuf.Any message. + * @interface IAny + * @type {Object} + * @property {string} [typeUrl] + * @property {Uint8Array} [bytes] + * @memberof common + */ + Any: { + fields: { + type_url: { + type: "string", + id: 1 + }, + value: { + type: "bytes", + id: 2 + } + } + } + }); + var timeType; + common("duration", { + /** + * Properties of a google.protobuf.Duration message. + * @interface IDuration + * @type {Object} + * @property {number|Long} [seconds] + * @property {number} [nanos] + * @memberof common + */ + Duration: timeType = { + fields: { + seconds: { + type: "int64", + id: 1 + }, + nanos: { + type: "int32", + id: 2 + } + } + } + }); + common("timestamp", { + /** + * Properties of a google.protobuf.Timestamp message. + * @interface ITimestamp + * @type {Object} + * @property {number|Long} [seconds] + * @property {number} [nanos] + * @memberof common + */ + Timestamp: timeType + }); + common("empty", { + /** + * Properties of a google.protobuf.Empty message. + * @interface IEmpty + * @memberof common + */ + Empty: { + fields: {} + } + }); + common("struct", { + /** + * Properties of a google.protobuf.Struct message. + * @interface IStruct + * @type {Object} + * @property {Object.} [fields] + * @memberof common + */ + Struct: { + fields: { + fields: { + keyType: "string", + type: "Value", + id: 1 + } + } + }, + /** + * Properties of a google.protobuf.Value message. + * @interface IValue + * @type {Object} + * @property {string} [kind] + * @property {0} [nullValue] + * @property {number} [numberValue] + * @property {string} [stringValue] + * @property {boolean} [boolValue] + * @property {IStruct} [structValue] + * @property {IListValue} [listValue] + * @memberof common + */ + Value: { + oneofs: { + kind: { + oneof: [ + "nullValue", + "numberValue", + "stringValue", + "boolValue", + "structValue", + "listValue" + ] + } + }, + fields: { + nullValue: { + type: "NullValue", + id: 1 + }, + numberValue: { + type: "double", + id: 2 + }, + stringValue: { + type: "string", + id: 3 + }, + boolValue: { + type: "bool", + id: 4 + }, + structValue: { + type: "Struct", + id: 5 + }, + listValue: { + type: "ListValue", + id: 6 + } + } + }, + NullValue: { + values: { + NULL_VALUE: 0 + } + }, + /** + * Properties of a google.protobuf.ListValue message. + * @interface IListValue + * @type {Object} + * @property {Array.} [values] + * @memberof common + */ + ListValue: { + fields: { + values: { + rule: "repeated", + type: "Value", + id: 1 + } + } + } + }); + common("wrappers", { + /** + * Properties of a google.protobuf.DoubleValue message. + * @interface IDoubleValue + * @type {Object} + * @property {number} [value] + * @memberof common + */ + DoubleValue: { + fields: { + value: { + type: "double", + id: 1 + } + } + }, + /** + * Properties of a google.protobuf.FloatValue message. + * @interface IFloatValue + * @type {Object} + * @property {number} [value] + * @memberof common + */ + FloatValue: { + fields: { + value: { + type: "float", + id: 1 + } + } + }, + /** + * Properties of a google.protobuf.Int64Value message. + * @interface IInt64Value + * @type {Object} + * @property {number|Long} [value] + * @memberof common + */ + Int64Value: { + fields: { + value: { + type: "int64", + id: 1 + } + } + }, + /** + * Properties of a google.protobuf.UInt64Value message. + * @interface IUInt64Value + * @type {Object} + * @property {number|Long} [value] + * @memberof common + */ + UInt64Value: { + fields: { + value: { + type: "uint64", + id: 1 + } + } + }, + /** + * Properties of a google.protobuf.Int32Value message. + * @interface IInt32Value + * @type {Object} + * @property {number} [value] + * @memberof common + */ + Int32Value: { + fields: { + value: { + type: "int32", + id: 1 + } + } + }, + /** + * Properties of a google.protobuf.UInt32Value message. + * @interface IUInt32Value + * @type {Object} + * @property {number} [value] + * @memberof common + */ + UInt32Value: { + fields: { + value: { + type: "uint32", + id: 1 + } + } + }, + /** + * Properties of a google.protobuf.BoolValue message. + * @interface IBoolValue + * @type {Object} + * @property {boolean} [value] + * @memberof common + */ + BoolValue: { + fields: { + value: { + type: "bool", + id: 1 + } + } + }, + /** + * Properties of a google.protobuf.StringValue message. + * @interface IStringValue + * @type {Object} + * @property {string} [value] + * @memberof common + */ + StringValue: { + fields: { + value: { + type: "string", + id: 1 + } + } + }, + /** + * Properties of a google.protobuf.BytesValue message. + * @interface IBytesValue + * @type {Object} + * @property {Uint8Array} [value] + * @memberof common + */ + BytesValue: { + fields: { + value: { + type: "bytes", + id: 1 + } + } + } + }); + common("field_mask", { + /** + * Properties of a google.protobuf.FieldMask message. + * @interface IDoubleValue + * @type {Object} + * @property {number} [value] + * @memberof common + */ + FieldMask: { + fields: { + paths: { + rule: "repeated", + type: "string", + id: 1 + } + } + } + }); + common.get = function get(file) { + return common[file] || null; + }; + } +}); + +// node_modules/protobufjs/src/index.js +var require_src2 = __commonJS({ + "node_modules/protobufjs/src/index.js"(exports2, module2) { + "use strict"; + var protobuf = module2.exports = require_index_light(); + protobuf.build = "full"; + protobuf.tokenize = require_tokenize(); + protobuf.parse = require_parse2(); + protobuf.common = require_common2(); + protobuf.Root._configure(protobuf.Type, protobuf.parse, protobuf.common); + } +}); + +// node_modules/protobufjs/index.js +var require_protobufjs = __commonJS({ + "node_modules/protobufjs/index.js"(exports2, module2) { + "use strict"; + module2.exports = require_src2(); + } +}); + +// node_modules/protobufjs/google/protobuf/descriptor.json +var require_descriptor = __commonJS({ + "node_modules/protobufjs/google/protobuf/descriptor.json"(exports2, module2) { + module2.exports = { + nested: { + google: { + nested: { + protobuf: { + options: { + go_package: "google.golang.org/protobuf/types/descriptorpb", + java_package: "com.google.protobuf", + java_outer_classname: "DescriptorProtos", + csharp_namespace: "Google.Protobuf.Reflection", + objc_class_prefix: "GPB", + cc_enable_arenas: true, + optimize_for: "SPEED" + }, + nested: { + FileDescriptorSet: { + edition: "proto2", + fields: { + file: { + rule: "repeated", + type: "FileDescriptorProto", + id: 1 + } + }, + extensions: [ + [ + 536e6, + 536e6 + ] + ] + }, + Edition: { + edition: "proto2", + values: { + EDITION_UNKNOWN: 0, + EDITION_LEGACY: 900, + EDITION_PROTO2: 998, + EDITION_PROTO3: 999, + EDITION_2023: 1e3, + EDITION_2024: 1001, + EDITION_1_TEST_ONLY: 1, + EDITION_2_TEST_ONLY: 2, + EDITION_99997_TEST_ONLY: 99997, + EDITION_99998_TEST_ONLY: 99998, + EDITION_99999_TEST_ONLY: 99999, + EDITION_MAX: 2147483647 + } + }, + FileDescriptorProto: { + edition: "proto2", + fields: { + name: { + type: "string", + id: 1 + }, + package: { + type: "string", + id: 2 + }, + dependency: { + rule: "repeated", + type: "string", + id: 3 + }, + publicDependency: { + rule: "repeated", + type: "int32", + id: 10 + }, + weakDependency: { + rule: "repeated", + type: "int32", + id: 11 + }, + optionDependency: { + rule: "repeated", + type: "string", + id: 15 + }, + messageType: { + rule: "repeated", + type: "DescriptorProto", + id: 4 + }, + enumType: { + rule: "repeated", + type: "EnumDescriptorProto", + id: 5 + }, + service: { + rule: "repeated", + type: "ServiceDescriptorProto", + id: 6 + }, + extension: { + rule: "repeated", + type: "FieldDescriptorProto", + id: 7 + }, + options: { + type: "FileOptions", + id: 8 + }, + sourceCodeInfo: { + type: "SourceCodeInfo", + id: 9 + }, + syntax: { + type: "string", + id: 12 + }, + edition: { + type: "Edition", + id: 14 + } + } + }, + DescriptorProto: { + edition: "proto2", + fields: { + name: { + type: "string", + id: 1 + }, + field: { + rule: "repeated", + type: "FieldDescriptorProto", + id: 2 + }, + extension: { + rule: "repeated", + type: "FieldDescriptorProto", + id: 6 + }, + nestedType: { + rule: "repeated", + type: "DescriptorProto", + id: 3 + }, + enumType: { + rule: "repeated", + type: "EnumDescriptorProto", + id: 4 + }, + extensionRange: { + rule: "repeated", + type: "ExtensionRange", + id: 5 + }, + oneofDecl: { + rule: "repeated", + type: "OneofDescriptorProto", + id: 8 + }, + options: { + type: "MessageOptions", + id: 7 + }, + reservedRange: { + rule: "repeated", + type: "ReservedRange", + id: 9 + }, + reservedName: { + rule: "repeated", + type: "string", + id: 10 + }, + visibility: { + type: "SymbolVisibility", + id: 11 + } + }, + nested: { + ExtensionRange: { + fields: { + start: { + type: "int32", + id: 1 + }, + end: { + type: "int32", + id: 2 + }, + options: { + type: "ExtensionRangeOptions", + id: 3 + } + } + }, + ReservedRange: { + fields: { + start: { + type: "int32", + id: 1 + }, + end: { + type: "int32", + id: 2 + } + } + } + } + }, + ExtensionRangeOptions: { + edition: "proto2", + fields: { + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + }, + declaration: { + rule: "repeated", + type: "Declaration", + id: 2, + options: { + retention: "RETENTION_SOURCE" + } + }, + features: { + type: "FeatureSet", + id: 50 + }, + verification: { + type: "VerificationState", + id: 3, + options: { + default: "UNVERIFIED", + retention: "RETENTION_SOURCE" + } + } + }, + extensions: [ + [ + 1e3, + 536870911 + ] + ], + nested: { + Declaration: { + fields: { + number: { + type: "int32", + id: 1 + }, + fullName: { + type: "string", + id: 2 + }, + type: { + type: "string", + id: 3 + }, + reserved: { + type: "bool", + id: 5 + }, + repeated: { + type: "bool", + id: 6 + } + }, + reserved: [ + [ + 4, + 4 + ] + ] + }, + VerificationState: { + values: { + DECLARATION: 0, + UNVERIFIED: 1 + } + } + } + }, + FieldDescriptorProto: { + edition: "proto2", + fields: { + name: { + type: "string", + id: 1 + }, + number: { + type: "int32", + id: 3 + }, + label: { + type: "Label", + id: 4 + }, + type: { + type: "Type", + id: 5 + }, + typeName: { + type: "string", + id: 6 + }, + extendee: { + type: "string", + id: 2 + }, + defaultValue: { + type: "string", + id: 7 + }, + oneofIndex: { + type: "int32", + id: 9 + }, + jsonName: { + type: "string", + id: 10 + }, + options: { + type: "FieldOptions", + id: 8 + }, + proto3Optional: { + type: "bool", + id: 17 + } + }, + nested: { + Type: { + values: { + TYPE_DOUBLE: 1, + TYPE_FLOAT: 2, + TYPE_INT64: 3, + TYPE_UINT64: 4, + TYPE_INT32: 5, + TYPE_FIXED64: 6, + TYPE_FIXED32: 7, + TYPE_BOOL: 8, + TYPE_STRING: 9, + TYPE_GROUP: 10, + TYPE_MESSAGE: 11, + TYPE_BYTES: 12, + TYPE_UINT32: 13, + TYPE_ENUM: 14, + TYPE_SFIXED32: 15, + TYPE_SFIXED64: 16, + TYPE_SINT32: 17, + TYPE_SINT64: 18 + } + }, + Label: { + values: { + LABEL_OPTIONAL: 1, + LABEL_REPEATED: 3, + LABEL_REQUIRED: 2 + } + } + } + }, + OneofDescriptorProto: { + edition: "proto2", + fields: { + name: { + type: "string", + id: 1 + }, + options: { + type: "OneofOptions", + id: 2 + } + } + }, + EnumDescriptorProto: { + edition: "proto2", + fields: { + name: { + type: "string", + id: 1 + }, + value: { + rule: "repeated", + type: "EnumValueDescriptorProto", + id: 2 + }, + options: { + type: "EnumOptions", + id: 3 + }, + reservedRange: { + rule: "repeated", + type: "EnumReservedRange", + id: 4 + }, + reservedName: { + rule: "repeated", + type: "string", + id: 5 + }, + visibility: { + type: "SymbolVisibility", + id: 6 + } + }, + nested: { + EnumReservedRange: { + fields: { + start: { + type: "int32", + id: 1 + }, + end: { + type: "int32", + id: 2 + } + } + } + } + }, + EnumValueDescriptorProto: { + edition: "proto2", + fields: { + name: { + type: "string", + id: 1 + }, + number: { + type: "int32", + id: 2 + }, + options: { + type: "EnumValueOptions", + id: 3 + } + } + }, + ServiceDescriptorProto: { + edition: "proto2", + fields: { + name: { + type: "string", + id: 1 + }, + method: { + rule: "repeated", + type: "MethodDescriptorProto", + id: 2 + }, + options: { + type: "ServiceOptions", + id: 3 + } + } + }, + MethodDescriptorProto: { + edition: "proto2", + fields: { + name: { + type: "string", + id: 1 + }, + inputType: { + type: "string", + id: 2 + }, + outputType: { + type: "string", + id: 3 + }, + options: { + type: "MethodOptions", + id: 4 + }, + clientStreaming: { + type: "bool", + id: 5 + }, + serverStreaming: { + type: "bool", + id: 6 + } + } + }, + FileOptions: { + edition: "proto2", + fields: { + javaPackage: { + type: "string", + id: 1 + }, + javaOuterClassname: { + type: "string", + id: 8 + }, + javaMultipleFiles: { + type: "bool", + id: 10 + }, + javaGenerateEqualsAndHash: { + type: "bool", + id: 20, + options: { + deprecated: true + } + }, + javaStringCheckUtf8: { + type: "bool", + id: 27 + }, + optimizeFor: { + type: "OptimizeMode", + id: 9, + options: { + default: "SPEED" + } + }, + goPackage: { + type: "string", + id: 11 + }, + ccGenericServices: { + type: "bool", + id: 16 + }, + javaGenericServices: { + type: "bool", + id: 17 + }, + pyGenericServices: { + type: "bool", + id: 18 + }, + deprecated: { + type: "bool", + id: 23 + }, + ccEnableArenas: { + type: "bool", + id: 31, + options: { + default: true + } + }, + objcClassPrefix: { + type: "string", + id: 36 + }, + csharpNamespace: { + type: "string", + id: 37 + }, + swiftPrefix: { + type: "string", + id: 39 + }, + phpClassPrefix: { + type: "string", + id: 40 + }, + phpNamespace: { + type: "string", + id: 41 + }, + phpMetadataNamespace: { + type: "string", + id: 44 + }, + rubyPackage: { + type: "string", + id: 45 + }, + features: { + type: "FeatureSet", + id: 50 + }, + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1e3, + 536870911 + ] + ], + reserved: [ + [ + 42, + 42 + ], + [ + 38, + 38 + ], + "php_generic_services" + ], + nested: { + OptimizeMode: { + values: { + SPEED: 1, + CODE_SIZE: 2, + LITE_RUNTIME: 3 + } + } + } + }, + MessageOptions: { + edition: "proto2", + fields: { + messageSetWireFormat: { + type: "bool", + id: 1 + }, + noStandardDescriptorAccessor: { + type: "bool", + id: 2 + }, + deprecated: { + type: "bool", + id: 3 + }, + mapEntry: { + type: "bool", + id: 7 + }, + deprecatedLegacyJsonFieldConflicts: { + type: "bool", + id: 11, + options: { + deprecated: true + } + }, + features: { + type: "FeatureSet", + id: 12 + }, + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1e3, + 536870911 + ] + ], + reserved: [ + [ + 4, + 4 + ], + [ + 5, + 5 + ], + [ + 6, + 6 + ], + [ + 8, + 8 + ], + [ + 9, + 9 + ] + ] + }, + FieldOptions: { + edition: "proto2", + fields: { + ctype: { + type: "CType", + id: 1, + options: { + default: "STRING" + } + }, + packed: { + type: "bool", + id: 2 + }, + jstype: { + type: "JSType", + id: 6, + options: { + default: "JS_NORMAL" + } + }, + lazy: { + type: "bool", + id: 5 + }, + unverifiedLazy: { + type: "bool", + id: 15 + }, + deprecated: { + type: "bool", + id: 3 + }, + weak: { + type: "bool", + id: 10, + options: { + deprecated: true + } + }, + debugRedact: { + type: "bool", + id: 16 + }, + retention: { + type: "OptionRetention", + id: 17 + }, + targets: { + rule: "repeated", + type: "OptionTargetType", + id: 19 + }, + editionDefaults: { + rule: "repeated", + type: "EditionDefault", + id: 20 + }, + features: { + type: "FeatureSet", + id: 21 + }, + featureSupport: { + type: "FeatureSupport", + id: 22 + }, + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1e3, + 536870911 + ] + ], + reserved: [ + [ + 4, + 4 + ], + [ + 18, + 18 + ] + ], + nested: { + CType: { + values: { + STRING: 0, + CORD: 1, + STRING_PIECE: 2 + } + }, + JSType: { + values: { + JS_NORMAL: 0, + JS_STRING: 1, + JS_NUMBER: 2 + } + }, + OptionRetention: { + values: { + RETENTION_UNKNOWN: 0, + RETENTION_RUNTIME: 1, + RETENTION_SOURCE: 2 + } + }, + OptionTargetType: { + values: { + TARGET_TYPE_UNKNOWN: 0, + TARGET_TYPE_FILE: 1, + TARGET_TYPE_EXTENSION_RANGE: 2, + TARGET_TYPE_MESSAGE: 3, + TARGET_TYPE_FIELD: 4, + TARGET_TYPE_ONEOF: 5, + TARGET_TYPE_ENUM: 6, + TARGET_TYPE_ENUM_ENTRY: 7, + TARGET_TYPE_SERVICE: 8, + TARGET_TYPE_METHOD: 9 + } + }, + EditionDefault: { + fields: { + edition: { + type: "Edition", + id: 3 + }, + value: { + type: "string", + id: 2 + } + } + }, + FeatureSupport: { + fields: { + editionIntroduced: { + type: "Edition", + id: 1 + }, + editionDeprecated: { + type: "Edition", + id: 2 + }, + deprecationWarning: { + type: "string", + id: 3 + }, + editionRemoved: { + type: "Edition", + id: 4 + } + } + } + } + }, + OneofOptions: { + edition: "proto2", + fields: { + features: { + type: "FeatureSet", + id: 1 + }, + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1e3, + 536870911 + ] + ] + }, + EnumOptions: { + edition: "proto2", + fields: { + allowAlias: { + type: "bool", + id: 2 + }, + deprecated: { + type: "bool", + id: 3 + }, + deprecatedLegacyJsonFieldConflicts: { + type: "bool", + id: 6, + options: { + deprecated: true + } + }, + features: { + type: "FeatureSet", + id: 7 + }, + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1e3, + 536870911 + ] + ], + reserved: [ + [ + 5, + 5 + ] + ] + }, + EnumValueOptions: { + edition: "proto2", + fields: { + deprecated: { + type: "bool", + id: 1 + }, + features: { + type: "FeatureSet", + id: 2 + }, + debugRedact: { + type: "bool", + id: 3 + }, + featureSupport: { + type: "FieldOptions.FeatureSupport", + id: 4 + }, + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1e3, + 536870911 + ] + ] + }, + ServiceOptions: { + edition: "proto2", + fields: { + features: { + type: "FeatureSet", + id: 34 + }, + deprecated: { + type: "bool", + id: 33 + }, + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1e3, + 536870911 + ] + ] + }, + MethodOptions: { + edition: "proto2", + fields: { + deprecated: { + type: "bool", + id: 33 + }, + idempotencyLevel: { + type: "IdempotencyLevel", + id: 34, + options: { + default: "IDEMPOTENCY_UNKNOWN" + } + }, + features: { + type: "FeatureSet", + id: 35 + }, + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1e3, + 536870911 + ] + ], + nested: { + IdempotencyLevel: { + values: { + IDEMPOTENCY_UNKNOWN: 0, + NO_SIDE_EFFECTS: 1, + IDEMPOTENT: 2 + } + } + } + }, + UninterpretedOption: { + edition: "proto2", + fields: { + name: { + rule: "repeated", + type: "NamePart", + id: 2 + }, + identifierValue: { + type: "string", + id: 3 + }, + positiveIntValue: { + type: "uint64", + id: 4 + }, + negativeIntValue: { + type: "int64", + id: 5 + }, + doubleValue: { + type: "double", + id: 6 + }, + stringValue: { + type: "bytes", + id: 7 + }, + aggregateValue: { + type: "string", + id: 8 + } + }, + nested: { + NamePart: { + fields: { + namePart: { + rule: "required", + type: "string", + id: 1 + }, + isExtension: { + rule: "required", + type: "bool", + id: 2 + } + } + } + } + }, + FeatureSet: { + edition: "proto2", + fields: { + fieldPresence: { + type: "FieldPresence", + id: 1, + options: { + retention: "RETENTION_RUNTIME", + targets: "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", + "edition_defaults.edition": "EDITION_2023", + "edition_defaults.value": "EXPLICIT" + } + }, + enumType: { + type: "EnumType", + id: 2, + options: { + retention: "RETENTION_RUNTIME", + targets: "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "OPEN" + } + }, + repeatedFieldEncoding: { + type: "RepeatedFieldEncoding", + id: 3, + options: { + retention: "RETENTION_RUNTIME", + targets: "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "PACKED" + } + }, + utf8Validation: { + type: "Utf8Validation", + id: 4, + options: { + retention: "RETENTION_RUNTIME", + targets: "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "VERIFY" + } + }, + messageEncoding: { + type: "MessageEncoding", + id: 5, + options: { + retention: "RETENTION_RUNTIME", + targets: "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", + "edition_defaults.edition": "EDITION_LEGACY", + "edition_defaults.value": "LENGTH_PREFIXED" + } + }, + jsonFormat: { + type: "JsonFormat", + id: 6, + options: { + retention: "RETENTION_RUNTIME", + targets: "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "ALLOW" + } + }, + enforceNamingStyle: { + type: "EnforceNamingStyle", + id: 7, + options: { + retention: "RETENTION_SOURCE", + targets: "TARGET_TYPE_METHOD", + "feature_support.edition_introduced": "EDITION_2024", + "edition_defaults.edition": "EDITION_2024", + "edition_defaults.value": "STYLE2024" + } + }, + defaultSymbolVisibility: { + type: "VisibilityFeature.DefaultSymbolVisibility", + id: 8, + options: { + retention: "RETENTION_SOURCE", + targets: "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2024", + "edition_defaults.edition": "EDITION_2024", + "edition_defaults.value": "EXPORT_TOP_LEVEL" + } + } + }, + extensions: [ + [ + 1e3, + 9994 + ], + [ + 9995, + 9999 + ], + [ + 1e4, + 1e4 + ] + ], + reserved: [ + [ + 999, + 999 + ] + ], + nested: { + FieldPresence: { + values: { + FIELD_PRESENCE_UNKNOWN: 0, + EXPLICIT: 1, + IMPLICIT: 2, + LEGACY_REQUIRED: 3 + } + }, + EnumType: { + values: { + ENUM_TYPE_UNKNOWN: 0, + OPEN: 1, + CLOSED: 2 + } + }, + RepeatedFieldEncoding: { + values: { + REPEATED_FIELD_ENCODING_UNKNOWN: 0, + PACKED: 1, + EXPANDED: 2 + } + }, + Utf8Validation: { + values: { + UTF8_VALIDATION_UNKNOWN: 0, + VERIFY: 2, + NONE: 3 + } + }, + MessageEncoding: { + values: { + MESSAGE_ENCODING_UNKNOWN: 0, + LENGTH_PREFIXED: 1, + DELIMITED: 2 + } + }, + JsonFormat: { + values: { + JSON_FORMAT_UNKNOWN: 0, + ALLOW: 1, + LEGACY_BEST_EFFORT: 2 + } + }, + EnforceNamingStyle: { + values: { + ENFORCE_NAMING_STYLE_UNKNOWN: 0, + STYLE2024: 1, + STYLE_LEGACY: 2 + } + }, + VisibilityFeature: { + fields: {}, + reserved: [ + [ + 1, + 536870911 + ] + ], + nested: { + DefaultSymbolVisibility: { + values: { + DEFAULT_SYMBOL_VISIBILITY_UNKNOWN: 0, + EXPORT_ALL: 1, + EXPORT_TOP_LEVEL: 2, + LOCAL_ALL: 3, + STRICT: 4 + } + } + } + } + } + }, + FeatureSetDefaults: { + edition: "proto2", + fields: { + defaults: { + rule: "repeated", + type: "FeatureSetEditionDefault", + id: 1 + }, + minimumEdition: { + type: "Edition", + id: 4 + }, + maximumEdition: { + type: "Edition", + id: 5 + } + }, + nested: { + FeatureSetEditionDefault: { + fields: { + edition: { + type: "Edition", + id: 3 + }, + overridableFeatures: { + type: "FeatureSet", + id: 4 + }, + fixedFeatures: { + type: "FeatureSet", + id: 5 + } + }, + reserved: [ + [ + 1, + 1 + ], + [ + 2, + 2 + ], + "features" + ] + } + } + }, + SourceCodeInfo: { + edition: "proto2", + fields: { + location: { + rule: "repeated", + type: "Location", + id: 1 + } + }, + extensions: [ + [ + 536e6, + 536e6 + ] + ], + nested: { + Location: { + fields: { + path: { + rule: "repeated", + type: "int32", + id: 1, + options: { + packed: true + } + }, + span: { + rule: "repeated", + type: "int32", + id: 2, + options: { + packed: true + } + }, + leadingComments: { + type: "string", + id: 3 + }, + trailingComments: { + type: "string", + id: 4 + }, + leadingDetachedComments: { + rule: "repeated", + type: "string", + id: 6 + } + } + } + } + }, + GeneratedCodeInfo: { + edition: "proto2", + fields: { + annotation: { + rule: "repeated", + type: "Annotation", + id: 1 + } + }, + nested: { + Annotation: { + fields: { + path: { + rule: "repeated", + type: "int32", + id: 1, + options: { + packed: true + } + }, + sourceFile: { + type: "string", + id: 2 + }, + begin: { + type: "int32", + id: 3 + }, + end: { + type: "int32", + id: 4 + }, + semantic: { + type: "Semantic", + id: 5 + } + }, + nested: { + Semantic: { + values: { + NONE: 0, + SET: 1, + ALIAS: 2 + } + } + } + } + } + }, + SymbolVisibility: { + edition: "proto2", + values: { + VISIBILITY_UNSET: 0, + VISIBILITY_LOCAL: 1, + VISIBILITY_EXPORT: 2 + } + } + } + } + } + } + } + }; + } +}); + +// node_modules/protobufjs/ext/descriptor/index.js +var require_descriptor2 = __commonJS({ + "node_modules/protobufjs/ext/descriptor/index.js"(exports2, module2) { + "use strict"; + var $protobuf = require_protobufjs(); + module2.exports = exports2 = $protobuf.descriptor = $protobuf.Root.fromJSON(require_descriptor()).lookup(".google.protobuf"); + var Namespace = $protobuf.Namespace; + var Root = $protobuf.Root; + var Enum = $protobuf.Enum; + var Type = $protobuf.Type; + var Field = $protobuf.Field; + var MapField = $protobuf.MapField; + var OneOf = $protobuf.OneOf; + var Service = $protobuf.Service; + var Method = $protobuf.Method; + var patterns = $protobuf.util.patterns; + var numberRe = patterns.numberRe; + var typeRefRe = patterns.typeRefRe; + Root.fromDescriptor = function fromDescriptor(descriptor) { + if (typeof descriptor.length === "number") + descriptor = exports2.FileDescriptorSet.decode(descriptor); + var root = new Root(); + if (descriptor.file) { + var fileDescriptor, filePackage; + for (var j = 0, i; j < descriptor.file.length; ++j) { + filePackage = root; + if ((fileDescriptor = descriptor.file[j])["package"] && fileDescriptor["package"].length) + filePackage = root.define(fileDescriptor["package"]); + var edition = editionFromDescriptor(fileDescriptor); + if (fileDescriptor.name && fileDescriptor.name.length) + root.files.push(filePackage.filename = fileDescriptor.name); + if (fileDescriptor.messageType) + for (i = 0; i < fileDescriptor.messageType.length; ++i) + filePackage.add(Type.fromDescriptor(fileDescriptor.messageType[i], edition)); + if (fileDescriptor.enumType) + for (i = 0; i < fileDescriptor.enumType.length; ++i) + filePackage.add(Enum.fromDescriptor(fileDescriptor.enumType[i], edition)); + if (fileDescriptor.extension) + for (i = 0; i < fileDescriptor.extension.length; ++i) + filePackage.add(Field.fromDescriptor(fileDescriptor.extension[i], edition)); + if (fileDescriptor.service) + for (i = 0; i < fileDescriptor.service.length; ++i) + filePackage.add(Service.fromDescriptor(fileDescriptor.service[i], edition)); + var opts = fromDescriptorOptions(fileDescriptor.options, exports2.FileOptions); + if (opts) { + var ks = Object.keys(opts); + for (i = 0; i < ks.length; ++i) + filePackage.setOption(ks[i], opts[ks[i]]); + } + } + } + return root.resolveAll(); + }; + Root.prototype.toDescriptor = function toDescriptor(edition) { + var set = exports2.FileDescriptorSet.create(); + Root_toDescriptorRecursive(this, set.file, edition); + return set; + }; + function Root_toDescriptorRecursive(ns, files, edition) { + var file = exports2.FileDescriptorProto.create({ name: ns.filename || (ns.fullName.substring(1).replace(/\./g, "_") || "root") + ".proto" }); + editionToDescriptor(edition, file); + if (!(ns instanceof Root)) + file["package"] = ns.fullName.substring(1); + for (var i = 0, nested; i < ns.nestedArray.length; ++i) + if ((nested = ns._nestedArray[i]) instanceof Type) + file.messageType.push(nested.toDescriptor(edition)); + else if (nested instanceof Enum) + file.enumType.push(nested.toDescriptor()); + else if (nested instanceof Field) + file.extension.push(nested.toDescriptor(edition)); + else if (nested instanceof Service) + file.service.push(nested.toDescriptor()); + else if (nested instanceof /* plain */ + Namespace) + Root_toDescriptorRecursive(nested, files, edition); + file.options = toDescriptorOptions(ns.options, exports2.FileOptions); + if (file.messageType.length + file.enumType.length + file.extension.length + file.service.length) + files.push(file); + } + var unnamedMessageIndex = 0; + Type.fromDescriptor = function fromDescriptor(descriptor, edition, nested) { + if (typeof descriptor.length === "number") + descriptor = exports2.DescriptorProto.decode(descriptor); + var type = new Type(descriptor.name.length ? descriptor.name : "Type" + unnamedMessageIndex++, fromDescriptorOptions(descriptor.options, exports2.MessageOptions)), i; + if (!nested) + type._edition = edition; + if (descriptor.oneofDecl) + for (i = 0; i < descriptor.oneofDecl.length; ++i) + type.add(OneOf.fromDescriptor(descriptor.oneofDecl[i])); + if (descriptor.field) + for (i = 0; i < descriptor.field.length; ++i) { + var field = Field.fromDescriptor(descriptor.field[i], edition, true); + type.add(field); + if (descriptor.field[i].hasOwnProperty("oneofIndex")) + type.oneofsArray[descriptor.field[i].oneofIndex].add(field); + } + if (descriptor.extension) + for (i = 0; i < descriptor.extension.length; ++i) + type.add(Field.fromDescriptor(descriptor.extension[i], edition, true)); + if (descriptor.nestedType) + for (i = 0; i < descriptor.nestedType.length; ++i) { + type.add(Type.fromDescriptor(descriptor.nestedType[i], edition, true)); + if (descriptor.nestedType[i].options && descriptor.nestedType[i].options.mapEntry) + type.setOption("map_entry", true); + } + if (descriptor.enumType) + for (i = 0; i < descriptor.enumType.length; ++i) + type.add(Enum.fromDescriptor(descriptor.enumType[i], edition, true)); + if (descriptor.extensionRange && descriptor.extensionRange.length) { + type.extensions = []; + for (i = 0; i < descriptor.extensionRange.length; ++i) + type.extensions.push([descriptor.extensionRange[i].start, descriptor.extensionRange[i].end]); + } + if (descriptor.reservedRange && descriptor.reservedRange.length || descriptor.reservedName && descriptor.reservedName.length) { + type.reserved = []; + if (descriptor.reservedRange) + for (i = 0; i < descriptor.reservedRange.length; ++i) + type.reserved.push([descriptor.reservedRange[i].start, descriptor.reservedRange[i].end]); + if (descriptor.reservedName) + for (i = 0; i < descriptor.reservedName.length; ++i) + type.reserved.push(descriptor.reservedName[i]); + } + return type; + }; + Type.prototype.toDescriptor = function toDescriptor(edition) { + var descriptor = exports2.DescriptorProto.create({ name: this.name }), i; + for (i = 0; i < this.fieldsArray.length; ++i) { + var fieldDescriptor; + descriptor.field.push(fieldDescriptor = this._fieldsArray[i].toDescriptor(edition)); + if (this._fieldsArray[i] instanceof MapField) { + var keyType = toDescriptorType(this._fieldsArray[i].keyType, this._fieldsArray[i].resolvedKeyType, false), valueType = toDescriptorType(this._fieldsArray[i].type, this._fieldsArray[i].resolvedType, false), valueTypeName = valueType === /* type */ + 11 || valueType === /* enum */ + 14 ? this._fieldsArray[i].resolvedType && shortname(this.parent, this._fieldsArray[i].resolvedType) || this._fieldsArray[i].type : void 0; + descriptor.nestedType.push(exports2.DescriptorProto.create({ + name: fieldDescriptor.typeName, + field: [ + exports2.FieldDescriptorProto.create({ name: "key", number: 1, label: 1, type: keyType }), + // can't reference a type or enum + exports2.FieldDescriptorProto.create({ name: "value", number: 2, label: 1, type: valueType, typeName: valueTypeName }) + ], + options: exports2.MessageOptions.create({ mapEntry: true }) + })); + } + } + for (i = 0; i < this.oneofsArray.length; ++i) + descriptor.oneofDecl.push(this._oneofsArray[i].toDescriptor()); + for (i = 0; i < this.nestedArray.length; ++i) { + if (this._nestedArray[i] instanceof Field) + descriptor.field.push(this._nestedArray[i].toDescriptor(edition)); + else if (this._nestedArray[i] instanceof Type) + descriptor.nestedType.push(this._nestedArray[i].toDescriptor(edition)); + else if (this._nestedArray[i] instanceof Enum) + descriptor.enumType.push(this._nestedArray[i].toDescriptor()); + } + if (this.extensions) + for (i = 0; i < this.extensions.length; ++i) + descriptor.extensionRange.push(exports2.DescriptorProto.ExtensionRange.create({ start: this.extensions[i][0], end: this.extensions[i][1] })); + if (this.reserved) + for (i = 0; i < this.reserved.length; ++i) + if (typeof this.reserved[i] === "string") + descriptor.reservedName.push(this.reserved[i]); + else + descriptor.reservedRange.push(exports2.DescriptorProto.ReservedRange.create({ start: this.reserved[i][0], end: this.reserved[i][1] })); + descriptor.options = toDescriptorOptions(this.options, exports2.MessageOptions); + return descriptor; + }; + Field.fromDescriptor = function fromDescriptor(descriptor, edition, nested) { + if (typeof descriptor.length === "number") + descriptor = exports2.DescriptorProto.decode(descriptor); + if (typeof descriptor.number !== "number") + throw Error("missing field id"); + var typeName = descriptor.typeName, fieldType; + if (typeName != null && typeName !== "") { + if (typeof typeName !== "string" || !typeRefRe.test(typeName)) + throw Error("illegal type name: " + typeName); + fieldType = typeName; + } else + fieldType = fromDescriptorType(descriptor.type); + var fieldRule; + switch (descriptor.label) { + // 0 is reserved for errors + case 1: + fieldRule = void 0; + break; + case 2: + fieldRule = "required"; + break; + case 3: + fieldRule = "repeated"; + break; + default: + throw Error("illegal label: " + descriptor.label); + } + var extendee = descriptor.extendee; + if (extendee != null && extendee !== "") { + if (typeof extendee !== "string" || !typeRefRe.test(extendee)) + throw Error("illegal type name: " + extendee); + } else + extendee = void 0; + var field = new Field( + descriptor.name.length ? descriptor.name : "field" + descriptor.number, + descriptor.number, + fieldType, + fieldRule, + extendee + ); + if (!nested) + field._edition = edition; + field.options = fromDescriptorOptions(descriptor.options, exports2.FieldOptions); + if (descriptor.proto3_optional) + field.options.proto3_optional = true; + if (descriptor.defaultValue && descriptor.defaultValue.length) { + var defaultValue = descriptor.defaultValue; + switch (defaultValue) { + case "true": + case "TRUE": + defaultValue = true; + break; + case "false": + case "FALSE": + defaultValue = false; + break; + default: + var match = numberRe.exec(defaultValue); + if (match) + defaultValue = parseInt(defaultValue); + break; + } + field.setOption("default", defaultValue); + } + if (packableDescriptorType(descriptor.type)) { + if (edition === "proto3") { + if (descriptor.options && !descriptor.options.packed) + field.setOption("packed", false); + } else if ((!edition || edition === "proto2") && descriptor.options && descriptor.options.packed) + field.setOption("packed", true); + } + return field; + }; + Field.prototype.toDescriptor = function toDescriptor(edition) { + var descriptor = exports2.FieldDescriptorProto.create({ name: this.name, number: this.id }); + if (this.map) { + descriptor.type = 11; + descriptor.typeName = $protobuf.util.ucFirst(this.name); + descriptor.label = 3; + } else { + switch (descriptor.type = toDescriptorType(this.type, this.resolve().resolvedType, this.delimited)) { + case 10: + // group + case 11: + // type + case 14: + descriptor.typeName = this.resolvedType ? shortname(this.parent, this.resolvedType) : this.type; + break; + } + if (this.rule === "repeated") { + descriptor.label = 3; + } else if (this.required && edition === "proto2") { + descriptor.label = 2; + } else { + descriptor.label = 1; + } + } + descriptor.extendee = this.extensionField ? this.extensionField.parent.fullName : this.extend; + if (this.partOf && this.parent instanceof Type) { + if ((descriptor.oneofIndex = this.parent.oneofsArray.indexOf(this.partOf)) < 0) + throw Error("missing oneof"); + } + if (this.options) { + descriptor.options = toDescriptorOptions(this.options, exports2.FieldOptions); + if (this.options["default"] != null) + descriptor.defaultValue = String(this.options["default"]); + if (this.options.proto3_optional) + descriptor.proto3_optional = true; + } + if (edition === "proto3") { + if (!this.packed) + (descriptor.options || (descriptor.options = exports2.FieldOptions.create())).packed = false; + } else if ((!edition || edition === "proto2") && this.packed) + (descriptor.options || (descriptor.options = exports2.FieldOptions.create())).packed = true; + return descriptor; + }; + var unnamedEnumIndex = 0; + Enum.fromDescriptor = function fromDescriptor(descriptor, edition, nested) { + if (typeof descriptor.length === "number") + descriptor = exports2.EnumDescriptorProto.decode(descriptor); + var values = {}; + if (descriptor.value) + for (var i = 0; i < descriptor.value.length; ++i) { + var name = descriptor.value[i].name, value = descriptor.value[i].number || 0; + values[name && name.length ? name : "NAME" + value] = value; + } + var enm = new Enum( + descriptor.name && descriptor.name.length ? descriptor.name : "Enum" + unnamedEnumIndex++, + values, + fromDescriptorOptions(descriptor.options, exports2.EnumOptions) + ); + if (!nested) + enm._edition = edition; + return enm; + }; + Enum.prototype.toDescriptor = function toDescriptor() { + var values = []; + for (var i = 0, ks = Object.keys(this.values); i < ks.length; ++i) + values.push(exports2.EnumValueDescriptorProto.create({ name: ks[i], number: this.values[ks[i]] })); + return exports2.EnumDescriptorProto.create({ + name: this.name, + value: values, + options: toDescriptorOptions(this.options, exports2.EnumOptions) + }); + }; + var unnamedOneofIndex = 0; + OneOf.fromDescriptor = function fromDescriptor(descriptor) { + if (typeof descriptor.length === "number") + descriptor = exports2.OneofDescriptorProto.decode(descriptor); + return new OneOf( + // unnamedOneOfIndex is global, not per type, because we have no ref to a type here + descriptor.name && descriptor.name.length ? descriptor.name : "oneof" + unnamedOneofIndex++ + // fromDescriptorOptions(descriptor.options, exports.OneofOptions) - only uninterpreted_option + ); + }; + OneOf.prototype.toDescriptor = function toDescriptor() { + return exports2.OneofDescriptorProto.create({ + name: this.name + // options: toDescriptorOptions(this.options, exports.OneofOptions) - only uninterpreted_option + }); + }; + var unnamedServiceIndex = 0; + Service.fromDescriptor = function fromDescriptor(descriptor, edition, nested) { + if (typeof descriptor.length === "number") + descriptor = exports2.ServiceDescriptorProto.decode(descriptor); + var service = new Service(descriptor.name && descriptor.name.length ? descriptor.name : "Service" + unnamedServiceIndex++, fromDescriptorOptions(descriptor.options, exports2.ServiceOptions)); + if (!nested) + service._edition = edition; + if (descriptor.method) + for (var i = 0; i < descriptor.method.length; ++i) + service.add(Method.fromDescriptor(descriptor.method[i])); + return service; + }; + Service.prototype.toDescriptor = function toDescriptor() { + var methods = []; + for (var i = 0; i < this.methodsArray.length; ++i) + methods.push(this._methodsArray[i].toDescriptor()); + return exports2.ServiceDescriptorProto.create({ + name: this.name, + method: methods, + options: toDescriptorOptions(this.options, exports2.ServiceOptions) + }); + }; + var unnamedMethodIndex = 0; + Method.fromDescriptor = function fromDescriptor(descriptor) { + if (typeof descriptor.length === "number") + descriptor = exports2.MethodDescriptorProto.decode(descriptor); + var inputType = descriptor.inputType, outputType = descriptor.outputType; + if (inputType != null && inputType !== "") { + if (typeof inputType !== "string" || !typeRefRe.test(inputType)) + throw Error("illegal type name: " + inputType); + } + if (outputType != null && outputType !== "") { + if (typeof outputType !== "string" || !typeRefRe.test(outputType)) + throw Error("illegal type name: " + outputType); + } + return new Method( + // unnamedMethodIndex is global, not per service, because we have no ref to a service here + descriptor.name && descriptor.name.length ? descriptor.name : "Method" + unnamedMethodIndex++, + "rpc", + inputType, + outputType, + Boolean(descriptor.clientStreaming), + Boolean(descriptor.serverStreaming), + fromDescriptorOptions(descriptor.options, exports2.MethodOptions) + ); + }; + Method.prototype.toDescriptor = function toDescriptor() { + return exports2.MethodDescriptorProto.create({ + name: this.name, + inputType: this.resolvedRequestType ? this.resolvedRequestType.fullName : this.requestType, + outputType: this.resolvedResponseType ? this.resolvedResponseType.fullName : this.responseType, + clientStreaming: this.requestStream, + serverStreaming: this.responseStream, + options: toDescriptorOptions(this.options, exports2.MethodOptions) + }); + }; + function fromDescriptorType(type) { + switch (type) { + // 0 is reserved for errors + case 1: + return "double"; + case 2: + return "float"; + case 3: + return "int64"; + case 4: + return "uint64"; + case 5: + return "int32"; + case 6: + return "fixed64"; + case 7: + return "fixed32"; + case 8: + return "bool"; + case 9: + return "string"; + case 12: + return "bytes"; + case 13: + return "uint32"; + case 15: + return "sfixed32"; + case 16: + return "sfixed64"; + case 17: + return "sint32"; + case 18: + return "sint64"; + } + throw Error("illegal type: " + type); + } + function packableDescriptorType(type) { + switch (type) { + case 1: + // double + case 2: + // float + case 3: + // int64 + case 4: + // uint64 + case 5: + // int32 + case 6: + // fixed64 + case 7: + // fixed32 + case 8: + // bool + case 13: + // uint32 + case 14: + // enum (!) + case 15: + // sfixed32 + case 16: + // sfixed64 + case 17: + // sint32 + case 18: + return true; + } + return false; + } + function toDescriptorType(type, resolvedType, delimited) { + switch (type) { + // 0 is reserved for errors + case "double": + return 1; + case "float": + return 2; + case "int64": + return 3; + case "uint64": + return 4; + case "int32": + return 5; + case "fixed64": + return 6; + case "fixed32": + return 7; + case "bool": + return 8; + case "string": + return 9; + case "bytes": + return 12; + case "uint32": + return 13; + case "sfixed32": + return 15; + case "sfixed64": + return 16; + case "sint32": + return 17; + case "sint64": + return 18; + } + if (resolvedType instanceof Enum) + return 14; + if (resolvedType instanceof Type) + return delimited ? 10 : 11; + throw Error("illegal type: " + type); + } + function fromDescriptorOptionsRecursive(obj, type) { + var val = {}; + for (var i = 0, field, key; i < type.fieldsArray.length; ++i) { + if ((key = (field = type._fieldsArray[i]).name) === "uninterpretedOption") continue; + if (!Object.prototype.hasOwnProperty.call(obj, key)) continue; + var newKey = underScore(key); + if (field.resolvedType instanceof Type) { + val[newKey] = fromDescriptorOptionsRecursive(obj[key], field.resolvedType); + } else if (field.resolvedType instanceof Enum) { + val[newKey] = field.resolvedType.valuesById[obj[key]]; + } else { + val[newKey] = obj[key]; + } + } + return val; + } + function fromDescriptorOptions(options, type) { + if (!options) + return void 0; + return fromDescriptorOptionsRecursive(type.toObject(options), type); + } + function toDescriptorOptionsRecursive(obj, type) { + var val = {}; + var keys = Object.keys(obj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + var newKey = $protobuf.util.camelCase(key); + if (!Object.prototype.hasOwnProperty.call(type.fields, newKey)) continue; + var field = type.fields[newKey]; + if (field.resolvedType instanceof Type) { + val[newKey] = toDescriptorOptionsRecursive(obj[key], field.resolvedType); + } else { + val[newKey] = obj[key]; + } + if (field.repeated && !Array.isArray(val[newKey])) { + val[newKey] = [val[newKey]]; + } + } + return val; + } + function toDescriptorOptions(options, type) { + if (!options) + return void 0; + return type.fromObject(toDescriptorOptionsRecursive(options, type)); + } + function shortname(from, to) { + var fromPath = from.fullName.split("."), toPath = to.fullName.split("."), i = 0, j = 0, k = toPath.length - 1; + if (!(from instanceof Root) && to instanceof Namespace) + while (i < fromPath.length && j < k && fromPath[i] === toPath[j]) { + var other = to.lookup(fromPath[i++], true); + if (other !== null && other !== to) + break; + ++j; + } + else + for (; i < fromPath.length && j < k && fromPath[i] === toPath[j]; ++i, ++j) ; + return toPath.slice(j).join("."); + } + function underScore(str) { + return str.substring(0, 1) + str.substring(1).replace(/([A-Z])(?=[a-z]|$)/g, function($0, $1) { + return "_" + $1.toLowerCase(); + }); + } + function editionFromDescriptor(fileDescriptor) { + if (fileDescriptor.syntax === "editions") { + switch (fileDescriptor.edition) { + case exports2.Edition.EDITION_2023: + return "2023"; + default: + throw new Error("Unsupported edition " + fileDescriptor.edition); + } + } + if (fileDescriptor.syntax === "proto3") { + return "proto3"; + } + return "proto2"; + } + function editionToDescriptor(edition, fileDescriptor) { + if (!edition) return; + if (edition === "proto2" || edition === "proto3") { + fileDescriptor.syntax = edition; + } else { + fileDescriptor.syntax = "editions"; + switch (edition) { + case "2023": + fileDescriptor.edition = exports2.Edition.EDITION_2023; + break; + default: + throw new Error("Unsupported edition " + edition); + } + } + } + } +}); + +// node_modules/protobufjs/google/protobuf/api.json +var require_api2 = __commonJS({ + "node_modules/protobufjs/google/protobuf/api.json"(exports2, module2) { + module2.exports = { + nested: { + google: { + nested: { + protobuf: { + nested: { + Api: { + fields: { + name: { + type: "string", + id: 1 + }, + methods: { + rule: "repeated", + type: "Method", + id: 2 + }, + options: { + rule: "repeated", + type: "Option", + id: 3 + }, + version: { + type: "string", + id: 4 + }, + sourceContext: { + type: "SourceContext", + id: 5 + }, + mixins: { + rule: "repeated", + type: "Mixin", + id: 6 + }, + syntax: { + type: "Syntax", + id: 7 + } + } + }, + Method: { + fields: { + name: { + type: "string", + id: 1 + }, + requestTypeUrl: { + type: "string", + id: 2 + }, + requestStreaming: { + type: "bool", + id: 3 + }, + responseTypeUrl: { + type: "string", + id: 4 + }, + responseStreaming: { + type: "bool", + id: 5 + }, + options: { + rule: "repeated", + type: "Option", + id: 6 + }, + syntax: { + type: "Syntax", + id: 7 + } + } + }, + Mixin: { + fields: { + name: { + type: "string", + id: 1 + }, + root: { + type: "string", + id: 2 + } + } + }, + SourceContext: { + fields: { + fileName: { + type: "string", + id: 1 + } + } + }, + Option: { + fields: { + name: { + type: "string", + id: 1 + }, + value: { + type: "Any", + id: 2 + } + } + }, + Syntax: { + values: { + SYNTAX_PROTO2: 0, + SYNTAX_PROTO3: 1 + } + } + } + } + } + } + } + }; + } +}); + +// node_modules/protobufjs/google/protobuf/source_context.json +var require_source_context = __commonJS({ + "node_modules/protobufjs/google/protobuf/source_context.json"(exports2, module2) { + module2.exports = { + nested: { + google: { + nested: { + protobuf: { + nested: { + SourceContext: { + fields: { + fileName: { + type: "string", + id: 1 + } + } + } + } + } + } + } + } + }; + } +}); + +// node_modules/protobufjs/google/protobuf/type.json +var require_type2 = __commonJS({ + "node_modules/protobufjs/google/protobuf/type.json"(exports2, module2) { + module2.exports = { + nested: { + google: { + nested: { + protobuf: { + nested: { + Type: { + fields: { + name: { + type: "string", + id: 1 + }, + fields: { + rule: "repeated", + type: "Field", + id: 2 + }, + oneofs: { + rule: "repeated", + type: "string", + id: 3 + }, + options: { + rule: "repeated", + type: "Option", + id: 4 + }, + sourceContext: { + type: "SourceContext", + id: 5 + }, + syntax: { + type: "Syntax", + id: 6 + } + } + }, + Field: { + fields: { + kind: { + type: "Kind", + id: 1 + }, + cardinality: { + type: "Cardinality", + id: 2 + }, + number: { + type: "int32", + id: 3 + }, + name: { + type: "string", + id: 4 + }, + typeUrl: { + type: "string", + id: 6 + }, + oneofIndex: { + type: "int32", + id: 7 + }, + packed: { + type: "bool", + id: 8 + }, + options: { + rule: "repeated", + type: "Option", + id: 9 + }, + jsonName: { + type: "string", + id: 10 + }, + defaultValue: { + type: "string", + id: 11 + } + }, + nested: { + Kind: { + values: { + TYPE_UNKNOWN: 0, + TYPE_DOUBLE: 1, + TYPE_FLOAT: 2, + TYPE_INT64: 3, + TYPE_UINT64: 4, + TYPE_INT32: 5, + TYPE_FIXED64: 6, + TYPE_FIXED32: 7, + TYPE_BOOL: 8, + TYPE_STRING: 9, + TYPE_GROUP: 10, + TYPE_MESSAGE: 11, + TYPE_BYTES: 12, + TYPE_UINT32: 13, + TYPE_ENUM: 14, + TYPE_SFIXED32: 15, + TYPE_SFIXED64: 16, + TYPE_SINT32: 17, + TYPE_SINT64: 18 + } + }, + Cardinality: { + values: { + CARDINALITY_UNKNOWN: 0, + CARDINALITY_OPTIONAL: 1, + CARDINALITY_REQUIRED: 2, + CARDINALITY_REPEATED: 3 + } + } + } + }, + Enum: { + fields: { + name: { + type: "string", + id: 1 + }, + enumvalue: { + rule: "repeated", + type: "EnumValue", + id: 2 + }, + options: { + rule: "repeated", + type: "Option", + id: 3 + }, + sourceContext: { + type: "SourceContext", + id: 4 + }, + syntax: { + type: "Syntax", + id: 5 + } + } + }, + EnumValue: { + fields: { + name: { + type: "string", + id: 1 + }, + number: { + type: "int32", + id: 2 + }, + options: { + rule: "repeated", + type: "Option", + id: 3 + } + } + }, + Option: { + fields: { + name: { + type: "string", + id: 1 + }, + value: { + type: "Any", + id: 2 + } + } + }, + Syntax: { + values: { + SYNTAX_PROTO2: 0, + SYNTAX_PROTO3: 1 + } + }, + Any: { + fields: { + type_url: { + type: "string", + id: 1 + }, + value: { + type: "bytes", + id: 2 + } + } + }, + SourceContext: { + fields: { + fileName: { + type: "string", + id: 1 + } + } + } + } + } + } + } + } + }; + } +}); + +// node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/util.js +var require_util11 = __commonJS({ + "node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/util.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.addCommonProtos = exports2.loadProtosWithOptionsSync = exports2.loadProtosWithOptions = void 0; + var fs4 = require("fs"); + var path = require("path"); + var Protobuf = require_protobufjs(); + function addIncludePathResolver(root, includePaths) { + const originalResolvePath = root.resolvePath; + root.resolvePath = (origin, target) => { + if (path.isAbsolute(target)) { + return target; + } + for (const directory of includePaths) { + const fullPath = path.join(directory, target); + try { + fs4.accessSync(fullPath, fs4.constants.R_OK); + return fullPath; + } catch (err) { + continue; + } + } + process.emitWarning(`${target} not found in any of the include paths ${includePaths}`); + return originalResolvePath(origin, target); + }; + } + async function loadProtosWithOptions(filename, options) { + const root = new Protobuf.Root(); + options = options || {}; + if (!!options.includeDirs) { + if (!Array.isArray(options.includeDirs)) { + return Promise.reject(new Error("The includeDirs option must be an array")); + } + addIncludePathResolver(root, options.includeDirs); + } + const loadedRoot = await root.load(filename, options); + loadedRoot.resolveAll(); + return loadedRoot; + } + exports2.loadProtosWithOptions = loadProtosWithOptions; + function loadProtosWithOptionsSync(filename, options) { + const root = new Protobuf.Root(); + options = options || {}; + if (!!options.includeDirs) { + if (!Array.isArray(options.includeDirs)) { + throw new Error("The includeDirs option must be an array"); + } + addIncludePathResolver(root, options.includeDirs); + } + const loadedRoot = root.loadSync(filename, options); + loadedRoot.resolveAll(); + return loadedRoot; + } + exports2.loadProtosWithOptionsSync = loadProtosWithOptionsSync; + function addCommonProtos() { + const apiDescriptor = require_api2(); + const descriptorDescriptor = require_descriptor(); + const sourceContextDescriptor = require_source_context(); + const typeDescriptor = require_type2(); + Protobuf.common("api", apiDescriptor.nested.google.nested.protobuf.nested); + Protobuf.common("descriptor", descriptorDescriptor.nested.google.nested.protobuf.nested); + Protobuf.common("source_context", sourceContextDescriptor.nested.google.nested.protobuf.nested); + Protobuf.common("type", typeDescriptor.nested.google.nested.protobuf.nested); + } + exports2.addCommonProtos = addCommonProtos; + } +}); + +// node_modules/long/umd/index.js +var require_umd = __commonJS({ + "node_modules/long/umd/index.js"(exports2, module2) { + (function(global2, factory) { + function unwrapDefault(exports3) { + return "default" in exports3 ? exports3.default : exports3; + } + if (typeof define === "function" && define.amd) { + define([], function() { + var exports3 = {}; + factory(exports3); + return unwrapDefault(exports3); + }); + } else if (typeof exports2 === "object") { + factory(exports2); + if (typeof module2 === "object") module2.exports = unwrapDefault(exports2); + } else { + (function() { + var exports3 = {}; + factory(exports3); + global2.Long = unwrapDefault(exports3); + })(); + } + })( + typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : exports2, + function(_exports) { + "use strict"; + Object.defineProperty(_exports, "__esModule", { + value: true + }); + _exports.default = void 0; + var wasm = null; + try { + wasm = new WebAssembly.Instance( + new WebAssembly.Module( + new Uint8Array([ + // \0asm + 0, + 97, + 115, + 109, + // version 1 + 1, + 0, + 0, + 0, + // section "type" + 1, + 13, + 2, + // 0, () => i32 + 96, + 0, + 1, + 127, + // 1, (i32, i32, i32, i32) => i32 + 96, + 4, + 127, + 127, + 127, + 127, + 1, + 127, + // section "function" + 3, + 7, + 6, + // 0, type 0 + 0, + // 1, type 1 + 1, + // 2, type 1 + 1, + // 3, type 1 + 1, + // 4, type 1 + 1, + // 5, type 1 + 1, + // section "global" + 6, + 6, + 1, + // 0, "high", mutable i32 + 127, + 1, + 65, + 0, + 11, + // section "export" + 7, + 50, + 6, + // 0, "mul" + 3, + 109, + 117, + 108, + 0, + 1, + // 1, "div_s" + 5, + 100, + 105, + 118, + 95, + 115, + 0, + 2, + // 2, "div_u" + 5, + 100, + 105, + 118, + 95, + 117, + 0, + 3, + // 3, "rem_s" + 5, + 114, + 101, + 109, + 95, + 115, + 0, + 4, + // 4, "rem_u" + 5, + 114, + 101, + 109, + 95, + 117, + 0, + 5, + // 5, "get_high" + 8, + 103, + 101, + 116, + 95, + 104, + 105, + 103, + 104, + 0, + 0, + // section "code" + 10, + 191, + 1, + 6, + // 0, "get_high" + 4, + 0, + 35, + 0, + 11, + // 1, "mul" + 36, + 1, + 1, + 126, + 32, + 0, + 173, + 32, + 1, + 173, + 66, + 32, + 134, + 132, + 32, + 2, + 173, + 32, + 3, + 173, + 66, + 32, + 134, + 132, + 126, + 34, + 4, + 66, + 32, + 135, + 167, + 36, + 0, + 32, + 4, + 167, + 11, + // 2, "div_s" + 36, + 1, + 1, + 126, + 32, + 0, + 173, + 32, + 1, + 173, + 66, + 32, + 134, + 132, + 32, + 2, + 173, + 32, + 3, + 173, + 66, + 32, + 134, + 132, + 127, + 34, + 4, + 66, + 32, + 135, + 167, + 36, + 0, + 32, + 4, + 167, + 11, + // 3, "div_u" + 36, + 1, + 1, + 126, + 32, + 0, + 173, + 32, + 1, + 173, + 66, + 32, + 134, + 132, + 32, + 2, + 173, + 32, + 3, + 173, + 66, + 32, + 134, + 132, + 128, + 34, + 4, + 66, + 32, + 135, + 167, + 36, + 0, + 32, + 4, + 167, + 11, + // 4, "rem_s" + 36, + 1, + 1, + 126, + 32, + 0, + 173, + 32, + 1, + 173, + 66, + 32, + 134, + 132, + 32, + 2, + 173, + 32, + 3, + 173, + 66, + 32, + 134, + 132, + 129, + 34, + 4, + 66, + 32, + 135, + 167, + 36, + 0, + 32, + 4, + 167, + 11, + // 5, "rem_u" + 36, + 1, + 1, + 126, + 32, + 0, + 173, + 32, + 1, + 173, + 66, + 32, + 134, + 132, + 32, + 2, + 173, + 32, + 3, + 173, + 66, + 32, + 134, + 132, + 130, + 34, + 4, + 66, + 32, + 135, + 167, + 36, + 0, + 32, + 4, + 167, + 11 + ]) + ), + {} + ).exports; + } catch { + } + function Long(low, high, unsigned) { + this.low = low | 0; + this.high = high | 0; + this.unsigned = !!unsigned; + } + Long.prototype.__isLong__; + Object.defineProperty(Long.prototype, "__isLong__", { + value: true + }); + function isLong(obj) { + return (obj && obj["__isLong__"]) === true; + } + function ctz32(value) { + var c = Math.clz32(value & -value); + return value ? 31 - c : c; + } + Long.isLong = isLong; + var INT_CACHE = {}; + var UINT_CACHE = {}; + function fromInt(value, unsigned) { + var obj, cachedObj, cache; + if (unsigned) { + value >>>= 0; + if (cache = 0 <= value && value < 256) { + cachedObj = UINT_CACHE[value]; + if (cachedObj) return cachedObj; + } + obj = fromBits(value, 0, true); + if (cache) UINT_CACHE[value] = obj; + return obj; + } else { + value |= 0; + if (cache = -128 <= value && value < 128) { + cachedObj = INT_CACHE[value]; + if (cachedObj) return cachedObj; + } + obj = fromBits(value, value < 0 ? -1 : 0, false); + if (cache) INT_CACHE[value] = obj; + return obj; + } + } + Long.fromInt = fromInt; + function fromNumber(value, unsigned) { + if (isNaN(value)) return unsigned ? UZERO : ZERO; + if (unsigned) { + if (value < 0) return UZERO; + if (value >= TWO_PWR_64_DBL) return MAX_UNSIGNED_VALUE; + } else { + if (value <= -TWO_PWR_63_DBL) return MIN_VALUE; + if (value + 1 >= TWO_PWR_63_DBL) return MAX_VALUE; + } + if (value < 0) return fromNumber(-value, unsigned).neg(); + return fromBits( + value % TWO_PWR_32_DBL | 0, + value / TWO_PWR_32_DBL | 0, + unsigned + ); + } + Long.fromNumber = fromNumber; + function fromBits(lowBits, highBits, unsigned) { + return new Long(lowBits, highBits, unsigned); + } + Long.fromBits = fromBits; + var pow_dbl = Math.pow; + function fromString(str, unsigned, radix) { + if (str.length === 0) throw Error("empty string"); + if (typeof unsigned === "number") { + radix = unsigned; + unsigned = false; + } else { + unsigned = !!unsigned; + } + if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity") + return unsigned ? UZERO : ZERO; + radix = radix || 10; + if (radix < 2 || 36 < radix) throw RangeError("radix"); + var p; + if ((p = str.indexOf("-")) > 0) throw Error("interior hyphen"); + else if (p === 0) { + return fromString(str.substring(1), unsigned, radix).neg(); + } + var radixToPower = fromNumber(pow_dbl(radix, 8)); + var result = ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = fromNumber(pow_dbl(radix, size)); + result = result.mul(power).add(fromNumber(value)); + } else { + result = result.mul(radixToPower); + result = result.add(fromNumber(value)); + } + } + result.unsigned = unsigned; + return result; + } + Long.fromString = fromString; + function fromValue(val, unsigned) { + if (typeof val === "number") return fromNumber(val, unsigned); + if (typeof val === "string") return fromString(val, unsigned); + return fromBits( + val.low, + val.high, + typeof unsigned === "boolean" ? unsigned : val.unsigned + ); + } + Long.fromValue = fromValue; + var TWO_PWR_16_DBL = 1 << 16; + var TWO_PWR_24_DBL = 1 << 24; + var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; + var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; + var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; + var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL); + var ZERO = fromInt(0); + Long.ZERO = ZERO; + var UZERO = fromInt(0, true); + Long.UZERO = UZERO; + var ONE = fromInt(1); + Long.ONE = ONE; + var UONE = fromInt(1, true); + Long.UONE = UONE; + var NEG_ONE = fromInt(-1); + Long.NEG_ONE = NEG_ONE; + var MAX_VALUE = fromBits(4294967295 | 0, 2147483647 | 0, false); + Long.MAX_VALUE = MAX_VALUE; + var MAX_UNSIGNED_VALUE = fromBits(4294967295 | 0, 4294967295 | 0, true); + Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE; + var MIN_VALUE = fromBits(0, 2147483648 | 0, false); + Long.MIN_VALUE = MIN_VALUE; + var LongPrototype = Long.prototype; + LongPrototype.toInt = function toInt() { + return this.unsigned ? this.low >>> 0 : this.low; + }; + LongPrototype.toNumber = function toNumber() { + if (this.unsigned) + return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); + return this.high * TWO_PWR_32_DBL + (this.low >>> 0); + }; + LongPrototype.toString = function toString(radix) { + radix = radix || 10; + if (radix < 2 || 36 < radix) throw RangeError("radix"); + if (this.isZero()) return "0"; + if (this.isNegative()) { + if (this.eq(MIN_VALUE)) { + var radixLong = fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this); + return div.toString(radix) + rem1.toInt().toString(radix); + } else return "-" + this.neg().toString(radix); + } + var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned), rem = this; + var result = ""; + while (true) { + var remDiv = rem.div(radixToPower), intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0, digits = intval.toString(radix); + rem = remDiv; + if (rem.isZero()) return digits + result; + else { + while (digits.length < 6) digits = "0" + digits; + result = "" + digits + result; + } + } + }; + LongPrototype.getHighBits = function getHighBits() { + return this.high; + }; + LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() { + return this.high >>> 0; + }; + LongPrototype.getLowBits = function getLowBits() { + return this.low; + }; + LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() { + return this.low >>> 0; + }; + LongPrototype.getNumBitsAbs = function getNumBitsAbs() { + if (this.isNegative()) + return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); + var val = this.high != 0 ? this.high : this.low; + for (var bit = 31; bit > 0; bit--) if ((val & 1 << bit) != 0) break; + return this.high != 0 ? bit + 33 : bit + 1; + }; + LongPrototype.isSafeInteger = function isSafeInteger() { + var top11Bits = this.high >> 21; + if (!top11Bits) return true; + if (this.unsigned) return false; + return top11Bits === -1 && !(this.low === 0 && this.high === -2097152); + }; + LongPrototype.isZero = function isZero() { + return this.high === 0 && this.low === 0; + }; + LongPrototype.eqz = LongPrototype.isZero; + LongPrototype.isNegative = function isNegative() { + return !this.unsigned && this.high < 0; + }; + LongPrototype.isPositive = function isPositive() { + return this.unsigned || this.high >= 0; + }; + LongPrototype.isOdd = function isOdd() { + return (this.low & 1) === 1; + }; + LongPrototype.isEven = function isEven() { + return (this.low & 1) === 0; + }; + LongPrototype.equals = function equals(other) { + if (!isLong(other)) other = fromValue(other); + if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) + return false; + return this.high === other.high && this.low === other.low; + }; + LongPrototype.eq = LongPrototype.equals; + LongPrototype.notEquals = function notEquals(other) { + return !this.eq( + /* validates */ + other + ); + }; + LongPrototype.neq = LongPrototype.notEquals; + LongPrototype.ne = LongPrototype.notEquals; + LongPrototype.lessThan = function lessThan(other) { + return this.comp( + /* validates */ + other + ) < 0; + }; + LongPrototype.lt = LongPrototype.lessThan; + LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) { + return this.comp( + /* validates */ + other + ) <= 0; + }; + LongPrototype.lte = LongPrototype.lessThanOrEqual; + LongPrototype.le = LongPrototype.lessThanOrEqual; + LongPrototype.greaterThan = function greaterThan(other) { + return this.comp( + /* validates */ + other + ) > 0; + }; + LongPrototype.gt = LongPrototype.greaterThan; + LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) { + return this.comp( + /* validates */ + other + ) >= 0; + }; + LongPrototype.gte = LongPrototype.greaterThanOrEqual; + LongPrototype.ge = LongPrototype.greaterThanOrEqual; + LongPrototype.compare = function compare(other) { + if (!isLong(other)) other = fromValue(other); + if (this.eq(other)) return 0; + var thisNeg = this.isNegative(), otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) return -1; + if (!thisNeg && otherNeg) return 1; + if (!this.unsigned) return this.sub(other).isNegative() ? -1 : 1; + return other.high >>> 0 > this.high >>> 0 || other.high === this.high && other.low >>> 0 > this.low >>> 0 ? -1 : 1; + }; + LongPrototype.comp = LongPrototype.compare; + LongPrototype.negate = function negate() { + if (!this.unsigned && this.eq(MIN_VALUE)) return MIN_VALUE; + return this.not().add(ONE); + }; + LongPrototype.neg = LongPrototype.negate; + LongPrototype.add = function add(addend) { + if (!isLong(addend)) addend = fromValue(addend); + var a48 = this.high >>> 16; + var a32 = this.high & 65535; + var a16 = this.low >>> 16; + var a00 = this.low & 65535; + var b48 = addend.high >>> 16; + var b32 = addend.high & 65535; + var b16 = addend.low >>> 16; + var b00 = addend.low & 65535; + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 65535; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 65535; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 65535; + c48 += a48 + b48; + c48 &= 65535; + return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned); + }; + LongPrototype.subtract = function subtract(subtrahend) { + if (!isLong(subtrahend)) subtrahend = fromValue(subtrahend); + return this.add(subtrahend.neg()); + }; + LongPrototype.sub = LongPrototype.subtract; + LongPrototype.multiply = function multiply(multiplier) { + if (this.isZero()) return this; + if (!isLong(multiplier)) multiplier = fromValue(multiplier); + if (wasm) { + var low = wasm["mul"]( + this.low, + this.high, + multiplier.low, + multiplier.high + ); + return fromBits(low, wasm["get_high"](), this.unsigned); + } + if (multiplier.isZero()) return this.unsigned ? UZERO : ZERO; + if (this.eq(MIN_VALUE)) return multiplier.isOdd() ? MIN_VALUE : ZERO; + if (multiplier.eq(MIN_VALUE)) return this.isOdd() ? MIN_VALUE : ZERO; + if (this.isNegative()) { + if (multiplier.isNegative()) return this.neg().mul(multiplier.neg()); + else return this.neg().mul(multiplier).neg(); + } else if (multiplier.isNegative()) + return this.mul(multiplier.neg()).neg(); + if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24)) + return fromNumber( + this.toNumber() * multiplier.toNumber(), + this.unsigned + ); + var a48 = this.high >>> 16; + var a32 = this.high & 65535; + var a16 = this.low >>> 16; + var a00 = this.low & 65535; + var b48 = multiplier.high >>> 16; + var b32 = multiplier.high & 65535; + var b16 = multiplier.low >>> 16; + var b00 = multiplier.low & 65535; + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 65535; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 65535; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 65535; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 65535; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 65535; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 65535; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 65535; + return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned); + }; + LongPrototype.mul = LongPrototype.multiply; + LongPrototype.divide = function divide(divisor) { + if (!isLong(divisor)) divisor = fromValue(divisor); + if (divisor.isZero()) throw Error("division by zero"); + if (wasm) { + if (!this.unsigned && this.high === -2147483648 && divisor.low === -1 && divisor.high === -1) { + return this; + } + var low = (this.unsigned ? wasm["div_u"] : wasm["div_s"])( + this.low, + this.high, + divisor.low, + divisor.high + ); + return fromBits(low, wasm["get_high"](), this.unsigned); + } + if (this.isZero()) return this.unsigned ? UZERO : ZERO; + var approx, rem, res; + if (!this.unsigned) { + if (this.eq(MIN_VALUE)) { + if (divisor.eq(ONE) || divisor.eq(NEG_ONE)) + return MIN_VALUE; + else if (divisor.eq(MIN_VALUE)) return ONE; + else { + var halfThis = this.shr(1); + approx = halfThis.div(divisor).shl(1); + if (approx.eq(ZERO)) { + return divisor.isNegative() ? ONE : NEG_ONE; + } else { + rem = this.sub(divisor.mul(approx)); + res = approx.add(rem.div(divisor)); + return res; + } + } + } else if (divisor.eq(MIN_VALUE)) return this.unsigned ? UZERO : ZERO; + if (this.isNegative()) { + if (divisor.isNegative()) return this.neg().div(divisor.neg()); + return this.neg().div(divisor).neg(); + } else if (divisor.isNegative()) return this.div(divisor.neg()).neg(); + res = ZERO; + } else { + if (!divisor.unsigned) divisor = divisor.toUnsigned(); + if (divisor.gt(this)) return UZERO; + if (divisor.gt(this.shru(1))) + return UONE; + res = UZERO; + } + rem = this; + while (rem.gte(divisor)) { + approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); + var log2 = Math.ceil(Math.log(approx) / Math.LN2), delta = log2 <= 48 ? 1 : pow_dbl(2, log2 - 48), approxRes = fromNumber(approx), approxRem = approxRes.mul(divisor); + while (approxRem.isNegative() || approxRem.gt(rem)) { + approx -= delta; + approxRes = fromNumber(approx, this.unsigned); + approxRem = approxRes.mul(divisor); + } + if (approxRes.isZero()) approxRes = ONE; + res = res.add(approxRes); + rem = rem.sub(approxRem); + } + return res; + }; + LongPrototype.div = LongPrototype.divide; + LongPrototype.modulo = function modulo(divisor) { + if (!isLong(divisor)) divisor = fromValue(divisor); + if (wasm) { + var low = (this.unsigned ? wasm["rem_u"] : wasm["rem_s"])( + this.low, + this.high, + divisor.low, + divisor.high + ); + return fromBits(low, wasm["get_high"](), this.unsigned); + } + return this.sub(this.div(divisor).mul(divisor)); + }; + LongPrototype.mod = LongPrototype.modulo; + LongPrototype.rem = LongPrototype.modulo; + LongPrototype.not = function not() { + return fromBits(~this.low, ~this.high, this.unsigned); + }; + LongPrototype.countLeadingZeros = function countLeadingZeros() { + return this.high ? Math.clz32(this.high) : Math.clz32(this.low) + 32; + }; + LongPrototype.clz = LongPrototype.countLeadingZeros; + LongPrototype.countTrailingZeros = function countTrailingZeros() { + return this.low ? ctz32(this.low) : ctz32(this.high) + 32; + }; + LongPrototype.ctz = LongPrototype.countTrailingZeros; + LongPrototype.and = function and(other) { + if (!isLong(other)) other = fromValue(other); + return fromBits( + this.low & other.low, + this.high & other.high, + this.unsigned + ); + }; + LongPrototype.or = function or(other) { + if (!isLong(other)) other = fromValue(other); + return fromBits( + this.low | other.low, + this.high | other.high, + this.unsigned + ); + }; + LongPrototype.xor = function xor(other) { + if (!isLong(other)) other = fromValue(other); + return fromBits( + this.low ^ other.low, + this.high ^ other.high, + this.unsigned + ); + }; + LongPrototype.shiftLeft = function shiftLeft(numBits) { + if (isLong(numBits)) numBits = numBits.toInt(); + if ((numBits &= 63) === 0) return this; + else if (numBits < 32) + return fromBits( + this.low << numBits, + this.high << numBits | this.low >>> 32 - numBits, + this.unsigned + ); + else return fromBits(0, this.low << numBits - 32, this.unsigned); + }; + LongPrototype.shl = LongPrototype.shiftLeft; + LongPrototype.shiftRight = function shiftRight(numBits) { + if (isLong(numBits)) numBits = numBits.toInt(); + if ((numBits &= 63) === 0) return this; + else if (numBits < 32) + return fromBits( + this.low >>> numBits | this.high << 32 - numBits, + this.high >> numBits, + this.unsigned + ); + else + return fromBits( + this.high >> numBits - 32, + this.high >= 0 ? 0 : -1, + this.unsigned + ); + }; + LongPrototype.shr = LongPrototype.shiftRight; + LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) { + if (isLong(numBits)) numBits = numBits.toInt(); + if ((numBits &= 63) === 0) return this; + if (numBits < 32) + return fromBits( + this.low >>> numBits | this.high << 32 - numBits, + this.high >>> numBits, + this.unsigned + ); + if (numBits === 32) return fromBits(this.high, 0, this.unsigned); + return fromBits(this.high >>> numBits - 32, 0, this.unsigned); + }; + LongPrototype.shru = LongPrototype.shiftRightUnsigned; + LongPrototype.shr_u = LongPrototype.shiftRightUnsigned; + LongPrototype.rotateLeft = function rotateLeft(numBits) { + var b; + if (isLong(numBits)) numBits = numBits.toInt(); + if ((numBits &= 63) === 0) return this; + if (numBits === 32) return fromBits(this.high, this.low, this.unsigned); + if (numBits < 32) { + b = 32 - numBits; + return fromBits( + this.low << numBits | this.high >>> b, + this.high << numBits | this.low >>> b, + this.unsigned + ); + } + numBits -= 32; + b = 32 - numBits; + return fromBits( + this.high << numBits | this.low >>> b, + this.low << numBits | this.high >>> b, + this.unsigned + ); + }; + LongPrototype.rotl = LongPrototype.rotateLeft; + LongPrototype.rotateRight = function rotateRight(numBits) { + var b; + if (isLong(numBits)) numBits = numBits.toInt(); + if ((numBits &= 63) === 0) return this; + if (numBits === 32) return fromBits(this.high, this.low, this.unsigned); + if (numBits < 32) { + b = 32 - numBits; + return fromBits( + this.high << b | this.low >>> numBits, + this.low << b | this.high >>> numBits, + this.unsigned + ); + } + numBits -= 32; + b = 32 - numBits; + return fromBits( + this.low << b | this.high >>> numBits, + this.high << b | this.low >>> numBits, + this.unsigned + ); + }; + LongPrototype.rotr = LongPrototype.rotateRight; + LongPrototype.toSigned = function toSigned() { + if (!this.unsigned) return this; + return fromBits(this.low, this.high, false); + }; + LongPrototype.toUnsigned = function toUnsigned() { + if (this.unsigned) return this; + return fromBits(this.low, this.high, true); + }; + LongPrototype.toBytes = function toBytes(le) { + return le ? this.toBytesLE() : this.toBytesBE(); + }; + LongPrototype.toBytesLE = function toBytesLE() { + var hi = this.high, lo = this.low; + return [ + lo & 255, + lo >>> 8 & 255, + lo >>> 16 & 255, + lo >>> 24, + hi & 255, + hi >>> 8 & 255, + hi >>> 16 & 255, + hi >>> 24 + ]; + }; + LongPrototype.toBytesBE = function toBytesBE() { + var hi = this.high, lo = this.low; + return [ + hi >>> 24, + hi >>> 16 & 255, + hi >>> 8 & 255, + hi & 255, + lo >>> 24, + lo >>> 16 & 255, + lo >>> 8 & 255, + lo & 255 + ]; + }; + Long.fromBytes = function fromBytes(bytes, unsigned, le) { + return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); + }; + Long.fromBytesLE = function fromBytesLE(bytes, unsigned) { + return new Long( + bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24, + bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24, + unsigned + ); + }; + Long.fromBytesBE = function fromBytesBE(bytes, unsigned) { + return new Long( + bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7], + bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], + unsigned + ); + }; + if (typeof BigInt === "function") { + Long.fromBigInt = function fromBigInt2(value, unsigned) { + var lowBits = Number(BigInt.asIntN(32, value)); + var highBits = Number(BigInt.asIntN(32, value >> BigInt(32))); + return fromBits(lowBits, highBits, unsigned); + }; + Long.fromValue = function fromValueWithBigInt(value, unsigned) { + if (typeof value === "bigint") return fromBigInt(value, unsigned); + return fromValue(value, unsigned); + }; + LongPrototype.toBigInt = function toBigInt() { + var lowBigInt = BigInt(this.low >>> 0); + var highBigInt = BigInt(this.unsigned ? this.high >>> 0 : this.high); + return highBigInt << BigInt(32) | lowBigInt; + }; + } + var _default = _exports.default = Long; + } + ); + } +}); + +// node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/index.js +var require_src3 = __commonJS({ + "node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.loadFileDescriptorSetFromObject = exports2.loadFileDescriptorSetFromBuffer = exports2.fromJSON = exports2.loadSync = exports2.load = exports2.IdempotencyLevel = exports2.isAnyExtension = exports2.Long = void 0; + var camelCase = require_lodash(); + var Protobuf = require_protobufjs(); + var descriptor = require_descriptor2(); + var util_1 = require_util11(); + var Long = require_umd(); + exports2.Long = Long; + function isAnyExtension(obj) { + return "@type" in obj && typeof obj["@type"] === "string"; + } + exports2.isAnyExtension = isAnyExtension; + var IdempotencyLevel; + (function(IdempotencyLevel2) { + IdempotencyLevel2["IDEMPOTENCY_UNKNOWN"] = "IDEMPOTENCY_UNKNOWN"; + IdempotencyLevel2["NO_SIDE_EFFECTS"] = "NO_SIDE_EFFECTS"; + IdempotencyLevel2["IDEMPOTENT"] = "IDEMPOTENT"; + })(IdempotencyLevel = exports2.IdempotencyLevel || (exports2.IdempotencyLevel = {})); + var descriptorOptions = { + longs: String, + enums: String, + bytes: String, + defaults: true, + oneofs: true, + json: true + }; + function joinName(baseName, name) { + if (baseName === "") { + return name; + } else { + return baseName + "." + name; + } + } + function isHandledReflectionObject(obj) { + return obj instanceof Protobuf.Service || obj instanceof Protobuf.Type || obj instanceof Protobuf.Enum; + } + function isNamespaceBase(obj) { + return obj instanceof Protobuf.Namespace || obj instanceof Protobuf.Root; + } + function getAllHandledReflectionObjects(obj, parentName) { + const objName = joinName(parentName, obj.name); + if (isHandledReflectionObject(obj)) { + return [[objName, obj]]; + } else { + if (isNamespaceBase(obj) && typeof obj.nested !== "undefined") { + return Object.keys(obj.nested).map((name) => { + return getAllHandledReflectionObjects(obj.nested[name], objName); + }).reduce((accumulator, currentValue) => accumulator.concat(currentValue), []); + } + } + return []; + } + function createDeserializer(cls, options) { + return function deserialize(argBuf) { + return cls.toObject(cls.decode(argBuf), options); + }; + } + function createSerializer(cls) { + return function serialize(arg) { + if (Array.isArray(arg)) { + throw new Error(`Failed to serialize message: expected object with ${cls.name} structure, got array instead`); + } + const message = cls.fromObject(arg); + return cls.encode(message).finish(); + }; + } + function mapMethodOptions(options) { + return (options || []).reduce((obj, item) => { + for (const [key, value] of Object.entries(item)) { + switch (key) { + case "uninterpreted_option": + obj.uninterpreted_option.push(item.uninterpreted_option); + break; + default: + obj[key] = value; + } + } + return obj; + }, { + deprecated: false, + idempotency_level: IdempotencyLevel.IDEMPOTENCY_UNKNOWN, + uninterpreted_option: [] + }); + } + function createMethodDefinition(method, serviceName, options, fileDescriptors) { + const requestType = method.resolvedRequestType; + const responseType = method.resolvedResponseType; + return { + path: "/" + serviceName + "/" + method.name, + requestStream: !!method.requestStream, + responseStream: !!method.responseStream, + requestSerialize: createSerializer(requestType), + requestDeserialize: createDeserializer(requestType, options), + responseSerialize: createSerializer(responseType), + responseDeserialize: createDeserializer(responseType, options), + // TODO(murgatroid99): Find a better way to handle this + originalName: camelCase(method.name), + requestType: createMessageDefinition(requestType, options, fileDescriptors), + responseType: createMessageDefinition(responseType, options, fileDescriptors), + options: mapMethodOptions(method.parsedOptions) + }; + } + function createServiceDefinition(service, name, options, fileDescriptors) { + const def = {}; + for (const method of service.methodsArray) { + def[method.name] = createMethodDefinition(method, name, options, fileDescriptors); + } + return def; + } + function createMessageDefinition(message, options, fileDescriptors) { + const messageDescriptor = message.toDescriptor("proto3"); + return { + format: "Protocol Buffer 3 DescriptorProto", + type: messageDescriptor.$type.toObject(messageDescriptor, descriptorOptions), + fileDescriptorProtos: fileDescriptors, + serialize: createSerializer(message), + deserialize: createDeserializer(message, options) + }; + } + function createEnumDefinition(enumType, fileDescriptors) { + const enumDescriptor = enumType.toDescriptor("proto3"); + return { + format: "Protocol Buffer 3 EnumDescriptorProto", + type: enumDescriptor.$type.toObject(enumDescriptor, descriptorOptions), + fileDescriptorProtos: fileDescriptors + }; + } + function createDefinition(obj, name, options, fileDescriptors) { + if (obj instanceof Protobuf.Service) { + return createServiceDefinition(obj, name, options, fileDescriptors); + } else if (obj instanceof Protobuf.Type) { + return createMessageDefinition(obj, options, fileDescriptors); + } else if (obj instanceof Protobuf.Enum) { + return createEnumDefinition(obj, fileDescriptors); + } else { + throw new Error("Type mismatch in reflection object handling"); + } + } + function createPackageDefinition(root, options) { + const def = {}; + root.resolveAll(); + const descriptorList = root.toDescriptor("proto3").file; + const bufferList = descriptorList.map((value) => Buffer.from(descriptor.FileDescriptorProto.encode(value).finish())); + for (const [name, obj] of getAllHandledReflectionObjects(root, "")) { + def[name] = createDefinition(obj, name, options, bufferList); + } + return def; + } + function createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options) { + options = options || {}; + const root = Protobuf.Root.fromDescriptor(decodedDescriptorSet); + root.resolveAll(); + return createPackageDefinition(root, options); + } + function load(filename, options) { + return (0, util_1.loadProtosWithOptions)(filename, options).then((loadedRoot) => { + return createPackageDefinition(loadedRoot, options); + }); + } + exports2.load = load; + function loadSync(filename, options) { + const loadedRoot = (0, util_1.loadProtosWithOptionsSync)(filename, options); + return createPackageDefinition(loadedRoot, options); + } + exports2.loadSync = loadSync; + function fromJSON(json, options) { + options = options || {}; + const loadedRoot = Protobuf.Root.fromJSON(json); + loadedRoot.resolveAll(); + return createPackageDefinition(loadedRoot, options); + } + exports2.fromJSON = fromJSON; + function loadFileDescriptorSetFromBuffer(descriptorSet, options) { + const decodedDescriptorSet = descriptor.FileDescriptorSet.decode(descriptorSet); + return createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options); + } + exports2.loadFileDescriptorSetFromBuffer = loadFileDescriptorSetFromBuffer; + function loadFileDescriptorSetFromObject(descriptorSet, options) { + const decodedDescriptorSet = descriptor.FileDescriptorSet.fromObject(descriptorSet); + return createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options); + } + exports2.loadFileDescriptorSetFromObject = loadFileDescriptorSetFromObject; + (0, util_1.addCommonProtos)(); + } +}); + +// node_modules/@grpc/grpc-js/build/src/channelz.js +var require_channelz = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/channelz.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.registerChannelzSocket = exports2.registerChannelzServer = exports2.registerChannelzSubchannel = exports2.registerChannelzChannel = exports2.ChannelzCallTrackerStub = exports2.ChannelzCallTracker = exports2.ChannelzChildrenTrackerStub = exports2.ChannelzChildrenTracker = exports2.ChannelzTrace = exports2.ChannelzTraceStub = void 0; + exports2.unregisterChannelzRef = unregisterChannelzRef; + exports2.getChannelzHandlers = getChannelzHandlers; + exports2.getChannelzServiceDefinition = getChannelzServiceDefinition; + exports2.setup = setup; + var net_1 = require("net"); + var ordered_map_1 = require_cjs(); + var connectivity_state_1 = require_connectivity_state(); + var constants_1 = require_constants7(); + var subchannel_address_1 = require_subchannel_address(); + var admin_1 = require_admin(); + var make_client_1 = require_make_client(); + function channelRefToMessage(ref) { + return { + channel_id: ref.id, + name: ref.name + }; + } + function subchannelRefToMessage(ref) { + return { + subchannel_id: ref.id, + name: ref.name + }; + } + function serverRefToMessage(ref) { + return { + server_id: ref.id + }; + } + function socketRefToMessage(ref) { + return { + socket_id: ref.id, + name: ref.name + }; + } + var TARGET_RETAINED_TRACES = 32; + var DEFAULT_MAX_RESULTS = 100; + var ChannelzTraceStub = class { + constructor() { + this.events = []; + this.creationTimestamp = /* @__PURE__ */ new Date(); + this.eventsLogged = 0; + } + addTrace() { + } + getTraceMessage() { + return { + creation_timestamp: dateToProtoTimestamp(this.creationTimestamp), + num_events_logged: this.eventsLogged, + events: [] + }; + } + }; + exports2.ChannelzTraceStub = ChannelzTraceStub; + var ChannelzTrace = class { + constructor() { + this.events = []; + this.eventsLogged = 0; + this.creationTimestamp = /* @__PURE__ */ new Date(); + } + addTrace(severity, description, child) { + const timestamp = /* @__PURE__ */ new Date(); + this.events.push({ + description, + severity, + timestamp, + childChannel: (child === null || child === void 0 ? void 0 : child.kind) === "channel" ? child : void 0, + childSubchannel: (child === null || child === void 0 ? void 0 : child.kind) === "subchannel" ? child : void 0 + }); + if (this.events.length >= TARGET_RETAINED_TRACES * 2) { + this.events = this.events.slice(TARGET_RETAINED_TRACES); + } + this.eventsLogged += 1; + } + getTraceMessage() { + return { + creation_timestamp: dateToProtoTimestamp(this.creationTimestamp), + num_events_logged: this.eventsLogged, + events: this.events.map((event) => { + return { + description: event.description, + severity: event.severity, + timestamp: dateToProtoTimestamp(event.timestamp), + channel_ref: event.childChannel ? channelRefToMessage(event.childChannel) : null, + subchannel_ref: event.childSubchannel ? subchannelRefToMessage(event.childSubchannel) : null + }; + }) + }; + } + }; + exports2.ChannelzTrace = ChannelzTrace; + var ChannelzChildrenTracker = class { + constructor() { + this.channelChildren = new ordered_map_1.OrderedMap(); + this.subchannelChildren = new ordered_map_1.OrderedMap(); + this.socketChildren = new ordered_map_1.OrderedMap(); + this.trackerMap = { + [ + "channel" + /* EntityTypes.channel */ + ]: this.channelChildren, + [ + "subchannel" + /* EntityTypes.subchannel */ + ]: this.subchannelChildren, + [ + "socket" + /* EntityTypes.socket */ + ]: this.socketChildren + }; + } + refChild(child) { + const tracker = this.trackerMap[child.kind]; + const trackedChild = tracker.find(child.id); + if (trackedChild.equals(tracker.end())) { + tracker.setElement(child.id, { + ref: child, + count: 1 + }, trackedChild); + } else { + trackedChild.pointer[1].count += 1; + } + } + unrefChild(child) { + const tracker = this.trackerMap[child.kind]; + const trackedChild = tracker.getElementByKey(child.id); + if (trackedChild !== void 0) { + trackedChild.count -= 1; + if (trackedChild.count === 0) { + tracker.eraseElementByKey(child.id); + } + } + } + getChildLists() { + return { + channels: this.channelChildren, + subchannels: this.subchannelChildren, + sockets: this.socketChildren + }; + } + }; + exports2.ChannelzChildrenTracker = ChannelzChildrenTracker; + var ChannelzChildrenTrackerStub = class extends ChannelzChildrenTracker { + refChild() { + } + unrefChild() { + } + }; + exports2.ChannelzChildrenTrackerStub = ChannelzChildrenTrackerStub; + var ChannelzCallTracker = class { + constructor() { + this.callsStarted = 0; + this.callsSucceeded = 0; + this.callsFailed = 0; + this.lastCallStartedTimestamp = null; + } + addCallStarted() { + this.callsStarted += 1; + this.lastCallStartedTimestamp = /* @__PURE__ */ new Date(); + } + addCallSucceeded() { + this.callsSucceeded += 1; + } + addCallFailed() { + this.callsFailed += 1; + } + }; + exports2.ChannelzCallTracker = ChannelzCallTracker; + var ChannelzCallTrackerStub = class extends ChannelzCallTracker { + addCallStarted() { + } + addCallSucceeded() { + } + addCallFailed() { + } + }; + exports2.ChannelzCallTrackerStub = ChannelzCallTrackerStub; + var entityMaps = { + [ + "channel" + /* EntityTypes.channel */ + ]: new ordered_map_1.OrderedMap(), + [ + "subchannel" + /* EntityTypes.subchannel */ + ]: new ordered_map_1.OrderedMap(), + [ + "server" + /* EntityTypes.server */ + ]: new ordered_map_1.OrderedMap(), + [ + "socket" + /* EntityTypes.socket */ + ]: new ordered_map_1.OrderedMap() + }; + var generateRegisterFn = (kind) => { + let nextId = 1; + function getNextId() { + return nextId++; + } + const entityMap = entityMaps[kind]; + return (name, getInfo, channelzEnabled) => { + const id = getNextId(); + const ref = { id, name, kind }; + if (channelzEnabled) { + entityMap.setElement(id, { ref, getInfo }); + } + return ref; + }; + }; + exports2.registerChannelzChannel = generateRegisterFn( + "channel" + /* EntityTypes.channel */ + ); + exports2.registerChannelzSubchannel = generateRegisterFn( + "subchannel" + /* EntityTypes.subchannel */ + ); + exports2.registerChannelzServer = generateRegisterFn( + "server" + /* EntityTypes.server */ + ); + exports2.registerChannelzSocket = generateRegisterFn( + "socket" + /* EntityTypes.socket */ + ); + function unregisterChannelzRef(ref) { + entityMaps[ref.kind].eraseElementByKey(ref.id); + } + function parseIPv6Section(addressSection) { + const numberValue = Number.parseInt(addressSection, 16); + return [numberValue / 256 | 0, numberValue % 256]; + } + function parseIPv6Chunk(addressChunk) { + if (addressChunk === "") { + return []; + } + const bytePairs = addressChunk.split(":").map((section) => parseIPv6Section(section)); + const result = []; + return result.concat(...bytePairs); + } + function isIPv6MappedIPv4(ipAddress) { + return (0, net_1.isIPv6)(ipAddress) && ipAddress.toLowerCase().startsWith("::ffff:") && (0, net_1.isIPv4)(ipAddress.substring(7)); + } + function ipv4AddressStringToBuffer(ipAddress) { + return Buffer.from(Uint8Array.from(ipAddress.split(".").map((segment) => Number.parseInt(segment)))); + } + function ipAddressStringToBuffer(ipAddress) { + if ((0, net_1.isIPv4)(ipAddress)) { + return ipv4AddressStringToBuffer(ipAddress); + } else if (isIPv6MappedIPv4(ipAddress)) { + return ipv4AddressStringToBuffer(ipAddress.substring(7)); + } else if ((0, net_1.isIPv6)(ipAddress)) { + let leftSection; + let rightSection; + const doubleColonIndex = ipAddress.indexOf("::"); + if (doubleColonIndex === -1) { + leftSection = ipAddress; + rightSection = ""; + } else { + leftSection = ipAddress.substring(0, doubleColonIndex); + rightSection = ipAddress.substring(doubleColonIndex + 2); + } + const leftBuffer = Buffer.from(parseIPv6Chunk(leftSection)); + const rightBuffer = Buffer.from(parseIPv6Chunk(rightSection)); + const middleBuffer = Buffer.alloc(16 - leftBuffer.length - rightBuffer.length, 0); + return Buffer.concat([leftBuffer, middleBuffer, rightBuffer]); + } else { + return null; + } + } + function connectivityStateToMessage(state) { + switch (state) { + case connectivity_state_1.ConnectivityState.CONNECTING: + return { + state: "CONNECTING" + }; + case connectivity_state_1.ConnectivityState.IDLE: + return { + state: "IDLE" + }; + case connectivity_state_1.ConnectivityState.READY: + return { + state: "READY" + }; + case connectivity_state_1.ConnectivityState.SHUTDOWN: + return { + state: "SHUTDOWN" + }; + case connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE: + return { + state: "TRANSIENT_FAILURE" + }; + default: + return { + state: "UNKNOWN" + }; + } + } + function dateToProtoTimestamp(date) { + if (!date) { + return null; + } + const millisSinceEpoch = date.getTime(); + return { + seconds: millisSinceEpoch / 1e3 | 0, + nanos: millisSinceEpoch % 1e3 * 1e6 + }; + } + function getChannelMessage(channelEntry) { + const resolvedInfo = channelEntry.getInfo(); + const channelRef = []; + const subchannelRef = []; + resolvedInfo.children.channels.forEach((el) => { + channelRef.push(channelRefToMessage(el[1].ref)); + }); + resolvedInfo.children.subchannels.forEach((el) => { + subchannelRef.push(subchannelRefToMessage(el[1].ref)); + }); + return { + ref: channelRefToMessage(channelEntry.ref), + data: { + target: resolvedInfo.target, + state: connectivityStateToMessage(resolvedInfo.state), + calls_started: resolvedInfo.callTracker.callsStarted, + calls_succeeded: resolvedInfo.callTracker.callsSucceeded, + calls_failed: resolvedInfo.callTracker.callsFailed, + last_call_started_timestamp: dateToProtoTimestamp(resolvedInfo.callTracker.lastCallStartedTimestamp), + trace: resolvedInfo.trace.getTraceMessage() + }, + channel_ref: channelRef, + subchannel_ref: subchannelRef + }; + } + function GetChannel(call, callback) { + const channelId = parseInt(call.request.channel_id, 10); + const channelEntry = entityMaps[ + "channel" + /* EntityTypes.channel */ + ].getElementByKey(channelId); + if (channelEntry === void 0) { + callback({ + code: constants_1.Status.NOT_FOUND, + details: "No channel data found for id " + channelId + }); + return; + } + callback(null, { channel: getChannelMessage(channelEntry) }); + } + function GetTopChannels(call, callback) { + const maxResults = parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS; + const resultList = []; + const startId = parseInt(call.request.start_channel_id, 10); + const channelEntries = entityMaps[ + "channel" + /* EntityTypes.channel */ + ]; + let i; + for (i = channelEntries.lowerBound(startId); !i.equals(channelEntries.end()) && resultList.length < maxResults; i = i.next()) { + resultList.push(getChannelMessage(i.pointer[1])); + } + callback(null, { + channel: resultList, + end: i.equals(channelEntries.end()) + }); + } + function getServerMessage(serverEntry) { + const resolvedInfo = serverEntry.getInfo(); + const listenSocket = []; + resolvedInfo.listenerChildren.sockets.forEach((el) => { + listenSocket.push(socketRefToMessage(el[1].ref)); + }); + return { + ref: serverRefToMessage(serverEntry.ref), + data: { + calls_started: resolvedInfo.callTracker.callsStarted, + calls_succeeded: resolvedInfo.callTracker.callsSucceeded, + calls_failed: resolvedInfo.callTracker.callsFailed, + last_call_started_timestamp: dateToProtoTimestamp(resolvedInfo.callTracker.lastCallStartedTimestamp), + trace: resolvedInfo.trace.getTraceMessage() + }, + listen_socket: listenSocket + }; + } + function GetServer(call, callback) { + const serverId = parseInt(call.request.server_id, 10); + const serverEntries = entityMaps[ + "server" + /* EntityTypes.server */ + ]; + const serverEntry = serverEntries.getElementByKey(serverId); + if (serverEntry === void 0) { + callback({ + code: constants_1.Status.NOT_FOUND, + details: "No server data found for id " + serverId + }); + return; + } + callback(null, { server: getServerMessage(serverEntry) }); + } + function GetServers(call, callback) { + const maxResults = parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS; + const startId = parseInt(call.request.start_server_id, 10); + const serverEntries = entityMaps[ + "server" + /* EntityTypes.server */ + ]; + const resultList = []; + let i; + for (i = serverEntries.lowerBound(startId); !i.equals(serverEntries.end()) && resultList.length < maxResults; i = i.next()) { + resultList.push(getServerMessage(i.pointer[1])); + } + callback(null, { + server: resultList, + end: i.equals(serverEntries.end()) + }); + } + function GetSubchannel(call, callback) { + const subchannelId = parseInt(call.request.subchannel_id, 10); + const subchannelEntry = entityMaps[ + "subchannel" + /* EntityTypes.subchannel */ + ].getElementByKey(subchannelId); + if (subchannelEntry === void 0) { + callback({ + code: constants_1.Status.NOT_FOUND, + details: "No subchannel data found for id " + subchannelId + }); + return; + } + const resolvedInfo = subchannelEntry.getInfo(); + const listenSocket = []; + resolvedInfo.children.sockets.forEach((el) => { + listenSocket.push(socketRefToMessage(el[1].ref)); + }); + const subchannelMessage = { + ref: subchannelRefToMessage(subchannelEntry.ref), + data: { + target: resolvedInfo.target, + state: connectivityStateToMessage(resolvedInfo.state), + calls_started: resolvedInfo.callTracker.callsStarted, + calls_succeeded: resolvedInfo.callTracker.callsSucceeded, + calls_failed: resolvedInfo.callTracker.callsFailed, + last_call_started_timestamp: dateToProtoTimestamp(resolvedInfo.callTracker.lastCallStartedTimestamp), + trace: resolvedInfo.trace.getTraceMessage() + }, + socket_ref: listenSocket + }; + callback(null, { subchannel: subchannelMessage }); + } + function subchannelAddressToAddressMessage(subchannelAddress) { + var _a; + if ((0, subchannel_address_1.isTcpSubchannelAddress)(subchannelAddress)) { + return { + address: "tcpip_address", + tcpip_address: { + ip_address: (_a = ipAddressStringToBuffer(subchannelAddress.host)) !== null && _a !== void 0 ? _a : void 0, + port: subchannelAddress.port + } + }; + } else { + return { + address: "uds_address", + uds_address: { + filename: subchannelAddress.path + } + }; + } + } + function GetSocket(call, callback) { + var _a, _b, _c, _d, _e; + const socketId = parseInt(call.request.socket_id, 10); + const socketEntry = entityMaps[ + "socket" + /* EntityTypes.socket */ + ].getElementByKey(socketId); + if (socketEntry === void 0) { + callback({ + code: constants_1.Status.NOT_FOUND, + details: "No socket data found for id " + socketId + }); + return; + } + const resolvedInfo = socketEntry.getInfo(); + const securityMessage = resolvedInfo.security ? { + model: "tls", + tls: { + cipher_suite: resolvedInfo.security.cipherSuiteStandardName ? "standard_name" : "other_name", + standard_name: (_a = resolvedInfo.security.cipherSuiteStandardName) !== null && _a !== void 0 ? _a : void 0, + other_name: (_b = resolvedInfo.security.cipherSuiteOtherName) !== null && _b !== void 0 ? _b : void 0, + local_certificate: (_c = resolvedInfo.security.localCertificate) !== null && _c !== void 0 ? _c : void 0, + remote_certificate: (_d = resolvedInfo.security.remoteCertificate) !== null && _d !== void 0 ? _d : void 0 + } + } : null; + const socketMessage = { + ref: socketRefToMessage(socketEntry.ref), + local: resolvedInfo.localAddress ? subchannelAddressToAddressMessage(resolvedInfo.localAddress) : null, + remote: resolvedInfo.remoteAddress ? subchannelAddressToAddressMessage(resolvedInfo.remoteAddress) : null, + remote_name: (_e = resolvedInfo.remoteName) !== null && _e !== void 0 ? _e : void 0, + security: securityMessage, + data: { + keep_alives_sent: resolvedInfo.keepAlivesSent, + streams_started: resolvedInfo.streamsStarted, + streams_succeeded: resolvedInfo.streamsSucceeded, + streams_failed: resolvedInfo.streamsFailed, + last_local_stream_created_timestamp: dateToProtoTimestamp(resolvedInfo.lastLocalStreamCreatedTimestamp), + last_remote_stream_created_timestamp: dateToProtoTimestamp(resolvedInfo.lastRemoteStreamCreatedTimestamp), + messages_received: resolvedInfo.messagesReceived, + messages_sent: resolvedInfo.messagesSent, + last_message_received_timestamp: dateToProtoTimestamp(resolvedInfo.lastMessageReceivedTimestamp), + last_message_sent_timestamp: dateToProtoTimestamp(resolvedInfo.lastMessageSentTimestamp), + local_flow_control_window: resolvedInfo.localFlowControlWindow ? { value: resolvedInfo.localFlowControlWindow } : null, + remote_flow_control_window: resolvedInfo.remoteFlowControlWindow ? { value: resolvedInfo.remoteFlowControlWindow } : null + } + }; + callback(null, { socket: socketMessage }); + } + function GetServerSockets(call, callback) { + const serverId = parseInt(call.request.server_id, 10); + const serverEntry = entityMaps[ + "server" + /* EntityTypes.server */ + ].getElementByKey(serverId); + if (serverEntry === void 0) { + callback({ + code: constants_1.Status.NOT_FOUND, + details: "No server data found for id " + serverId + }); + return; + } + const startId = parseInt(call.request.start_socket_id, 10); + const maxResults = parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS; + const resolvedInfo = serverEntry.getInfo(); + const allSockets = resolvedInfo.sessionChildren.sockets; + const resultList = []; + let i; + for (i = allSockets.lowerBound(startId); !i.equals(allSockets.end()) && resultList.length < maxResults; i = i.next()) { + resultList.push(socketRefToMessage(i.pointer[1].ref)); + } + callback(null, { + socket_ref: resultList, + end: i.equals(allSockets.end()) + }); + } + function getChannelzHandlers() { + return { + GetChannel, + GetTopChannels, + GetServer, + GetServers, + GetSubchannel, + GetSocket, + GetServerSockets + }; + } + var loadedChannelzDefinition = null; + function getChannelzServiceDefinition() { + if (loadedChannelzDefinition) { + return loadedChannelzDefinition; + } + const loaderLoadSync = require_src3().loadSync; + const loadedProto = loaderLoadSync("channelz.proto", { + keepCase: true, + longs: String, + enums: String, + defaults: true, + oneofs: true, + includeDirs: [`${__dirname}/../../proto`] + }); + const channelzGrpcObject = (0, make_client_1.loadPackageDefinition)(loadedProto); + loadedChannelzDefinition = channelzGrpcObject.grpc.channelz.v1.Channelz.service; + return loadedChannelzDefinition; + } + function setup() { + (0, admin_1.registerAdminService)(getChannelzServiceDefinition, getChannelzHandlers); + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/call-number.js +var require_call_number = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/call-number.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getNextCallNumber = getNextCallNumber; + var nextCallNumber = 0; + function getNextCallNumber() { + return nextCallNumber++; + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/compression-algorithms.js +var require_compression_algorithms = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/compression-algorithms.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CompressionAlgorithms = void 0; + var CompressionAlgorithms; + (function(CompressionAlgorithms2) { + CompressionAlgorithms2[CompressionAlgorithms2["identity"] = 0] = "identity"; + CompressionAlgorithms2[CompressionAlgorithms2["deflate"] = 1] = "deflate"; + CompressionAlgorithms2[CompressionAlgorithms2["gzip"] = 2] = "gzip"; + })(CompressionAlgorithms || (exports2.CompressionAlgorithms = CompressionAlgorithms = {})); + } +}); + +// node_modules/@grpc/grpc-js/build/src/filter.js +var require_filter = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/filter.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.BaseFilter = void 0; + var BaseFilter = class { + async sendMetadata(metadata) { + return metadata; + } + receiveMetadata(metadata) { + return metadata; + } + async sendMessage(message) { + return message; + } + async receiveMessage(message) { + return message; + } + receiveTrailers(status) { + return status; + } + }; + exports2.BaseFilter = BaseFilter; + } +}); + +// node_modules/@grpc/grpc-js/build/src/compression-filter.js +var require_compression_filter = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/compression-filter.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CompressionFilterFactory = exports2.CompressionFilter = void 0; + var zlib = require("zlib"); + var compression_algorithms_1 = require_compression_algorithms(); + var constants_1 = require_constants7(); + var filter_1 = require_filter(); + var logging = require_logging(); + var isCompressionAlgorithmKey = (key) => { + return typeof key === "number" && typeof compression_algorithms_1.CompressionAlgorithms[key] === "string"; + }; + var CompressionHandler = class { + /** + * @param message Raw uncompressed message bytes + * @param compress Indicates whether the message should be compressed + * @return Framed message, compressed if applicable + */ + async writeMessage(message, compress) { + let messageBuffer = message; + if (compress) { + messageBuffer = await this.compressMessage(messageBuffer); + } + const output = Buffer.allocUnsafe(messageBuffer.length + 5); + output.writeUInt8(compress ? 1 : 0, 0); + output.writeUInt32BE(messageBuffer.length, 1); + messageBuffer.copy(output, 5); + return output; + } + /** + * @param data Framed message, possibly compressed + * @return Uncompressed message + */ + async readMessage(data) { + const compressed = data.readUInt8(0) === 1; + let messageBuffer = data.slice(5); + if (compressed) { + messageBuffer = await this.decompressMessage(messageBuffer); + } + return messageBuffer; + } + }; + var IdentityHandler = class extends CompressionHandler { + async compressMessage(message) { + return message; + } + async writeMessage(message, compress) { + const output = Buffer.allocUnsafe(message.length + 5); + output.writeUInt8(0, 0); + output.writeUInt32BE(message.length, 1); + message.copy(output, 5); + return output; + } + decompressMessage(message) { + return Promise.reject(new Error('Received compressed message but "grpc-encoding" header was identity')); + } + }; + var DeflateHandler = class extends CompressionHandler { + constructor(maxRecvMessageLength) { + super(); + this.maxRecvMessageLength = maxRecvMessageLength; + } + compressMessage(message) { + return new Promise((resolve, reject) => { + zlib.deflate(message, (err, output) => { + if (err) { + reject(err); + } else { + resolve(output); + } + }); + }); + } + decompressMessage(message) { + return new Promise((resolve, reject) => { + let totalLength = 0; + const messageParts = []; + const decompresser = zlib.createInflate(); + decompresser.on("error", (error2) => { + reject({ + code: constants_1.Status.INTERNAL, + details: "Failed to decompress deflate-encoded message" + }); + }); + decompresser.on("data", (chunk) => { + messageParts.push(chunk); + totalLength += chunk.byteLength; + if (this.maxRecvMessageLength !== -1 && totalLength > this.maxRecvMessageLength) { + decompresser.destroy(); + reject({ + code: constants_1.Status.RESOURCE_EXHAUSTED, + details: `Received message that decompresses to a size larger than ${this.maxRecvMessageLength}` + }); + } + }); + decompresser.on("end", () => { + resolve(Buffer.concat(messageParts)); + }); + decompresser.write(message); + decompresser.end(); + }); + } + }; + var GzipHandler = class extends CompressionHandler { + constructor(maxRecvMessageLength) { + super(); + this.maxRecvMessageLength = maxRecvMessageLength; + } + compressMessage(message) { + return new Promise((resolve, reject) => { + zlib.gzip(message, (err, output) => { + if (err) { + reject(err); + } else { + resolve(output); + } + }); + }); + } + decompressMessage(message) { + return new Promise((resolve, reject) => { + let totalLength = 0; + const messageParts = []; + const decompresser = zlib.createGunzip(); + decompresser.on("error", (error2) => { + reject({ + code: constants_1.Status.INTERNAL, + details: "Failed to decompress gzip-encoded message" + }); + }); + decompresser.on("data", (chunk) => { + messageParts.push(chunk); + totalLength += chunk.byteLength; + if (this.maxRecvMessageLength !== -1 && totalLength > this.maxRecvMessageLength) { + decompresser.destroy(); + reject({ + code: constants_1.Status.RESOURCE_EXHAUSTED, + details: `Received message that decompresses to a size larger than ${this.maxRecvMessageLength}` + }); + } + }); + decompresser.on("end", () => { + resolve(Buffer.concat(messageParts)); + }); + decompresser.write(message); + decompresser.end(); + }); + } + }; + var UnknownHandler = class extends CompressionHandler { + constructor(compressionName) { + super(); + this.compressionName = compressionName; + } + compressMessage(message) { + return Promise.reject(new Error(`Received message compressed with unsupported compression method ${this.compressionName}`)); + } + decompressMessage(message) { + return Promise.reject(new Error(`Compression method not supported: ${this.compressionName}`)); + } + }; + function getCompressionHandler(compressionName, maxReceiveMessageSize) { + switch (compressionName) { + case "identity": + return new IdentityHandler(); + case "deflate": + return new DeflateHandler(maxReceiveMessageSize); + case "gzip": + return new GzipHandler(maxReceiveMessageSize); + default: + return new UnknownHandler(compressionName); + } + } + var CompressionFilter = class extends filter_1.BaseFilter { + constructor(channelOptions, sharedFilterConfig) { + var _a, _b, _c; + super(); + this.sharedFilterConfig = sharedFilterConfig; + this.sendCompression = new IdentityHandler(); + this.receiveCompression = new IdentityHandler(); + this.currentCompressionAlgorithm = "identity"; + const compressionAlgorithmKey = channelOptions["grpc.default_compression_algorithm"]; + this.maxReceiveMessageLength = (_a = channelOptions["grpc.max_receive_message_length"]) !== null && _a !== void 0 ? _a : constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH; + this.maxSendMessageLength = (_b = channelOptions["grpc.max_send_message_length"]) !== null && _b !== void 0 ? _b : constants_1.DEFAULT_MAX_SEND_MESSAGE_LENGTH; + if (compressionAlgorithmKey !== void 0) { + if (isCompressionAlgorithmKey(compressionAlgorithmKey)) { + const clientSelectedEncoding = compression_algorithms_1.CompressionAlgorithms[compressionAlgorithmKey]; + const serverSupportedEncodings = (_c = sharedFilterConfig.serverSupportedEncodingHeader) === null || _c === void 0 ? void 0 : _c.split(","); + if (!serverSupportedEncodings || serverSupportedEncodings.includes(clientSelectedEncoding)) { + this.currentCompressionAlgorithm = clientSelectedEncoding; + this.sendCompression = getCompressionHandler(this.currentCompressionAlgorithm, -1); + } + } else { + logging.log(constants_1.LogVerbosity.ERROR, `Invalid value provided for grpc.default_compression_algorithm option: ${compressionAlgorithmKey}`); + } + } + } + async sendMetadata(metadata) { + const headers = await metadata; + headers.set("grpc-accept-encoding", "identity,deflate,gzip"); + headers.set("accept-encoding", "identity"); + if (this.currentCompressionAlgorithm === "identity") { + headers.remove("grpc-encoding"); + } else { + headers.set("grpc-encoding", this.currentCompressionAlgorithm); + } + return headers; + } + receiveMetadata(metadata) { + const receiveEncoding = metadata.get("grpc-encoding"); + if (receiveEncoding.length > 0) { + const encoding = receiveEncoding[0]; + if (typeof encoding === "string") { + this.receiveCompression = getCompressionHandler(encoding, this.maxReceiveMessageLength); + } + } + metadata.remove("grpc-encoding"); + const serverSupportedEncodingsHeader = metadata.get("grpc-accept-encoding")[0]; + if (serverSupportedEncodingsHeader) { + this.sharedFilterConfig.serverSupportedEncodingHeader = serverSupportedEncodingsHeader; + const serverSupportedEncodings = serverSupportedEncodingsHeader.split(","); + if (!serverSupportedEncodings.includes(this.currentCompressionAlgorithm)) { + this.sendCompression = new IdentityHandler(); + this.currentCompressionAlgorithm = "identity"; + } + } + metadata.remove("grpc-accept-encoding"); + return metadata; + } + async sendMessage(message) { + var _a; + const resolvedMessage = await message; + if (this.maxSendMessageLength !== -1 && resolvedMessage.message.length > this.maxSendMessageLength) { + throw { + code: constants_1.Status.RESOURCE_EXHAUSTED, + details: `Attempted to send message with a size larger than ${this.maxSendMessageLength}` + }; + } + let compress; + if (this.sendCompression instanceof IdentityHandler) { + compress = false; + } else { + compress = (((_a = resolvedMessage.flags) !== null && _a !== void 0 ? _a : 0) & 2) === 0; + } + return { + message: await this.sendCompression.writeMessage(resolvedMessage.message, compress), + flags: resolvedMessage.flags + }; + } + async receiveMessage(message) { + return this.receiveCompression.readMessage(await message); + } + }; + exports2.CompressionFilter = CompressionFilter; + var CompressionFilterFactory = class { + constructor(channel, options) { + this.options = options; + this.sharedFilterConfig = {}; + } + createFilter() { + return new CompressionFilter(this.options, this.sharedFilterConfig); + } + }; + exports2.CompressionFilterFactory = CompressionFilterFactory; + } +}); + +// node_modules/@grpc/grpc-js/build/src/control-plane-status.js +var require_control_plane_status = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/control-plane-status.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.restrictControlPlaneStatusCode = restrictControlPlaneStatusCode; + var constants_1 = require_constants7(); + var INAPPROPRIATE_CONTROL_PLANE_CODES = [ + constants_1.Status.OK, + constants_1.Status.INVALID_ARGUMENT, + constants_1.Status.NOT_FOUND, + constants_1.Status.ALREADY_EXISTS, + constants_1.Status.FAILED_PRECONDITION, + constants_1.Status.ABORTED, + constants_1.Status.OUT_OF_RANGE, + constants_1.Status.DATA_LOSS + ]; + function restrictControlPlaneStatusCode(code, details) { + if (INAPPROPRIATE_CONTROL_PLANE_CODES.includes(code)) { + return { + code: constants_1.Status.INTERNAL, + details: `Invalid status from control plane: ${code} ${constants_1.Status[code]} ${details}` + }; + } else { + return { code, details }; + } + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/deadline.js +var require_deadline = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/deadline.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.minDeadline = minDeadline; + exports2.getDeadlineTimeoutString = getDeadlineTimeoutString; + exports2.getRelativeTimeout = getRelativeTimeout; + exports2.deadlineToString = deadlineToString; + exports2.formatDateDifference = formatDateDifference; + function minDeadline(...deadlineList) { + let minValue = Infinity; + for (const deadline of deadlineList) { + const deadlineMsecs = deadline instanceof Date ? deadline.getTime() : deadline; + if (deadlineMsecs < minValue) { + minValue = deadlineMsecs; + } + } + return minValue; + } + var units = [ + ["m", 1], + ["S", 1e3], + ["M", 60 * 1e3], + ["H", 60 * 60 * 1e3] + ]; + function getDeadlineTimeoutString(deadline) { + const now = (/* @__PURE__ */ new Date()).getTime(); + if (deadline instanceof Date) { + deadline = deadline.getTime(); + } + const timeoutMs = Math.max(deadline - now, 0); + for (const [unit, factor] of units) { + const amount = timeoutMs / factor; + if (amount < 1e8) { + return String(Math.ceil(amount)) + unit; + } + } + throw new Error("Deadline is too far in the future"); + } + var MAX_TIMEOUT_TIME = 2147483647; + function getRelativeTimeout(deadline) { + const deadlineMs = deadline instanceof Date ? deadline.getTime() : deadline; + const now = (/* @__PURE__ */ new Date()).getTime(); + const timeout = deadlineMs - now; + if (timeout < 0) { + return 0; + } else if (timeout > MAX_TIMEOUT_TIME) { + return Infinity; + } else { + return timeout; + } + } + function deadlineToString(deadline) { + if (deadline instanceof Date) { + return deadline.toISOString(); + } else { + const dateDeadline = new Date(deadline); + if (Number.isNaN(dateDeadline.getTime())) { + return "" + deadline; + } else { + return dateDeadline.toISOString(); + } + } + } + function formatDateDifference(startDate, endDate) { + return ((endDate.getTime() - startDate.getTime()) / 1e3).toFixed(3) + "s"; + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/filter-stack.js +var require_filter_stack = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/filter-stack.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.FilterStackFactory = exports2.FilterStack = void 0; + var FilterStack = class { + constructor(filters) { + this.filters = filters; + } + sendMetadata(metadata) { + let result = metadata; + for (let i = 0; i < this.filters.length; i++) { + result = this.filters[i].sendMetadata(result); + } + return result; + } + receiveMetadata(metadata) { + let result = metadata; + for (let i = this.filters.length - 1; i >= 0; i--) { + result = this.filters[i].receiveMetadata(result); + } + return result; + } + sendMessage(message) { + let result = message; + for (let i = 0; i < this.filters.length; i++) { + result = this.filters[i].sendMessage(result); + } + return result; + } + receiveMessage(message) { + let result = message; + for (let i = this.filters.length - 1; i >= 0; i--) { + result = this.filters[i].receiveMessage(result); + } + return result; + } + receiveTrailers(status) { + let result = status; + for (let i = this.filters.length - 1; i >= 0; i--) { + result = this.filters[i].receiveTrailers(result); + } + return result; + } + push(filters) { + this.filters.unshift(...filters); + } + getFilters() { + return this.filters; + } + }; + exports2.FilterStack = FilterStack; + var FilterStackFactory = class _FilterStackFactory { + constructor(factories) { + this.factories = factories; + } + push(filterFactories) { + this.factories.unshift(...filterFactories); + } + clone() { + return new _FilterStackFactory([...this.factories]); + } + createFilter() { + return new FilterStack(this.factories.map((factory) => factory.createFilter())); + } + }; + exports2.FilterStackFactory = FilterStackFactory; + } +}); + +// node_modules/@grpc/grpc-js/build/src/single-subchannel-channel.js +var require_single_subchannel_channel = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/single-subchannel-channel.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.SingleSubchannelChannel = void 0; + var call_number_1 = require_call_number(); + var channelz_1 = require_channelz(); + var compression_filter_1 = require_compression_filter(); + var connectivity_state_1 = require_connectivity_state(); + var constants_1 = require_constants7(); + var control_plane_status_1 = require_control_plane_status(); + var deadline_1 = require_deadline(); + var filter_stack_1 = require_filter_stack(); + var metadata_1 = require_metadata(); + var resolver_1 = require_resolver(); + var uri_parser_1 = require_uri_parser(); + var SubchannelCallWrapper = class { + constructor(subchannel, method, filterStackFactory, options, callNumber) { + var _a, _b; + this.subchannel = subchannel; + this.method = method; + this.options = options; + this.callNumber = callNumber; + this.childCall = null; + this.pendingMessage = null; + this.readPending = false; + this.halfClosePending = false; + this.pendingStatus = null; + this.readFilterPending = false; + this.writeFilterPending = false; + const splitPath = this.method.split("/"); + let serviceName = ""; + if (splitPath.length >= 2) { + serviceName = splitPath[1]; + } + const hostname = (_b = (_a = (0, uri_parser_1.splitHostPort)(this.options.host)) === null || _a === void 0 ? void 0 : _a.host) !== null && _b !== void 0 ? _b : "localhost"; + this.serviceUrl = `https://${hostname}/${serviceName}`; + const timeout = (0, deadline_1.getRelativeTimeout)(options.deadline); + if (timeout !== Infinity) { + if (timeout <= 0) { + this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, "Deadline exceeded"); + } else { + setTimeout(() => { + this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, "Deadline exceeded"); + }, timeout); + } + } + this.filterStack = filterStackFactory.createFilter(); + } + cancelWithStatus(status, details) { + if (this.childCall) { + this.childCall.cancelWithStatus(status, details); + } else { + this.pendingStatus = { + code: status, + details, + metadata: new metadata_1.Metadata() + }; + } + } + getPeer() { + var _a, _b; + return (_b = (_a = this.childCall) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : this.subchannel.getAddress(); + } + async start(metadata, listener) { + if (this.pendingStatus) { + listener.onReceiveStatus(this.pendingStatus); + return; + } + if (this.subchannel.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) { + listener.onReceiveStatus({ + code: constants_1.Status.UNAVAILABLE, + details: "Subchannel not ready", + metadata: new metadata_1.Metadata() + }); + return; + } + const filteredMetadata = await this.filterStack.sendMetadata(Promise.resolve(metadata)); + let credsMetadata; + try { + credsMetadata = await this.subchannel.getCallCredentials().generateMetadata({ method_name: this.method, service_url: this.serviceUrl }); + } catch (e) { + const error2 = e; + const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(typeof error2.code === "number" ? error2.code : constants_1.Status.UNKNOWN, `Getting metadata from plugin failed with error: ${error2.message}`); + listener.onReceiveStatus({ + code, + details, + metadata: new metadata_1.Metadata() + }); + return; + } + credsMetadata.merge(filteredMetadata); + const childListener = { + onReceiveMetadata: async (metadata2) => { + listener.onReceiveMetadata(await this.filterStack.receiveMetadata(metadata2)); + }, + onReceiveMessage: async (message) => { + this.readFilterPending = true; + const filteredMessage = await this.filterStack.receiveMessage(message); + this.readFilterPending = false; + listener.onReceiveMessage(filteredMessage); + if (this.pendingStatus) { + listener.onReceiveStatus(this.pendingStatus); + } + }, + onReceiveStatus: async (status) => { + const filteredStatus = await this.filterStack.receiveTrailers(status); + if (this.readFilterPending) { + this.pendingStatus = filteredStatus; + } else { + listener.onReceiveStatus(filteredStatus); + } + } + }; + this.childCall = this.subchannel.createCall(credsMetadata, this.options.host, this.method, childListener); + if (this.readPending) { + this.childCall.startRead(); + } + if (this.pendingMessage) { + this.childCall.sendMessageWithContext(this.pendingMessage.context, this.pendingMessage.message); + } + if (this.halfClosePending && !this.writeFilterPending) { + this.childCall.halfClose(); + } + } + async sendMessageWithContext(context3, message) { + this.writeFilterPending = true; + const filteredMessage = await this.filterStack.sendMessage(Promise.resolve({ message, flags: context3.flags })); + this.writeFilterPending = false; + if (this.childCall) { + this.childCall.sendMessageWithContext(context3, filteredMessage.message); + if (this.halfClosePending) { + this.childCall.halfClose(); + } + } else { + this.pendingMessage = { context: context3, message: filteredMessage.message }; + } + } + startRead() { + if (this.childCall) { + this.childCall.startRead(); + } else { + this.readPending = true; + } + } + halfClose() { + if (this.childCall && !this.writeFilterPending) { + this.childCall.halfClose(); + } else { + this.halfClosePending = true; + } + } + getCallNumber() { + return this.callNumber; + } + setCredentials(credentials) { + throw new Error("Method not implemented."); + } + getAuthContext() { + if (this.childCall) { + return this.childCall.getAuthContext(); + } else { + return null; + } + } + }; + var SingleSubchannelChannel = class { + constructor(subchannel, target, options) { + this.subchannel = subchannel; + this.target = target; + this.channelzEnabled = false; + this.channelzTrace = new channelz_1.ChannelzTrace(); + this.callTracker = new channelz_1.ChannelzCallTracker(); + this.childrenTracker = new channelz_1.ChannelzChildrenTracker(); + this.channelzEnabled = options["grpc.enable_channelz"] !== 0; + this.channelzRef = (0, channelz_1.registerChannelzChannel)((0, uri_parser_1.uriToString)(target), () => ({ + target: `${(0, uri_parser_1.uriToString)(target)} (${subchannel.getAddress()})`, + state: this.subchannel.getConnectivityState(), + trace: this.channelzTrace, + callTracker: this.callTracker, + children: this.childrenTracker.getChildLists() + }), this.channelzEnabled); + if (this.channelzEnabled) { + this.childrenTracker.refChild(subchannel.getChannelzRef()); + } + this.filterStackFactory = new filter_stack_1.FilterStackFactory([new compression_filter_1.CompressionFilterFactory(this, options)]); + } + close() { + if (this.channelzEnabled) { + this.childrenTracker.unrefChild(this.subchannel.getChannelzRef()); + } + (0, channelz_1.unregisterChannelzRef)(this.channelzRef); + } + getTarget() { + return (0, uri_parser_1.uriToString)(this.target); + } + getConnectivityState(tryToConnect) { + throw new Error("Method not implemented."); + } + watchConnectivityState(currentState, deadline, callback) { + throw new Error("Method not implemented."); + } + getChannelzRef() { + return this.channelzRef; + } + createCall(method, deadline) { + const callOptions = { + deadline, + host: (0, resolver_1.getDefaultAuthority)(this.target), + flags: constants_1.Propagate.DEFAULTS, + parentCall: null + }; + return new SubchannelCallWrapper(this.subchannel, method, this.filterStackFactory, callOptions, (0, call_number_1.getNextCallNumber)()); + } + }; + exports2.SingleSubchannelChannel = SingleSubchannelChannel; + } +}); + +// node_modules/@grpc/grpc-js/build/src/subchannel.js +var require_subchannel = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/subchannel.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Subchannel = void 0; + var connectivity_state_1 = require_connectivity_state(); + var backoff_timeout_1 = require_backoff_timeout(); + var logging = require_logging(); + var constants_1 = require_constants7(); + var uri_parser_1 = require_uri_parser(); + var subchannel_address_1 = require_subchannel_address(); + var channelz_1 = require_channelz(); + var single_subchannel_channel_1 = require_single_subchannel_channel(); + var TRACER_NAME = "subchannel"; + var KEEPALIVE_MAX_TIME_MS = ~(1 << 31); + var Subchannel = class { + /** + * A class representing a connection to a single backend. + * @param channelTarget The target string for the channel as a whole + * @param subchannelAddress The address for the backend that this subchannel + * will connect to + * @param options The channel options, plus any specific subchannel options + * for this subchannel + * @param credentials The channel credentials used to establish this + * connection + */ + constructor(channelTarget, subchannelAddress, options, credentials, connector) { + var _a; + this.channelTarget = channelTarget; + this.subchannelAddress = subchannelAddress; + this.options = options; + this.connector = connector; + this.connectivityState = connectivity_state_1.ConnectivityState.IDLE; + this.transport = null; + this.continueConnecting = false; + this.stateListeners = /* @__PURE__ */ new Set(); + this.refcount = 0; + this.channelzEnabled = true; + this.dataProducers = /* @__PURE__ */ new Map(); + this.subchannelChannel = null; + const backoffOptions = { + initialDelay: options["grpc.initial_reconnect_backoff_ms"], + maxDelay: options["grpc.max_reconnect_backoff_ms"] + }; + this.backoffTimeout = new backoff_timeout_1.BackoffTimeout(() => { + this.handleBackoffTimer(); + }, backoffOptions); + this.backoffTimeout.unref(); + this.subchannelAddressString = (0, subchannel_address_1.subchannelAddressToString)(subchannelAddress); + this.keepaliveTime = (_a = options["grpc.keepalive_time_ms"]) !== null && _a !== void 0 ? _a : -1; + if (options["grpc.enable_channelz"] === 0) { + this.channelzEnabled = false; + this.channelzTrace = new channelz_1.ChannelzTraceStub(); + this.callTracker = new channelz_1.ChannelzCallTrackerStub(); + this.childrenTracker = new channelz_1.ChannelzChildrenTrackerStub(); + this.streamTracker = new channelz_1.ChannelzCallTrackerStub(); + } else { + this.channelzTrace = new channelz_1.ChannelzTrace(); + this.callTracker = new channelz_1.ChannelzCallTracker(); + this.childrenTracker = new channelz_1.ChannelzChildrenTracker(); + this.streamTracker = new channelz_1.ChannelzCallTracker(); + } + this.channelzRef = (0, channelz_1.registerChannelzSubchannel)(this.subchannelAddressString, () => this.getChannelzInfo(), this.channelzEnabled); + this.channelzTrace.addTrace("CT_INFO", "Subchannel created"); + this.trace("Subchannel constructed with options " + JSON.stringify(options, void 0, 2)); + this.secureConnector = credentials._createSecureConnector(channelTarget, options); + } + getChannelzInfo() { + return { + state: this.connectivityState, + trace: this.channelzTrace, + callTracker: this.callTracker, + children: this.childrenTracker.getChildLists(), + target: this.subchannelAddressString + }; + } + trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + } + refTrace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, "subchannel_refcount", "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + } + handleBackoffTimer() { + if (this.continueConnecting) { + this.transitionToState([connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE], connectivity_state_1.ConnectivityState.CONNECTING); + } else { + this.transitionToState([connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE], connectivity_state_1.ConnectivityState.IDLE); + } + } + /** + * Start a backoff timer with the current nextBackoff timeout + */ + startBackoff() { + this.backoffTimeout.runOnce(); + } + stopBackoff() { + this.backoffTimeout.stop(); + this.backoffTimeout.reset(); + } + startConnectingInternal() { + let options = this.options; + if (options["grpc.keepalive_time_ms"]) { + const adjustedKeepaliveTime = Math.min(this.keepaliveTime, KEEPALIVE_MAX_TIME_MS); + options = Object.assign(Object.assign({}, options), { "grpc.keepalive_time_ms": adjustedKeepaliveTime }); + } + this.connector.connect(this.subchannelAddress, this.secureConnector, options).then((transport) => { + if (this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING], connectivity_state_1.ConnectivityState.READY)) { + this.transport = transport; + if (this.channelzEnabled) { + this.childrenTracker.refChild(transport.getChannelzRef()); + } + transport.addDisconnectListener((tooManyPings) => { + this.transitionToState([connectivity_state_1.ConnectivityState.READY], connectivity_state_1.ConnectivityState.IDLE); + if (tooManyPings && this.keepaliveTime > 0) { + this.keepaliveTime *= 2; + logging.log(constants_1.LogVerbosity.ERROR, `Connection to ${(0, uri_parser_1.uriToString)(this.channelTarget)} at ${this.subchannelAddressString} rejected by server because of excess pings. Increasing ping interval to ${this.keepaliveTime} ms`); + } + }); + } else { + transport.shutdown(); + } + }, (error2) => { + this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING], connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, `${error2}`); + }); + } + /** + * Initiate a state transition from any element of oldStates to the new + * state. If the current connectivityState is not in oldStates, do nothing. + * @param oldStates The set of states to transition from + * @param newState The state to transition to + * @returns True if the state changed, false otherwise + */ + transitionToState(oldStates, newState, errorMessage) { + var _a, _b; + if (oldStates.indexOf(this.connectivityState) === -1) { + return false; + } + if (errorMessage) { + this.trace(connectivity_state_1.ConnectivityState[this.connectivityState] + " -> " + connectivity_state_1.ConnectivityState[newState] + ' with error "' + errorMessage + '"'); + } else { + this.trace(connectivity_state_1.ConnectivityState[this.connectivityState] + " -> " + connectivity_state_1.ConnectivityState[newState]); + } + if (this.channelzEnabled) { + this.channelzTrace.addTrace("CT_INFO", "Connectivity state change to " + connectivity_state_1.ConnectivityState[newState]); + } + const previousState = this.connectivityState; + this.connectivityState = newState; + switch (newState) { + case connectivity_state_1.ConnectivityState.READY: + this.stopBackoff(); + break; + case connectivity_state_1.ConnectivityState.CONNECTING: + this.startBackoff(); + this.startConnectingInternal(); + this.continueConnecting = false; + break; + case connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE: + if (this.channelzEnabled && this.transport) { + this.childrenTracker.unrefChild(this.transport.getChannelzRef()); + } + (_a = this.transport) === null || _a === void 0 ? void 0 : _a.shutdown(); + this.transport = null; + if (!this.backoffTimeout.isRunning()) { + process.nextTick(() => { + this.handleBackoffTimer(); + }); + } + break; + case connectivity_state_1.ConnectivityState.IDLE: + if (this.channelzEnabled && this.transport) { + this.childrenTracker.unrefChild(this.transport.getChannelzRef()); + } + (_b = this.transport) === null || _b === void 0 ? void 0 : _b.shutdown(); + this.transport = null; + break; + default: + throw new Error(`Invalid state: unknown ConnectivityState ${newState}`); + } + for (const listener of this.stateListeners) { + listener(this, previousState, newState, this.keepaliveTime, errorMessage); + } + return true; + } + ref() { + this.refTrace("refcount " + this.refcount + " -> " + (this.refcount + 1)); + this.refcount += 1; + } + unref() { + this.refTrace("refcount " + this.refcount + " -> " + (this.refcount - 1)); + this.refcount -= 1; + if (this.refcount === 0) { + this.channelzTrace.addTrace("CT_INFO", "Shutting down"); + (0, channelz_1.unregisterChannelzRef)(this.channelzRef); + this.secureConnector.destroy(); + process.nextTick(() => { + this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING, connectivity_state_1.ConnectivityState.READY], connectivity_state_1.ConnectivityState.IDLE); + }); + } + } + unrefIfOneRef() { + if (this.refcount === 1) { + this.unref(); + return true; + } + return false; + } + createCall(metadata, host, method, listener) { + if (!this.transport) { + throw new Error("Cannot create call, subchannel not READY"); + } + let statsTracker; + if (this.channelzEnabled) { + this.callTracker.addCallStarted(); + this.streamTracker.addCallStarted(); + statsTracker = { + onCallEnd: (status) => { + if (status.code === constants_1.Status.OK) { + this.callTracker.addCallSucceeded(); + } else { + this.callTracker.addCallFailed(); + } + } + }; + } else { + statsTracker = {}; + } + return this.transport.createCall(metadata, host, method, listener, statsTracker); + } + /** + * If the subchannel is currently IDLE, start connecting and switch to the + * CONNECTING state. If the subchannel is current in TRANSIENT_FAILURE, + * the next time it would transition to IDLE, start connecting again instead. + * Otherwise, do nothing. + */ + startConnecting() { + process.nextTick(() => { + if (!this.transitionToState([connectivity_state_1.ConnectivityState.IDLE], connectivity_state_1.ConnectivityState.CONNECTING)) { + if (this.connectivityState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { + this.continueConnecting = true; + } + } + }); + } + /** + * Get the subchannel's current connectivity state. + */ + getConnectivityState() { + return this.connectivityState; + } + /** + * Add a listener function to be called whenever the subchannel's + * connectivity state changes. + * @param listener + */ + addConnectivityStateListener(listener) { + this.stateListeners.add(listener); + } + /** + * Remove a listener previously added with `addConnectivityStateListener` + * @param listener A reference to a function previously passed to + * `addConnectivityStateListener` + */ + removeConnectivityStateListener(listener) { + this.stateListeners.delete(listener); + } + /** + * Reset the backoff timeout, and immediately start connecting if in backoff. + */ + resetBackoff() { + process.nextTick(() => { + this.backoffTimeout.reset(); + this.transitionToState([connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE], connectivity_state_1.ConnectivityState.CONNECTING); + }); + } + getAddress() { + return this.subchannelAddressString; + } + getChannelzRef() { + return this.channelzRef; + } + isHealthy() { + return true; + } + addHealthStateWatcher(listener) { + } + removeHealthStateWatcher(listener) { + } + getRealSubchannel() { + return this; + } + realSubchannelEquals(other) { + return other.getRealSubchannel() === this; + } + throttleKeepalive(newKeepaliveTime) { + if (newKeepaliveTime > this.keepaliveTime) { + this.keepaliveTime = newKeepaliveTime; + } + } + getCallCredentials() { + return this.secureConnector.getCallCredentials(); + } + getChannel() { + if (!this.subchannelChannel) { + this.subchannelChannel = new single_subchannel_channel_1.SingleSubchannelChannel(this, this.channelTarget, this.options); + } + return this.subchannelChannel; + } + addDataWatcher(dataWatcher) { + throw new Error("Not implemented"); + } + getOrCreateDataProducer(name, createDataProducer) { + const existingProducer = this.dataProducers.get(name); + if (existingProducer) { + return existingProducer; + } + const newProducer = createDataProducer(this); + this.dataProducers.set(name, newProducer); + return newProducer; + } + removeDataProducer(name) { + this.dataProducers.delete(name); + } + }; + exports2.Subchannel = Subchannel; + } +}); + +// node_modules/@grpc/grpc-js/build/src/environment.js +var require_environment = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/environment.js"(exports2) { + "use strict"; + var _a; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.GRPC_NODE_USE_ALTERNATIVE_RESOLVER = void 0; + exports2.GRPC_NODE_USE_ALTERNATIVE_RESOLVER = ((_a = process.env.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) !== null && _a !== void 0 ? _a : "false") === "true"; + } +}); + +// node_modules/@grpc/grpc-js/build/src/resolver-dns.js +var require_resolver_dns = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/resolver-dns.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DEFAULT_PORT = void 0; + exports2.setup = setup; + var resolver_1 = require_resolver(); + var dns_1 = require("dns"); + var service_config_1 = require_service_config(); + var constants_1 = require_constants7(); + var call_interface_1 = require_call_interface(); + var metadata_1 = require_metadata(); + var logging = require_logging(); + var constants_2 = require_constants7(); + var uri_parser_1 = require_uri_parser(); + var net_1 = require("net"); + var backoff_timeout_1 = require_backoff_timeout(); + var environment_1 = require_environment(); + var TRACER_NAME = "dns_resolver"; + function trace(text) { + logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, text); + } + exports2.DEFAULT_PORT = 443; + var DEFAULT_MIN_TIME_BETWEEN_RESOLUTIONS_MS = 3e4; + var DnsResolver = class { + constructor(target, listener, channelOptions) { + var _a, _b, _c; + this.target = target; + this.listener = listener; + this.pendingLookupPromise = null; + this.pendingTxtPromise = null; + this.latestLookupResult = null; + this.latestServiceConfigResult = null; + this.continueResolving = false; + this.isNextResolutionTimerRunning = false; + this.isServiceConfigEnabled = true; + this.returnedIpResult = false; + this.alternativeResolver = new dns_1.promises.Resolver(); + trace("Resolver constructed for target " + (0, uri_parser_1.uriToString)(target)); + if (target.authority) { + this.alternativeResolver.setServers([target.authority]); + } + const hostPort = (0, uri_parser_1.splitHostPort)(target.path); + if (hostPort === null) { + this.ipResult = null; + this.dnsHostname = null; + this.port = null; + } else { + if ((0, net_1.isIPv4)(hostPort.host) || (0, net_1.isIPv6)(hostPort.host)) { + this.ipResult = [ + { + addresses: [ + { + host: hostPort.host, + port: (_a = hostPort.port) !== null && _a !== void 0 ? _a : exports2.DEFAULT_PORT + } + ] + } + ]; + this.dnsHostname = null; + this.port = null; + } else { + this.ipResult = null; + this.dnsHostname = hostPort.host; + this.port = (_b = hostPort.port) !== null && _b !== void 0 ? _b : exports2.DEFAULT_PORT; + } + } + this.percentage = Math.random() * 100; + if (channelOptions["grpc.service_config_disable_resolution"] === 1) { + this.isServiceConfigEnabled = false; + } + this.defaultResolutionError = { + code: constants_1.Status.UNAVAILABLE, + details: `Name resolution failed for target ${(0, uri_parser_1.uriToString)(this.target)}`, + metadata: new metadata_1.Metadata() + }; + const backoffOptions = { + initialDelay: channelOptions["grpc.initial_reconnect_backoff_ms"], + maxDelay: channelOptions["grpc.max_reconnect_backoff_ms"] + }; + this.backoff = new backoff_timeout_1.BackoffTimeout(() => { + if (this.continueResolving) { + this.startResolutionWithBackoff(); + } + }, backoffOptions); + this.backoff.unref(); + this.minTimeBetweenResolutionsMs = (_c = channelOptions["grpc.dns_min_time_between_resolutions_ms"]) !== null && _c !== void 0 ? _c : DEFAULT_MIN_TIME_BETWEEN_RESOLUTIONS_MS; + this.nextResolutionTimer = setTimeout(() => { + }, 0); + clearTimeout(this.nextResolutionTimer); + } + /** + * If the target is an IP address, just provide that address as a result. + * Otherwise, initiate A, AAAA, and TXT lookups + */ + startResolution() { + if (this.ipResult !== null) { + if (!this.returnedIpResult) { + trace("Returning IP address for target " + (0, uri_parser_1.uriToString)(this.target)); + setImmediate(() => { + this.listener((0, call_interface_1.statusOrFromValue)(this.ipResult), {}, null, ""); + }); + this.returnedIpResult = true; + } + this.backoff.stop(); + this.backoff.reset(); + this.stopNextResolutionTimer(); + return; + } + if (this.dnsHostname === null) { + trace("Failed to parse DNS address " + (0, uri_parser_1.uriToString)(this.target)); + setImmediate(() => { + this.listener((0, call_interface_1.statusOrFromError)({ + code: constants_1.Status.UNAVAILABLE, + details: `Failed to parse DNS address ${(0, uri_parser_1.uriToString)(this.target)}` + }), {}, null, ""); + }); + this.stopNextResolutionTimer(); + } else { + if (this.pendingLookupPromise !== null) { + return; + } + trace("Looking up DNS hostname " + this.dnsHostname); + this.latestLookupResult = null; + const hostname = this.dnsHostname; + this.pendingLookupPromise = this.lookup(hostname); + this.pendingLookupPromise.then((addressList) => { + if (this.pendingLookupPromise === null) { + return; + } + this.pendingLookupPromise = null; + this.latestLookupResult = (0, call_interface_1.statusOrFromValue)(addressList.map((address) => ({ + addresses: [address] + }))); + const allAddressesString = "[" + addressList.map((addr) => addr.host + ":" + addr.port).join(",") + "]"; + trace("Resolved addresses for target " + (0, uri_parser_1.uriToString)(this.target) + ": " + allAddressesString); + const healthStatus = this.listener(this.latestLookupResult, {}, this.latestServiceConfigResult, ""); + this.handleHealthStatus(healthStatus); + }, (err) => { + if (this.pendingLookupPromise === null) { + return; + } + trace("Resolution error for target " + (0, uri_parser_1.uriToString)(this.target) + ": " + err.message); + this.pendingLookupPromise = null; + this.stopNextResolutionTimer(); + this.listener((0, call_interface_1.statusOrFromError)(this.defaultResolutionError), {}, this.latestServiceConfigResult, ""); + }); + if (this.isServiceConfigEnabled && this.pendingTxtPromise === null) { + this.pendingTxtPromise = this.resolveTxt(hostname); + this.pendingTxtPromise.then((txtRecord) => { + if (this.pendingTxtPromise === null) { + return; + } + this.pendingTxtPromise = null; + let serviceConfig; + try { + serviceConfig = (0, service_config_1.extractAndSelectServiceConfig)(txtRecord, this.percentage); + if (serviceConfig) { + this.latestServiceConfigResult = (0, call_interface_1.statusOrFromValue)(serviceConfig); + } else { + this.latestServiceConfigResult = null; + } + } catch (err) { + this.latestServiceConfigResult = (0, call_interface_1.statusOrFromError)({ + code: constants_1.Status.UNAVAILABLE, + details: `Parsing service config failed with error ${err.message}` + }); + } + if (this.latestLookupResult !== null) { + this.listener(this.latestLookupResult, {}, this.latestServiceConfigResult, ""); + } + }, (err) => { + }); + } + } + } + /** + * The ResolverListener returns a boolean indicating whether the LB policy + * accepted the resolution result. A false result on an otherwise successful + * resolution should be treated as a resolution failure. + * @param healthStatus + */ + handleHealthStatus(healthStatus) { + if (healthStatus) { + this.backoff.stop(); + this.backoff.reset(); + } else { + this.continueResolving = true; + } + } + async lookup(hostname) { + if (environment_1.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) { + trace("Using alternative DNS resolver."); + const records = await Promise.allSettled([ + this.alternativeResolver.resolve4(hostname), + this.alternativeResolver.resolve6(hostname) + ]); + if (records.every((result) => result.status === "rejected")) { + throw new Error(records[0].reason); + } + return records.reduce((acc, result) => { + return result.status === "fulfilled" ? [...acc, ...result.value] : acc; + }, []).map((addr) => ({ + host: addr, + port: +this.port + })); + } + const addressList = await dns_1.promises.lookup(hostname, { all: true }); + return addressList.map((addr) => ({ host: addr.address, port: +this.port })); + } + async resolveTxt(hostname) { + if (environment_1.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) { + trace("Using alternative DNS resolver."); + return this.alternativeResolver.resolveTxt(hostname); + } + return dns_1.promises.resolveTxt(hostname); + } + startNextResolutionTimer() { + var _a, _b; + clearTimeout(this.nextResolutionTimer); + this.nextResolutionTimer = setTimeout(() => { + this.stopNextResolutionTimer(); + if (this.continueResolving) { + this.startResolutionWithBackoff(); + } + }, this.minTimeBetweenResolutionsMs); + (_b = (_a = this.nextResolutionTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); + this.isNextResolutionTimerRunning = true; + } + stopNextResolutionTimer() { + clearTimeout(this.nextResolutionTimer); + this.isNextResolutionTimerRunning = false; + } + startResolutionWithBackoff() { + if (this.pendingLookupPromise === null) { + this.continueResolving = false; + this.backoff.runOnce(); + this.startNextResolutionTimer(); + this.startResolution(); + } + } + updateResolution() { + if (this.pendingLookupPromise === null) { + if (this.isNextResolutionTimerRunning || this.backoff.isRunning()) { + if (this.isNextResolutionTimerRunning) { + trace('resolution update delayed by "min time between resolutions" rate limit'); + } else { + trace("resolution update delayed by backoff timer until " + this.backoff.getEndTime().toISOString()); + } + this.continueResolving = true; + } else { + this.startResolutionWithBackoff(); + } + } + } + /** + * Reset the resolver to the same state it had when it was created. In-flight + * DNS requests cannot be cancelled, but they are discarded and their results + * will be ignored. + */ + destroy() { + this.continueResolving = false; + this.backoff.reset(); + this.backoff.stop(); + this.stopNextResolutionTimer(); + this.pendingLookupPromise = null; + this.pendingTxtPromise = null; + this.latestLookupResult = null; + this.latestServiceConfigResult = null; + this.returnedIpResult = false; + } + /** + * Get the default authority for the given target. For IP targets, that is + * the IP address. For DNS targets, it is the hostname. + * @param target + */ + static getDefaultAuthority(target) { + return target.path; + } + }; + function setup() { + (0, resolver_1.registerResolver)("dns", DnsResolver); + (0, resolver_1.registerDefaultScheme)("dns"); + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/http_proxy.js +var require_http_proxy = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/http_proxy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.parseCIDR = parseCIDR; + exports2.mapProxyName = mapProxyName; + exports2.getProxiedConnection = getProxiedConnection; + var logging_1 = require_logging(); + var constants_1 = require_constants7(); + var net_1 = require("net"); + var http2 = require("http"); + var logging = require_logging(); + var subchannel_address_1 = require_subchannel_address(); + var uri_parser_1 = require_uri_parser(); + var url_1 = require("url"); + var resolver_dns_1 = require_resolver_dns(); + var TRACER_NAME = "proxy"; + function trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); + } + function getProxyInfo() { + let proxyEnv = ""; + let envVar = ""; + if (process.env.grpc_proxy) { + envVar = "grpc_proxy"; + proxyEnv = process.env.grpc_proxy; + } else if (process.env.https_proxy) { + envVar = "https_proxy"; + proxyEnv = process.env.https_proxy; + } else if (process.env.http_proxy) { + envVar = "http_proxy"; + proxyEnv = process.env.http_proxy; + } else { + return {}; + } + let proxyUrl; + try { + proxyUrl = new url_1.URL(proxyEnv); + } catch (e) { + (0, logging_1.log)(constants_1.LogVerbosity.ERROR, `cannot parse value of "${envVar}" env var`); + return {}; + } + if (proxyUrl.protocol !== "http:") { + (0, logging_1.log)(constants_1.LogVerbosity.ERROR, `"${proxyUrl.protocol}" scheme not supported in proxy URI`); + return {}; + } + let userCred = null; + if (proxyUrl.username) { + if (proxyUrl.password) { + (0, logging_1.log)(constants_1.LogVerbosity.INFO, "userinfo found in proxy URI"); + userCred = decodeURIComponent(`${proxyUrl.username}:${proxyUrl.password}`); + } else { + userCred = proxyUrl.username; + } + } + const hostname = proxyUrl.hostname; + let port = proxyUrl.port; + if (port === "") { + port = "80"; + } + const result = { + address: `${hostname}:${port}` + }; + if (userCred) { + result.creds = userCred; + } + trace("Proxy server " + result.address + " set by environment variable " + envVar); + return result; + } + function getNoProxyHostList() { + let noProxyStr = process.env.no_grpc_proxy; + let envVar = "no_grpc_proxy"; + if (!noProxyStr) { + noProxyStr = process.env.no_proxy; + envVar = "no_proxy"; + } + if (noProxyStr) { + trace("No proxy server list set by environment variable " + envVar); + return noProxyStr.split(","); + } else { + return []; + } + } + function parseCIDR(cidrString) { + const splitRange = cidrString.split("/"); + if (splitRange.length !== 2) { + return null; + } + const prefixLength = parseInt(splitRange[1], 10); + if (!(0, net_1.isIPv4)(splitRange[0]) || Number.isNaN(prefixLength) || prefixLength < 0 || prefixLength > 32) { + return null; + } + return { + ip: ipToInt(splitRange[0]), + prefixLength + }; + } + function ipToInt(ip) { + return ip.split(".").reduce((acc, octet) => (acc << 8) + parseInt(octet, 10), 0); + } + function isIpInCIDR(cidr, serverHost) { + const ip = cidr.ip; + const mask = -1 << 32 - cidr.prefixLength; + const hostIP = ipToInt(serverHost); + return (hostIP & mask) === (ip & mask); + } + function hostMatchesNoProxyList(serverHost) { + for (const host of getNoProxyHostList()) { + const parsedCIDR = parseCIDR(host); + if ((0, net_1.isIPv4)(serverHost) && parsedCIDR && isIpInCIDR(parsedCIDR, serverHost)) { + return true; + } else if (serverHost.endsWith(host)) { + return true; + } + } + return false; + } + function mapProxyName(target, options) { + var _a; + const noProxyResult = { + target, + extraOptions: {} + }; + if (((_a = options["grpc.enable_http_proxy"]) !== null && _a !== void 0 ? _a : 1) === 0) { + return noProxyResult; + } + if (target.scheme === "unix") { + return noProxyResult; + } + const proxyInfo = getProxyInfo(); + if (!proxyInfo.address) { + return noProxyResult; + } + const hostPort = (0, uri_parser_1.splitHostPort)(target.path); + if (!hostPort) { + return noProxyResult; + } + const serverHost = hostPort.host; + if (hostMatchesNoProxyList(serverHost)) { + trace("Not using proxy for target in no_proxy list: " + (0, uri_parser_1.uriToString)(target)); + return noProxyResult; + } + const extraOptions = { + "grpc.http_connect_target": (0, uri_parser_1.uriToString)(target) + }; + if (proxyInfo.creds) { + extraOptions["grpc.http_connect_creds"] = proxyInfo.creds; + } + return { + target: { + scheme: "dns", + path: proxyInfo.address + }, + extraOptions + }; + } + function getProxiedConnection(address, channelOptions) { + var _a; + if (!("grpc.http_connect_target" in channelOptions)) { + return Promise.resolve(null); + } + const realTarget = channelOptions["grpc.http_connect_target"]; + const parsedTarget = (0, uri_parser_1.parseUri)(realTarget); + if (parsedTarget === null) { + return Promise.resolve(null); + } + const splitHostPost = (0, uri_parser_1.splitHostPort)(parsedTarget.path); + if (splitHostPost === null) { + return Promise.resolve(null); + } + const hostPort = `${splitHostPost.host}:${(_a = splitHostPost.port) !== null && _a !== void 0 ? _a : resolver_dns_1.DEFAULT_PORT}`; + const options = { + method: "CONNECT", + path: hostPort + }; + const headers = { + Host: hostPort + }; + if ((0, subchannel_address_1.isTcpSubchannelAddress)(address)) { + options.host = address.host; + options.port = address.port; + } else { + options.socketPath = address.path; + } + if ("grpc.http_connect_creds" in channelOptions) { + headers["Proxy-Authorization"] = "Basic " + Buffer.from(channelOptions["grpc.http_connect_creds"]).toString("base64"); + } + options.headers = headers; + const proxyAddressString = (0, subchannel_address_1.subchannelAddressToString)(address); + trace("Using proxy " + proxyAddressString + " to connect to " + options.path); + return new Promise((resolve, reject) => { + const request2 = http2.request(options); + request2.once("connect", (res, socket, head) => { + request2.removeAllListeners(); + socket.removeAllListeners(); + if (res.statusCode === 200) { + trace("Successfully connected to " + options.path + " through proxy " + proxyAddressString); + if (head.length > 0) { + socket.unshift(head); + } + trace("Successfully established a plaintext connection to " + options.path + " through proxy " + proxyAddressString); + resolve(socket); + } else { + (0, logging_1.log)(constants_1.LogVerbosity.ERROR, "Failed to connect to " + options.path + " through proxy " + proxyAddressString + " with status " + res.statusCode); + reject(); + } + }); + request2.once("error", (err) => { + request2.removeAllListeners(); + (0, logging_1.log)(constants_1.LogVerbosity.ERROR, "Failed to connect to proxy " + proxyAddressString + " with error " + err.message); + reject(); + }); + request2.end(); + }); + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/stream-decoder.js +var require_stream_decoder = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/stream-decoder.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.StreamDecoder = void 0; + var ReadState; + (function(ReadState2) { + ReadState2[ReadState2["NO_DATA"] = 0] = "NO_DATA"; + ReadState2[ReadState2["READING_SIZE"] = 1] = "READING_SIZE"; + ReadState2[ReadState2["READING_MESSAGE"] = 2] = "READING_MESSAGE"; + })(ReadState || (ReadState = {})); + var StreamDecoder = class { + constructor(maxReadMessageLength) { + this.maxReadMessageLength = maxReadMessageLength; + this.readState = ReadState.NO_DATA; + this.readCompressFlag = Buffer.alloc(1); + this.readPartialSize = Buffer.alloc(4); + this.readSizeRemaining = 4; + this.readMessageSize = 0; + this.readPartialMessage = []; + this.readMessageRemaining = 0; + } + write(data) { + let readHead = 0; + let toRead; + const result = []; + while (readHead < data.length) { + switch (this.readState) { + case ReadState.NO_DATA: + this.readCompressFlag = data.slice(readHead, readHead + 1); + readHead += 1; + this.readState = ReadState.READING_SIZE; + this.readPartialSize.fill(0); + this.readSizeRemaining = 4; + this.readMessageSize = 0; + this.readMessageRemaining = 0; + this.readPartialMessage = []; + break; + case ReadState.READING_SIZE: + toRead = Math.min(data.length - readHead, this.readSizeRemaining); + data.copy(this.readPartialSize, 4 - this.readSizeRemaining, readHead, readHead + toRead); + this.readSizeRemaining -= toRead; + readHead += toRead; + if (this.readSizeRemaining === 0) { + this.readMessageSize = this.readPartialSize.readUInt32BE(0); + if (this.maxReadMessageLength !== -1 && this.readMessageSize > this.maxReadMessageLength) { + throw new Error(`Received message larger than max (${this.readMessageSize} vs ${this.maxReadMessageLength})`); + } + this.readMessageRemaining = this.readMessageSize; + if (this.readMessageRemaining > 0) { + this.readState = ReadState.READING_MESSAGE; + } else { + const message = Buffer.concat([this.readCompressFlag, this.readPartialSize], 5); + this.readState = ReadState.NO_DATA; + result.push(message); + } + } + break; + case ReadState.READING_MESSAGE: + toRead = Math.min(data.length - readHead, this.readMessageRemaining); + this.readPartialMessage.push(data.slice(readHead, readHead + toRead)); + this.readMessageRemaining -= toRead; + readHead += toRead; + if (this.readMessageRemaining === 0) { + const framedMessageBuffers = [ + this.readCompressFlag, + this.readPartialSize + ].concat(this.readPartialMessage); + const framedMessage = Buffer.concat(framedMessageBuffers, this.readMessageSize + 5); + this.readState = ReadState.NO_DATA; + result.push(framedMessage); + } + break; + default: + throw new Error("Unexpected read state"); + } + } + return result; + } + }; + exports2.StreamDecoder = StreamDecoder; + } +}); + +// node_modules/@grpc/grpc-js/build/src/subchannel-call.js +var require_subchannel_call = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/subchannel-call.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Http2SubchannelCall = void 0; + var http2 = require("http2"); + var os4 = require("os"); + var constants_1 = require_constants7(); + var metadata_1 = require_metadata(); + var stream_decoder_1 = require_stream_decoder(); + var logging = require_logging(); + var constants_2 = require_constants7(); + var TRACER_NAME = "subchannel_call"; + function getSystemErrorName(errno) { + for (const [name, num] of Object.entries(os4.constants.errno)) { + if (num === errno) { + return name; + } + } + return "Unknown system error " + errno; + } + function mapHttpStatusCode(code) { + const details = `Received HTTP status code ${code}`; + let mappedStatusCode; + switch (code) { + // TODO(murgatroid99): handle 100 and 101 + case 400: + mappedStatusCode = constants_1.Status.INTERNAL; + break; + case 401: + mappedStatusCode = constants_1.Status.UNAUTHENTICATED; + break; + case 403: + mappedStatusCode = constants_1.Status.PERMISSION_DENIED; + break; + case 404: + mappedStatusCode = constants_1.Status.UNIMPLEMENTED; + break; + case 429: + case 502: + case 503: + case 504: + mappedStatusCode = constants_1.Status.UNAVAILABLE; + break; + default: + mappedStatusCode = constants_1.Status.UNKNOWN; + } + return { + code: mappedStatusCode, + details, + metadata: new metadata_1.Metadata() + }; + } + var Http2SubchannelCall = class { + constructor(http2Stream, callEventTracker, listener, transport, callId) { + var _a; + this.http2Stream = http2Stream; + this.callEventTracker = callEventTracker; + this.listener = listener; + this.transport = transport; + this.callId = callId; + this.isReadFilterPending = false; + this.isPushPending = false; + this.canPush = false; + this.readsClosed = false; + this.statusOutput = false; + this.unpushedReadMessages = []; + this.finalStatus = null; + this.internalError = null; + this.serverEndedCall = false; + this.connectionDropped = false; + const maxReceiveMessageLength = (_a = transport.getOptions()["grpc.max_receive_message_length"]) !== null && _a !== void 0 ? _a : constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH; + this.decoder = new stream_decoder_1.StreamDecoder(maxReceiveMessageLength); + http2Stream.on("response", (headers, flags) => { + let headersString = ""; + for (const header of Object.keys(headers)) { + headersString += " " + header + ": " + headers[header] + "\n"; + } + this.trace("Received server headers:\n" + headersString); + this.httpStatusCode = headers[":status"]; + if (flags & http2.constants.NGHTTP2_FLAG_END_STREAM) { + this.handleTrailers(headers); + } else { + let metadata; + try { + metadata = metadata_1.Metadata.fromHttp2Headers(headers); + } catch (error2) { + this.endCall({ + code: constants_1.Status.UNKNOWN, + details: error2.message, + metadata: new metadata_1.Metadata() + }); + return; + } + this.listener.onReceiveMetadata(metadata); + } + }); + http2Stream.on("trailers", (headers) => { + this.handleTrailers(headers); + }); + http2Stream.on("data", (data) => { + if (this.statusOutput) { + return; + } + this.trace("receive HTTP/2 data frame of length " + data.length); + let messages; + try { + messages = this.decoder.write(data); + } catch (e) { + if (this.httpStatusCode !== void 0 && this.httpStatusCode !== 200) { + const mappedStatus = mapHttpStatusCode(this.httpStatusCode); + this.cancelWithStatus(mappedStatus.code, mappedStatus.details); + } else { + this.cancelWithStatus(constants_1.Status.RESOURCE_EXHAUSTED, e.message); + } + return; + } + for (const message of messages) { + this.trace("parsed message of length " + message.length); + this.callEventTracker.addMessageReceived(); + this.tryPush(message); + } + }); + http2Stream.on("end", () => { + this.readsClosed = true; + this.maybeOutputStatus(); + }); + http2Stream.on("close", () => { + this.serverEndedCall = true; + process.nextTick(() => { + var _a2; + this.trace("HTTP/2 stream closed with code " + http2Stream.rstCode); + if (((_a2 = this.finalStatus) === null || _a2 === void 0 ? void 0 : _a2.code) === constants_1.Status.OK) { + return; + } + let code; + let details = ""; + switch (http2Stream.rstCode) { + case http2.constants.NGHTTP2_NO_ERROR: + if (this.finalStatus !== null) { + return; + } + if (this.httpStatusCode && this.httpStatusCode !== 200) { + const mappedStatus = mapHttpStatusCode(this.httpStatusCode); + code = mappedStatus.code; + details = mappedStatus.details; + } else { + code = constants_1.Status.INTERNAL; + details = `Received RST_STREAM with code ${http2Stream.rstCode} (Call ended without gRPC status)`; + } + break; + case http2.constants.NGHTTP2_REFUSED_STREAM: + code = constants_1.Status.UNAVAILABLE; + details = "Stream refused by server"; + break; + case http2.constants.NGHTTP2_CANCEL: + if (this.connectionDropped) { + code = constants_1.Status.UNAVAILABLE; + details = "Connection dropped"; + } else { + code = constants_1.Status.CANCELLED; + details = "Call cancelled"; + } + break; + case http2.constants.NGHTTP2_ENHANCE_YOUR_CALM: + code = constants_1.Status.RESOURCE_EXHAUSTED; + details = "Bandwidth exhausted or memory limit exceeded"; + break; + case http2.constants.NGHTTP2_INADEQUATE_SECURITY: + code = constants_1.Status.PERMISSION_DENIED; + details = "Protocol not secure enough"; + break; + case http2.constants.NGHTTP2_INTERNAL_ERROR: + code = constants_1.Status.INTERNAL; + if (this.internalError === null) { + details = `Received RST_STREAM with code ${http2Stream.rstCode} (Internal server error)`; + } else { + if (this.internalError.code === "ECONNRESET" || this.internalError.code === "ETIMEDOUT") { + code = constants_1.Status.UNAVAILABLE; + details = this.internalError.message; + } else { + details = `Received RST_STREAM with code ${http2Stream.rstCode} triggered by internal client error: ${this.internalError.message}`; + } + } + break; + default: + code = constants_1.Status.INTERNAL; + details = `Received RST_STREAM with code ${http2Stream.rstCode}`; + } + this.endCall({ + code, + details, + metadata: new metadata_1.Metadata(), + rstCode: http2Stream.rstCode + }); + }); + }); + http2Stream.on("error", (err) => { + if (err.code !== "ERR_HTTP2_STREAM_ERROR") { + this.trace("Node error event: message=" + err.message + " code=" + err.code + " errno=" + getSystemErrorName(err.errno) + " syscall=" + err.syscall); + this.internalError = err; + } + this.callEventTracker.onStreamEnd(false); + }); + } + getDeadlineInfo() { + return [`remote_addr=${this.getPeer()}`]; + } + onDisconnect() { + this.connectionDropped = true; + setImmediate(() => { + this.endCall({ + code: constants_1.Status.UNAVAILABLE, + details: "Connection dropped", + metadata: new metadata_1.Metadata() + }); + }); + } + outputStatus() { + if (!this.statusOutput) { + this.statusOutput = true; + this.trace("ended with status: code=" + this.finalStatus.code + ' details="' + this.finalStatus.details + '"'); + this.callEventTracker.onCallEnd(this.finalStatus); + process.nextTick(() => { + this.listener.onReceiveStatus(this.finalStatus); + }); + this.http2Stream.resume(); + } + } + trace(text) { + logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callId + "] " + text); + } + /** + * On first call, emits a 'status' event with the given StatusObject. + * Subsequent calls are no-ops. + * @param status The status of the call. + */ + endCall(status) { + if (this.finalStatus === null || this.finalStatus.code === constants_1.Status.OK) { + this.finalStatus = status; + this.maybeOutputStatus(); + } + this.destroyHttp2Stream(); + } + maybeOutputStatus() { + if (this.finalStatus !== null) { + if (this.finalStatus.code !== constants_1.Status.OK || this.readsClosed && this.unpushedReadMessages.length === 0 && !this.isReadFilterPending && !this.isPushPending) { + this.outputStatus(); + } + } + } + push(message) { + this.trace("pushing to reader message of length " + (message instanceof Buffer ? message.length : null)); + this.canPush = false; + this.isPushPending = true; + process.nextTick(() => { + this.isPushPending = false; + if (this.statusOutput) { + return; + } + this.listener.onReceiveMessage(message); + this.maybeOutputStatus(); + }); + } + tryPush(messageBytes) { + if (this.canPush) { + this.http2Stream.pause(); + this.push(messageBytes); + } else { + this.trace("unpushedReadMessages.push message of length " + messageBytes.length); + this.unpushedReadMessages.push(messageBytes); + } + } + handleTrailers(headers) { + this.serverEndedCall = true; + this.callEventTracker.onStreamEnd(true); + let headersString = ""; + for (const header of Object.keys(headers)) { + headersString += " " + header + ": " + headers[header] + "\n"; + } + this.trace("Received server trailers:\n" + headersString); + let metadata; + try { + metadata = metadata_1.Metadata.fromHttp2Headers(headers); + } catch (e) { + metadata = new metadata_1.Metadata(); + } + const metadataMap = metadata.getMap(); + let status; + if (typeof metadataMap["grpc-status"] === "string") { + const receivedStatus = Number(metadataMap["grpc-status"]); + this.trace("received status code " + receivedStatus + " from server"); + metadata.remove("grpc-status"); + let details = ""; + if (typeof metadataMap["grpc-message"] === "string") { + try { + details = decodeURI(metadataMap["grpc-message"]); + } catch (e) { + details = metadataMap["grpc-message"]; + } + metadata.remove("grpc-message"); + this.trace('received status details string "' + details + '" from server'); + } + status = { + code: receivedStatus, + details, + metadata + }; + } else if (this.httpStatusCode) { + status = mapHttpStatusCode(this.httpStatusCode); + status.metadata = metadata; + } else { + status = { + code: constants_1.Status.UNKNOWN, + details: "No status information received", + metadata + }; + } + this.endCall(status); + } + destroyHttp2Stream() { + var _a; + if (this.http2Stream.destroyed) { + return; + } + if (this.serverEndedCall) { + this.http2Stream.end(); + } else { + let code; + if (((_a = this.finalStatus) === null || _a === void 0 ? void 0 : _a.code) === constants_1.Status.OK) { + code = http2.constants.NGHTTP2_NO_ERROR; + } else { + code = http2.constants.NGHTTP2_CANCEL; + } + this.trace("close http2 stream with code " + code); + this.http2Stream.close(code); + } + } + cancelWithStatus(status, details) { + this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"'); + this.endCall({ code: status, details, metadata: new metadata_1.Metadata() }); + } + getStatus() { + return this.finalStatus; + } + getPeer() { + return this.transport.getPeerName(); + } + getCallNumber() { + return this.callId; + } + getAuthContext() { + return this.transport.getAuthContext(); + } + startRead() { + if (this.finalStatus !== null && this.finalStatus.code !== constants_1.Status.OK) { + this.readsClosed = true; + this.maybeOutputStatus(); + return; + } + this.canPush = true; + if (this.unpushedReadMessages.length > 0) { + const nextMessage = this.unpushedReadMessages.shift(); + this.push(nextMessage); + return; + } + this.http2Stream.resume(); + } + sendMessageWithContext(context3, message) { + this.trace("write() called with message of length " + message.length); + const cb = (error2) => { + process.nextTick(() => { + var _a; + let code = constants_1.Status.UNAVAILABLE; + if ((error2 === null || error2 === void 0 ? void 0 : error2.code) === "ERR_STREAM_WRITE_AFTER_END") { + code = constants_1.Status.INTERNAL; + } + if (error2) { + this.cancelWithStatus(code, `Write error: ${error2.message}`); + } + (_a = context3.callback) === null || _a === void 0 ? void 0 : _a.call(context3); + }); + }; + this.trace("sending data chunk of length " + message.length); + this.callEventTracker.addMessageSent(); + try { + this.http2Stream.write(message, cb); + } catch (error2) { + this.endCall({ + code: constants_1.Status.UNAVAILABLE, + details: `Write failed with error ${error2.message}`, + metadata: new metadata_1.Metadata() + }); + } + } + halfClose() { + this.trace("end() called"); + this.trace("calling end() on HTTP/2 stream"); + this.http2Stream.end(); + } + }; + exports2.Http2SubchannelCall = Http2SubchannelCall; + } +}); + +// node_modules/@grpc/grpc-js/build/src/transport.js +var require_transport = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/transport.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Http2SubchannelConnector = void 0; + var http2 = require("http2"); + var tls_1 = require("tls"); + var channelz_1 = require_channelz(); + var constants_1 = require_constants7(); + var http_proxy_1 = require_http_proxy(); + var logging = require_logging(); + var resolver_1 = require_resolver(); + var subchannel_address_1 = require_subchannel_address(); + var uri_parser_1 = require_uri_parser(); + var net = require("net"); + var subchannel_call_1 = require_subchannel_call(); + var call_number_1 = require_call_number(); + var TRACER_NAME = "transport"; + var FLOW_CONTROL_TRACER_NAME = "transport_flowctrl"; + var clientVersion = require_package2().version; + var { HTTP2_HEADER_AUTHORITY, HTTP2_HEADER_CONTENT_TYPE, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_TE, HTTP2_HEADER_USER_AGENT } = http2.constants; + var KEEPALIVE_TIMEOUT_MS = 2e4; + var tooManyPingsData = Buffer.from("too_many_pings", "ascii"); + var Http2Transport = class { + constructor(session, subchannelAddress, options, remoteName) { + this.session = session; + this.options = options; + this.remoteName = remoteName; + this.keepaliveTimer = null; + this.pendingSendKeepalivePing = false; + this.activeCalls = /* @__PURE__ */ new Set(); + this.disconnectListeners = []; + this.disconnectHandled = false; + this.channelzEnabled = true; + this.keepalivesSent = 0; + this.messagesSent = 0; + this.messagesReceived = 0; + this.lastMessageSentTimestamp = null; + this.lastMessageReceivedTimestamp = null; + this.subchannelAddressString = (0, subchannel_address_1.subchannelAddressToString)(subchannelAddress); + if (options["grpc.enable_channelz"] === 0) { + this.channelzEnabled = false; + this.streamTracker = new channelz_1.ChannelzCallTrackerStub(); + } else { + this.streamTracker = new channelz_1.ChannelzCallTracker(); + } + this.channelzRef = (0, channelz_1.registerChannelzSocket)(this.subchannelAddressString, () => this.getChannelzInfo(), this.channelzEnabled); + this.userAgent = [ + options["grpc.primary_user_agent"], + `grpc-node-js/${clientVersion}`, + options["grpc.secondary_user_agent"] + ].filter((e) => e).join(" "); + if ("grpc.keepalive_time_ms" in options) { + this.keepaliveTimeMs = options["grpc.keepalive_time_ms"]; + } else { + this.keepaliveTimeMs = -1; + } + if ("grpc.keepalive_timeout_ms" in options) { + this.keepaliveTimeoutMs = options["grpc.keepalive_timeout_ms"]; + } else { + this.keepaliveTimeoutMs = KEEPALIVE_TIMEOUT_MS; + } + if ("grpc.keepalive_permit_without_calls" in options) { + this.keepaliveWithoutCalls = options["grpc.keepalive_permit_without_calls"] === 1; + } else { + this.keepaliveWithoutCalls = false; + } + session.once("close", () => { + this.trace("session closed"); + this.handleDisconnect(); + }); + session.once("goaway", (errorCode, lastStreamID, opaqueData) => { + let tooManyPings = false; + if (errorCode === http2.constants.NGHTTP2_ENHANCE_YOUR_CALM && opaqueData && opaqueData.equals(tooManyPingsData)) { + tooManyPings = true; + } + this.trace("connection closed by GOAWAY with code " + errorCode + " and data " + (opaqueData === null || opaqueData === void 0 ? void 0 : opaqueData.toString())); + this.reportDisconnectToOwner(tooManyPings); + }); + session.once("error", (error2) => { + this.trace("connection closed with error " + error2.message); + this.handleDisconnect(); + }); + session.socket.once("close", (hadError) => { + this.trace("connection closed. hadError=" + hadError); + this.handleDisconnect(); + }); + if (logging.isTracerEnabled(TRACER_NAME)) { + session.on("remoteSettings", (settings) => { + this.trace("new settings received" + (this.session !== session ? " on the old connection" : "") + ": " + JSON.stringify(settings)); + }); + session.on("localSettings", (settings) => { + this.trace("local settings acknowledged by remote" + (this.session !== session ? " on the old connection" : "") + ": " + JSON.stringify(settings)); + }); + } + if (this.keepaliveWithoutCalls) { + this.maybeStartKeepalivePingTimer(); + } + if (session.socket instanceof tls_1.TLSSocket) { + this.authContext = { + transportSecurityType: "ssl", + sslPeerCertificate: session.socket.getPeerCertificate() + }; + } else { + this.authContext = {}; + } + } + getChannelzInfo() { + var _a, _b, _c; + const sessionSocket = this.session.socket; + const remoteAddress = sessionSocket.remoteAddress ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.remoteAddress, sessionSocket.remotePort) : null; + const localAddress = sessionSocket.localAddress ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.localAddress, sessionSocket.localPort) : null; + let tlsInfo; + if (this.session.encrypted) { + const tlsSocket = sessionSocket; + const cipherInfo = tlsSocket.getCipher(); + const certificate = tlsSocket.getCertificate(); + const peerCertificate = tlsSocket.getPeerCertificate(); + tlsInfo = { + cipherSuiteStandardName: (_a = cipherInfo.standardName) !== null && _a !== void 0 ? _a : null, + cipherSuiteOtherName: cipherInfo.standardName ? null : cipherInfo.name, + localCertificate: certificate && "raw" in certificate ? certificate.raw : null, + remoteCertificate: peerCertificate && "raw" in peerCertificate ? peerCertificate.raw : null + }; + } else { + tlsInfo = null; + } + const socketInfo = { + remoteAddress, + localAddress, + security: tlsInfo, + remoteName: this.remoteName, + streamsStarted: this.streamTracker.callsStarted, + streamsSucceeded: this.streamTracker.callsSucceeded, + streamsFailed: this.streamTracker.callsFailed, + messagesSent: this.messagesSent, + messagesReceived: this.messagesReceived, + keepAlivesSent: this.keepalivesSent, + lastLocalStreamCreatedTimestamp: this.streamTracker.lastCallStartedTimestamp, + lastRemoteStreamCreatedTimestamp: null, + lastMessageSentTimestamp: this.lastMessageSentTimestamp, + lastMessageReceivedTimestamp: this.lastMessageReceivedTimestamp, + localFlowControlWindow: (_b = this.session.state.localWindowSize) !== null && _b !== void 0 ? _b : null, + remoteFlowControlWindow: (_c = this.session.state.remoteWindowSize) !== null && _c !== void 0 ? _c : null + }; + return socketInfo; + } + trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + } + keepaliveTrace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, "keepalive", "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + } + flowControlTrace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, FLOW_CONTROL_TRACER_NAME, "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + } + internalsTrace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, "transport_internals", "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + } + /** + * Indicate to the owner of this object that this transport should no longer + * be used. That happens if the connection drops, or if the server sends a + * GOAWAY. + * @param tooManyPings If true, this was triggered by a GOAWAY with data + * indicating that the session was closed becaues the client sent too many + * pings. + * @returns + */ + reportDisconnectToOwner(tooManyPings) { + if (this.disconnectHandled) { + return; + } + this.disconnectHandled = true; + this.disconnectListeners.forEach((listener) => listener(tooManyPings)); + } + /** + * Handle connection drops, but not GOAWAYs. + */ + handleDisconnect() { + this.clearKeepaliveTimeout(); + this.reportDisconnectToOwner(false); + for (const call of this.activeCalls) { + call.onDisconnect(); + } + setImmediate(() => { + this.session.destroy(); + }); + } + addDisconnectListener(listener) { + this.disconnectListeners.push(listener); + } + canSendPing() { + return !this.session.destroyed && this.keepaliveTimeMs > 0 && (this.keepaliveWithoutCalls || this.activeCalls.size > 0); + } + maybeSendPing() { + var _a, _b; + if (!this.canSendPing()) { + this.pendingSendKeepalivePing = true; + return; + } + if (this.keepaliveTimer) { + console.error("keepaliveTimeout is not null"); + return; + } + if (this.channelzEnabled) { + this.keepalivesSent += 1; + } + this.keepaliveTrace("Sending ping with timeout " + this.keepaliveTimeoutMs + "ms"); + this.keepaliveTimer = setTimeout(() => { + this.keepaliveTimer = null; + this.keepaliveTrace("Ping timeout passed without response"); + this.handleDisconnect(); + }, this.keepaliveTimeoutMs); + (_b = (_a = this.keepaliveTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); + let pingSendError = ""; + try { + const pingSentSuccessfully = this.session.ping((err, duration, payload) => { + this.clearKeepaliveTimeout(); + if (err) { + this.keepaliveTrace("Ping failed with error " + err.message); + this.handleDisconnect(); + } else { + this.keepaliveTrace("Received ping response"); + this.maybeStartKeepalivePingTimer(); + } + }); + if (!pingSentSuccessfully) { + pingSendError = "Ping returned false"; + } + } catch (e) { + pingSendError = (e instanceof Error ? e.message : "") || "Unknown error"; + } + if (pingSendError) { + this.keepaliveTrace("Ping send failed: " + pingSendError); + this.handleDisconnect(); + } + } + /** + * Starts the keepalive ping timer if appropriate. If the timer already ran + * out while there were no active requests, instead send a ping immediately. + * If the ping timer is already running or a ping is currently in flight, + * instead do nothing and wait for them to resolve. + */ + maybeStartKeepalivePingTimer() { + var _a, _b; + if (!this.canSendPing()) { + return; + } + if (this.pendingSendKeepalivePing) { + this.pendingSendKeepalivePing = false; + this.maybeSendPing(); + } else if (!this.keepaliveTimer) { + this.keepaliveTrace("Starting keepalive timer for " + this.keepaliveTimeMs + "ms"); + this.keepaliveTimer = setTimeout(() => { + this.keepaliveTimer = null; + this.maybeSendPing(); + }, this.keepaliveTimeMs); + (_b = (_a = this.keepaliveTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); + } + } + /** + * Clears whichever keepalive timeout is currently active, if any. + */ + clearKeepaliveTimeout() { + if (this.keepaliveTimer) { + clearTimeout(this.keepaliveTimer); + this.keepaliveTimer = null; + } + } + removeActiveCall(call) { + this.activeCalls.delete(call); + if (this.activeCalls.size === 0) { + this.session.unref(); + } + } + addActiveCall(call) { + this.activeCalls.add(call); + if (this.activeCalls.size === 1) { + this.session.ref(); + if (!this.keepaliveWithoutCalls) { + this.maybeStartKeepalivePingTimer(); + } + } + } + createCall(metadata, host, method, listener, subchannelCallStatsTracker) { + const headers = metadata.toHttp2Headers(); + headers[HTTP2_HEADER_AUTHORITY] = host; + headers[HTTP2_HEADER_USER_AGENT] = this.userAgent; + headers[HTTP2_HEADER_CONTENT_TYPE] = "application/grpc"; + headers[HTTP2_HEADER_METHOD] = "POST"; + headers[HTTP2_HEADER_PATH] = method; + headers[HTTP2_HEADER_TE] = "trailers"; + let http2Stream; + try { + http2Stream = this.session.request(headers); + } catch (e) { + this.handleDisconnect(); + throw e; + } + this.flowControlTrace("local window size: " + this.session.state.localWindowSize + " remote window size: " + this.session.state.remoteWindowSize); + this.internalsTrace("session.closed=" + this.session.closed + " session.destroyed=" + this.session.destroyed + " session.socket.destroyed=" + this.session.socket.destroyed); + let eventTracker; + let call; + if (this.channelzEnabled) { + this.streamTracker.addCallStarted(); + eventTracker = { + addMessageSent: () => { + var _a; + this.messagesSent += 1; + this.lastMessageSentTimestamp = /* @__PURE__ */ new Date(); + (_a = subchannelCallStatsTracker.addMessageSent) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); + }, + addMessageReceived: () => { + var _a; + this.messagesReceived += 1; + this.lastMessageReceivedTimestamp = /* @__PURE__ */ new Date(); + (_a = subchannelCallStatsTracker.addMessageReceived) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); + }, + onCallEnd: (status) => { + var _a; + (_a = subchannelCallStatsTracker.onCallEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, status); + this.removeActiveCall(call); + }, + onStreamEnd: (success) => { + var _a; + if (success) { + this.streamTracker.addCallSucceeded(); + } else { + this.streamTracker.addCallFailed(); + } + (_a = subchannelCallStatsTracker.onStreamEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, success); + } + }; + } else { + eventTracker = { + addMessageSent: () => { + var _a; + (_a = subchannelCallStatsTracker.addMessageSent) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); + }, + addMessageReceived: () => { + var _a; + (_a = subchannelCallStatsTracker.addMessageReceived) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); + }, + onCallEnd: (status) => { + var _a; + (_a = subchannelCallStatsTracker.onCallEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, status); + this.removeActiveCall(call); + }, + onStreamEnd: (success) => { + var _a; + (_a = subchannelCallStatsTracker.onStreamEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, success); + } + }; + } + call = new subchannel_call_1.Http2SubchannelCall(http2Stream, eventTracker, listener, this, (0, call_number_1.getNextCallNumber)()); + this.addActiveCall(call); + return call; + } + getChannelzRef() { + return this.channelzRef; + } + getPeerName() { + return this.subchannelAddressString; + } + getOptions() { + return this.options; + } + getAuthContext() { + return this.authContext; + } + shutdown() { + this.session.close(); + (0, channelz_1.unregisterChannelzRef)(this.channelzRef); + } + }; + var Http2SubchannelConnector = class { + constructor(channelTarget) { + this.channelTarget = channelTarget; + this.session = null; + this.isShutdown = false; + } + trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, (0, uri_parser_1.uriToString)(this.channelTarget) + " " + text); + } + createSession(secureConnectResult, address, options) { + if (this.isShutdown) { + return Promise.reject(); + } + if (secureConnectResult.socket.closed) { + return Promise.reject("Connection closed before starting HTTP/2 handshake"); + } + return new Promise((resolve, reject) => { + var _a, _b, _c, _d, _e, _f, _g, _h; + let remoteName = null; + let realTarget = this.channelTarget; + if ("grpc.http_connect_target" in options) { + const parsedTarget = (0, uri_parser_1.parseUri)(options["grpc.http_connect_target"]); + if (parsedTarget) { + realTarget = parsedTarget; + remoteName = (0, uri_parser_1.uriToString)(parsedTarget); + } + } + const scheme = secureConnectResult.secure ? "https" : "http"; + const targetPath = (0, resolver_1.getDefaultAuthority)(realTarget); + const closeHandler = () => { + var _a2; + (_a2 = this.session) === null || _a2 === void 0 ? void 0 : _a2.destroy(); + this.session = null; + setImmediate(() => { + if (!reportedError) { + reportedError = true; + reject(`${errorMessage.trim()} (${(/* @__PURE__ */ new Date()).toISOString()})`); + } + }); + }; + const errorHandler = (error2) => { + var _a2; + (_a2 = this.session) === null || _a2 === void 0 ? void 0 : _a2.destroy(); + errorMessage = error2.message; + this.trace("connection failed with error " + errorMessage); + if (!reportedError) { + reportedError = true; + reject(`${errorMessage} (${(/* @__PURE__ */ new Date()).toISOString()})`); + } + }; + const sessionOptions = { + createConnection: (authority, option) => { + return secureConnectResult.socket; + }, + settings: { + initialWindowSize: (_d = (_a = options["grpc-node.flow_control_window"]) !== null && _a !== void 0 ? _a : (_c = (_b = http2.getDefaultSettings) === null || _b === void 0 ? void 0 : _b.call(http2)) === null || _c === void 0 ? void 0 : _c.initialWindowSize) !== null && _d !== void 0 ? _d : 65535 + }, + maxSendHeaderBlockLength: Number.MAX_SAFE_INTEGER, + /* By default, set a very large max session memory limit, to effectively + * disable enforcement of the limit. Some testing indicates that Node's + * behavior degrades badly when this limit is reached, so we solve that + * by disabling the check entirely. */ + maxSessionMemory: (_e = options["grpc-node.max_session_memory"]) !== null && _e !== void 0 ? _e : Number.MAX_SAFE_INTEGER + }; + const session = http2.connect(`${scheme}://${targetPath}`, sessionOptions); + const defaultWin = (_h = (_g = (_f = http2.getDefaultSettings) === null || _f === void 0 ? void 0 : _f.call(http2)) === null || _g === void 0 ? void 0 : _g.initialWindowSize) !== null && _h !== void 0 ? _h : 65535; + const connWin = options["grpc-node.flow_control_window"]; + this.session = session; + let errorMessage = "Failed to connect"; + let reportedError = false; + session.unref(); + session.once("remoteSettings", () => { + var _a2; + if (connWin && connWin > defaultWin) { + try { + session.setLocalWindowSize(connWin); + } catch (_b2) { + const delta = connWin - ((_a2 = session.state.localWindowSize) !== null && _a2 !== void 0 ? _a2 : defaultWin); + if (delta > 0) + session.incrementWindowSize(delta); + } + } + session.removeAllListeners(); + secureConnectResult.socket.removeListener("close", closeHandler); + secureConnectResult.socket.removeListener("error", errorHandler); + resolve(new Http2Transport(session, address, options, remoteName)); + this.session = null; + }); + session.once("close", closeHandler); + session.once("error", errorHandler); + secureConnectResult.socket.once("close", closeHandler); + secureConnectResult.socket.once("error", errorHandler); + }); + } + tcpConnect(address, options) { + return (0, http_proxy_1.getProxiedConnection)(address, options).then((proxiedSocket) => { + if (proxiedSocket) { + return proxiedSocket; + } else { + return new Promise((resolve, reject) => { + const closeCallback = () => { + reject(new Error("Socket closed")); + }; + const errorCallback = (error2) => { + reject(error2); + }; + const socket = net.connect(address, () => { + socket.removeListener("close", closeCallback); + socket.removeListener("error", errorCallback); + resolve(socket); + }); + socket.once("close", closeCallback); + socket.once("error", errorCallback); + }); + } + }); + } + async connect(address, secureConnector, options) { + if (this.isShutdown) { + return Promise.reject(); + } + let tcpConnection = null; + let secureConnectResult = null; + const addressString = (0, subchannel_address_1.subchannelAddressToString)(address); + try { + this.trace(addressString + " Waiting for secureConnector to be ready"); + await secureConnector.waitForReady(); + this.trace(addressString + " secureConnector is ready"); + tcpConnection = await this.tcpConnect(address, options); + tcpConnection.setNoDelay(); + this.trace(addressString + " Established TCP connection"); + secureConnectResult = await secureConnector.connect(tcpConnection); + this.trace(addressString + " Established secure connection"); + return this.createSession(secureConnectResult, address, options); + } catch (e) { + tcpConnection === null || tcpConnection === void 0 ? void 0 : tcpConnection.destroy(); + secureConnectResult === null || secureConnectResult === void 0 ? void 0 : secureConnectResult.socket.destroy(); + throw e; + } + } + shutdown() { + var _a; + this.isShutdown = true; + (_a = this.session) === null || _a === void 0 ? void 0 : _a.close(); + this.session = null; + } + }; + exports2.Http2SubchannelConnector = Http2SubchannelConnector; + } +}); + +// node_modules/@grpc/grpc-js/build/src/subchannel-pool.js +var require_subchannel_pool = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/subchannel-pool.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.SubchannelPool = void 0; + exports2.getSubchannelPool = getSubchannelPool; + var channel_options_1 = require_channel_options(); + var subchannel_1 = require_subchannel(); + var subchannel_address_1 = require_subchannel_address(); + var uri_parser_1 = require_uri_parser(); + var transport_1 = require_transport(); + var REF_CHECK_INTERVAL = 1e4; + var SubchannelPool = class { + /** + * A pool of subchannels use for making connections. Subchannels with the + * exact same parameters will be reused. + */ + constructor() { + this.pool = /* @__PURE__ */ Object.create(null); + this.cleanupTimer = null; + } + /** + * Unrefs all unused subchannels and cancels the cleanup task if all + * subchannels have been unrefed. + */ + unrefUnusedSubchannels() { + let allSubchannelsUnrefed = true; + for (const channelTarget in this.pool) { + const subchannelObjArray = this.pool[channelTarget]; + const refedSubchannels = subchannelObjArray.filter((value) => !value.subchannel.unrefIfOneRef()); + if (refedSubchannels.length > 0) { + allSubchannelsUnrefed = false; + } + this.pool[channelTarget] = refedSubchannels; + } + if (allSubchannelsUnrefed && this.cleanupTimer !== null) { + clearInterval(this.cleanupTimer); + this.cleanupTimer = null; + } + } + /** + * Ensures that the cleanup task is spawned. + */ + ensureCleanupTask() { + var _a, _b; + if (this.cleanupTimer === null) { + this.cleanupTimer = setInterval(() => { + this.unrefUnusedSubchannels(); + }, REF_CHECK_INTERVAL); + (_b = (_a = this.cleanupTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); + } + } + /** + * Get a subchannel if one already exists with exactly matching parameters. + * Otherwise, create and save a subchannel with those parameters. + * @param channelTarget + * @param subchannelTarget + * @param channelArguments + * @param channelCredentials + */ + getOrCreateSubchannel(channelTargetUri, subchannelTarget, channelArguments, channelCredentials) { + this.ensureCleanupTask(); + const channelTarget = (0, uri_parser_1.uriToString)(channelTargetUri); + if (channelTarget in this.pool) { + const subchannelObjArray = this.pool[channelTarget]; + for (const subchannelObj of subchannelObjArray) { + if ((0, subchannel_address_1.subchannelAddressEqual)(subchannelTarget, subchannelObj.subchannelAddress) && (0, channel_options_1.channelOptionsEqual)(channelArguments, subchannelObj.channelArguments) && channelCredentials._equals(subchannelObj.channelCredentials)) { + return subchannelObj.subchannel; + } + } + } + const subchannel = new subchannel_1.Subchannel(channelTargetUri, subchannelTarget, channelArguments, channelCredentials, new transport_1.Http2SubchannelConnector(channelTargetUri)); + if (!(channelTarget in this.pool)) { + this.pool[channelTarget] = []; + } + this.pool[channelTarget].push({ + subchannelAddress: subchannelTarget, + channelArguments, + channelCredentials, + subchannel + }); + subchannel.ref(); + return subchannel; + } + }; + exports2.SubchannelPool = SubchannelPool; + var globalSubchannelPool = new SubchannelPool(); + function getSubchannelPool(global2) { + if (global2) { + return globalSubchannelPool; + } else { + return new SubchannelPool(); + } + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/load-balancing-call.js +var require_load_balancing_call = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/load-balancing-call.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.LoadBalancingCall = void 0; + var connectivity_state_1 = require_connectivity_state(); + var constants_1 = require_constants7(); + var deadline_1 = require_deadline(); + var metadata_1 = require_metadata(); + var picker_1 = require_picker(); + var uri_parser_1 = require_uri_parser(); + var logging = require_logging(); + var control_plane_status_1 = require_control_plane_status(); + var http2 = require("http2"); + var TRACER_NAME = "load_balancing_call"; + var LoadBalancingCall = class { + constructor(channel, callConfig, methodName, host, credentials, deadline, callNumber) { + var _a, _b; + this.channel = channel; + this.callConfig = callConfig; + this.methodName = methodName; + this.host = host; + this.credentials = credentials; + this.deadline = deadline; + this.callNumber = callNumber; + this.child = null; + this.readPending = false; + this.pendingMessage = null; + this.pendingHalfClose = false; + this.ended = false; + this.metadata = null; + this.listener = null; + this.onCallEnded = null; + this.childStartTime = null; + const splitPath = this.methodName.split("/"); + let serviceName = ""; + if (splitPath.length >= 2) { + serviceName = splitPath[1]; + } + const hostname = (_b = (_a = (0, uri_parser_1.splitHostPort)(this.host)) === null || _a === void 0 ? void 0 : _a.host) !== null && _b !== void 0 ? _b : "localhost"; + this.serviceUrl = `https://${hostname}/${serviceName}`; + this.startTime = /* @__PURE__ */ new Date(); + } + getDeadlineInfo() { + var _a, _b; + const deadlineInfo = []; + if (this.childStartTime) { + if (this.childStartTime > this.startTime) { + if ((_a = this.metadata) === null || _a === void 0 ? void 0 : _a.getOptions().waitForReady) { + deadlineInfo.push("wait_for_ready"); + } + deadlineInfo.push(`LB pick: ${(0, deadline_1.formatDateDifference)(this.startTime, this.childStartTime)}`); + } + deadlineInfo.push(...this.child.getDeadlineInfo()); + return deadlineInfo; + } else { + if ((_b = this.metadata) === null || _b === void 0 ? void 0 : _b.getOptions().waitForReady) { + deadlineInfo.push("wait_for_ready"); + } + deadlineInfo.push("Waiting for LB pick"); + } + return deadlineInfo; + } + trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callNumber + "] " + text); + } + outputStatus(status, progress) { + var _a, _b; + if (!this.ended) { + this.ended = true; + this.trace("ended with status: code=" + status.code + ' details="' + status.details + '" start time=' + this.startTime.toISOString()); + const finalStatus = Object.assign(Object.assign({}, status), { progress }); + (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onReceiveStatus(finalStatus); + (_b = this.onCallEnded) === null || _b === void 0 ? void 0 : _b.call(this, finalStatus.code, finalStatus.details, finalStatus.metadata); + } + } + doPick() { + var _a, _b; + if (this.ended) { + return; + } + if (!this.metadata) { + throw new Error("doPick called before start"); + } + this.trace("Pick called"); + const finalMetadata = this.metadata.clone(); + const pickResult = this.channel.doPick(finalMetadata, this.callConfig.pickInformation); + const subchannelString = pickResult.subchannel ? "(" + pickResult.subchannel.getChannelzRef().id + ") " + pickResult.subchannel.getAddress() : "" + pickResult.subchannel; + this.trace("Pick result: " + picker_1.PickResultType[pickResult.pickResultType] + " subchannel: " + subchannelString + " status: " + ((_a = pickResult.status) === null || _a === void 0 ? void 0 : _a.code) + " " + ((_b = pickResult.status) === null || _b === void 0 ? void 0 : _b.details)); + switch (pickResult.pickResultType) { + case picker_1.PickResultType.COMPLETE: + const combinedCallCredentials = this.credentials.compose(pickResult.subchannel.getCallCredentials()); + combinedCallCredentials.generateMetadata({ method_name: this.methodName, service_url: this.serviceUrl }).then((credsMetadata) => { + var _a2; + if (this.ended) { + this.trace("Credentials metadata generation finished after call ended"); + return; + } + finalMetadata.merge(credsMetadata); + if (finalMetadata.get("authorization").length > 1) { + this.outputStatus({ + code: constants_1.Status.INTERNAL, + details: '"authorization" metadata cannot have multiple values', + metadata: new metadata_1.Metadata() + }, "PROCESSED"); + } + if (pickResult.subchannel.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) { + this.trace("Picked subchannel " + subchannelString + " has state " + connectivity_state_1.ConnectivityState[pickResult.subchannel.getConnectivityState()] + " after getting credentials metadata. Retrying pick"); + this.doPick(); + return; + } + if (this.deadline !== Infinity) { + finalMetadata.set("grpc-timeout", (0, deadline_1.getDeadlineTimeoutString)(this.deadline)); + } + try { + this.child = pickResult.subchannel.getRealSubchannel().createCall(finalMetadata, this.host, this.methodName, { + onReceiveMetadata: (metadata) => { + this.trace("Received metadata"); + this.listener.onReceiveMetadata(metadata); + }, + onReceiveMessage: (message) => { + this.trace("Received message"); + this.listener.onReceiveMessage(message); + }, + onReceiveStatus: (status) => { + this.trace("Received status"); + if (status.rstCode === http2.constants.NGHTTP2_REFUSED_STREAM) { + this.outputStatus(status, "REFUSED"); + } else { + this.outputStatus(status, "PROCESSED"); + } + } + }); + this.childStartTime = /* @__PURE__ */ new Date(); + } catch (error2) { + this.trace("Failed to start call on picked subchannel " + subchannelString + " with error " + error2.message); + this.outputStatus({ + code: constants_1.Status.INTERNAL, + details: "Failed to start HTTP/2 stream with error " + error2.message, + metadata: new metadata_1.Metadata() + }, "NOT_STARTED"); + return; + } + (_a2 = pickResult.onCallStarted) === null || _a2 === void 0 ? void 0 : _a2.call(pickResult); + this.onCallEnded = pickResult.onCallEnded; + this.trace("Created child call [" + this.child.getCallNumber() + "]"); + if (this.readPending) { + this.child.startRead(); + } + if (this.pendingMessage) { + this.child.sendMessageWithContext(this.pendingMessage.context, this.pendingMessage.message); + } + if (this.pendingHalfClose) { + this.child.halfClose(); + } + }, (error2) => { + const { code: code2, details: details2 } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(typeof error2.code === "number" ? error2.code : constants_1.Status.UNKNOWN, `Getting metadata from plugin failed with error: ${error2.message}`); + this.outputStatus({ + code: code2, + details: details2, + metadata: new metadata_1.Metadata() + }, "PROCESSED"); + }); + break; + case picker_1.PickResultType.DROP: + const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(pickResult.status.code, pickResult.status.details); + setImmediate(() => { + this.outputStatus({ code, details, metadata: pickResult.status.metadata }, "DROP"); + }); + break; + case picker_1.PickResultType.TRANSIENT_FAILURE: + if (this.metadata.getOptions().waitForReady) { + this.channel.queueCallForPick(this); + } else { + const { code: code2, details: details2 } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(pickResult.status.code, pickResult.status.details); + setImmediate(() => { + this.outputStatus({ code: code2, details: details2, metadata: pickResult.status.metadata }, "PROCESSED"); + }); + } + break; + case picker_1.PickResultType.QUEUE: + this.channel.queueCallForPick(this); + } + } + cancelWithStatus(status, details) { + var _a; + this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"'); + (_a = this.child) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(status, details); + this.outputStatus({ code: status, details, metadata: new metadata_1.Metadata() }, "PROCESSED"); + } + getPeer() { + var _a, _b; + return (_b = (_a = this.child) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : this.channel.getTarget(); + } + start(metadata, listener) { + this.trace("start called"); + this.listener = listener; + this.metadata = metadata; + this.doPick(); + } + sendMessageWithContext(context3, message) { + this.trace("write() called with message of length " + message.length); + if (this.child) { + this.child.sendMessageWithContext(context3, message); + } else { + this.pendingMessage = { context: context3, message }; + } + } + startRead() { + this.trace("startRead called"); + if (this.child) { + this.child.startRead(); + } else { + this.readPending = true; + } + } + halfClose() { + this.trace("halfClose called"); + if (this.child) { + this.child.halfClose(); + } else { + this.pendingHalfClose = true; + } + } + setCredentials(credentials) { + throw new Error("Method not implemented."); + } + getCallNumber() { + return this.callNumber; + } + getAuthContext() { + if (this.child) { + return this.child.getAuthContext(); + } else { + return null; + } + } + }; + exports2.LoadBalancingCall = LoadBalancingCall; + } +}); + +// node_modules/@grpc/grpc-js/build/src/resolving-call.js +var require_resolving_call = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/resolving-call.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ResolvingCall = void 0; + var call_credentials_1 = require_call_credentials(); + var constants_1 = require_constants7(); + var deadline_1 = require_deadline(); + var metadata_1 = require_metadata(); + var logging = require_logging(); + var control_plane_status_1 = require_control_plane_status(); + var TRACER_NAME = "resolving_call"; + var ResolvingCall = class { + constructor(channel, method, options, filterStackFactory, callNumber) { + this.channel = channel; + this.method = method; + this.filterStackFactory = filterStackFactory; + this.callNumber = callNumber; + this.child = null; + this.readPending = false; + this.pendingMessage = null; + this.pendingHalfClose = false; + this.ended = false; + this.readFilterPending = false; + this.writeFilterPending = false; + this.pendingChildStatus = null; + this.metadata = null; + this.listener = null; + this.statusWatchers = []; + this.deadlineTimer = setTimeout(() => { + }, 0); + this.filterStack = null; + this.deadlineStartTime = null; + this.configReceivedTime = null; + this.childStartTime = null; + this.credentials = call_credentials_1.CallCredentials.createEmpty(); + this.deadline = options.deadline; + this.host = options.host; + if (options.parentCall) { + if (options.flags & constants_1.Propagate.CANCELLATION) { + options.parentCall.on("cancelled", () => { + this.cancelWithStatus(constants_1.Status.CANCELLED, "Cancelled by parent call"); + }); + } + if (options.flags & constants_1.Propagate.DEADLINE) { + this.trace("Propagating deadline from parent: " + options.parentCall.getDeadline()); + this.deadline = (0, deadline_1.minDeadline)(this.deadline, options.parentCall.getDeadline()); + } + } + this.trace("Created"); + this.runDeadlineTimer(); + } + trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callNumber + "] " + text); + } + runDeadlineTimer() { + clearTimeout(this.deadlineTimer); + this.deadlineStartTime = /* @__PURE__ */ new Date(); + this.trace("Deadline: " + (0, deadline_1.deadlineToString)(this.deadline)); + const timeout = (0, deadline_1.getRelativeTimeout)(this.deadline); + if (timeout !== Infinity) { + this.trace("Deadline will be reached in " + timeout + "ms"); + const handleDeadline = () => { + if (!this.deadlineStartTime) { + this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, "Deadline exceeded"); + return; + } + const deadlineInfo = []; + const deadlineEndTime = /* @__PURE__ */ new Date(); + deadlineInfo.push(`Deadline exceeded after ${(0, deadline_1.formatDateDifference)(this.deadlineStartTime, deadlineEndTime)}`); + if (this.configReceivedTime) { + if (this.configReceivedTime > this.deadlineStartTime) { + deadlineInfo.push(`name resolution: ${(0, deadline_1.formatDateDifference)(this.deadlineStartTime, this.configReceivedTime)}`); + } + if (this.childStartTime) { + if (this.childStartTime > this.configReceivedTime) { + deadlineInfo.push(`metadata filters: ${(0, deadline_1.formatDateDifference)(this.configReceivedTime, this.childStartTime)}`); + } + } else { + deadlineInfo.push("waiting for metadata filters"); + } + } else { + deadlineInfo.push("waiting for name resolution"); + } + if (this.child) { + deadlineInfo.push(...this.child.getDeadlineInfo()); + } + this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, deadlineInfo.join(",")); + }; + if (timeout <= 0) { + process.nextTick(handleDeadline); + } else { + this.deadlineTimer = setTimeout(handleDeadline, timeout); + } + } + } + outputStatus(status) { + if (!this.ended) { + this.ended = true; + if (!this.filterStack) { + this.filterStack = this.filterStackFactory.createFilter(); + } + clearTimeout(this.deadlineTimer); + const filteredStatus = this.filterStack.receiveTrailers(status); + this.trace("ended with status: code=" + filteredStatus.code + ' details="' + filteredStatus.details + '"'); + this.statusWatchers.forEach((watcher) => watcher(filteredStatus)); + process.nextTick(() => { + var _a; + (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onReceiveStatus(filteredStatus); + }); + } + } + sendMessageOnChild(context3, message) { + if (!this.child) { + throw new Error("sendMessageonChild called with child not populated"); + } + const child = this.child; + this.writeFilterPending = true; + this.filterStack.sendMessage(Promise.resolve({ message, flags: context3.flags })).then((filteredMessage) => { + this.writeFilterPending = false; + child.sendMessageWithContext(context3, filteredMessage.message); + if (this.pendingHalfClose) { + child.halfClose(); + } + }, (status) => { + this.cancelWithStatus(status.code, status.details); + }); + } + getConfig() { + if (this.ended) { + return; + } + if (!this.metadata || !this.listener) { + throw new Error("getConfig called before start"); + } + const configResult = this.channel.getConfig(this.method, this.metadata); + if (configResult.type === "NONE") { + this.channel.queueCallForConfig(this); + return; + } else if (configResult.type === "ERROR") { + if (this.metadata.getOptions().waitForReady) { + this.channel.queueCallForConfig(this); + } else { + this.outputStatus(configResult.error); + } + return; + } + this.configReceivedTime = /* @__PURE__ */ new Date(); + const config = configResult.config; + if (config.status !== constants_1.Status.OK) { + const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(config.status, "Failed to route call to method " + this.method); + this.outputStatus({ + code, + details, + metadata: new metadata_1.Metadata() + }); + return; + } + if (config.methodConfig.timeout) { + const configDeadline = /* @__PURE__ */ new Date(); + configDeadline.setSeconds(configDeadline.getSeconds() + config.methodConfig.timeout.seconds); + configDeadline.setMilliseconds(configDeadline.getMilliseconds() + config.methodConfig.timeout.nanos / 1e6); + this.deadline = (0, deadline_1.minDeadline)(this.deadline, configDeadline); + this.runDeadlineTimer(); + } + this.filterStackFactory.push(config.dynamicFilterFactories); + this.filterStack = this.filterStackFactory.createFilter(); + this.filterStack.sendMetadata(Promise.resolve(this.metadata)).then((filteredMetadata) => { + this.child = this.channel.createRetryingCall(config, this.method, this.host, this.credentials, this.deadline); + this.trace("Created child [" + this.child.getCallNumber() + "]"); + this.childStartTime = /* @__PURE__ */ new Date(); + this.child.start(filteredMetadata, { + onReceiveMetadata: (metadata) => { + this.trace("Received metadata"); + this.listener.onReceiveMetadata(this.filterStack.receiveMetadata(metadata)); + }, + onReceiveMessage: (message) => { + this.trace("Received message"); + this.readFilterPending = true; + this.filterStack.receiveMessage(message).then((filteredMesssage) => { + this.trace("Finished filtering received message"); + this.readFilterPending = false; + this.listener.onReceiveMessage(filteredMesssage); + if (this.pendingChildStatus) { + this.outputStatus(this.pendingChildStatus); + } + }, (status) => { + this.cancelWithStatus(status.code, status.details); + }); + }, + onReceiveStatus: (status) => { + this.trace("Received status"); + if (this.readFilterPending) { + this.pendingChildStatus = status; + } else { + this.outputStatus(status); + } + } + }); + if (this.readPending) { + this.child.startRead(); + } + if (this.pendingMessage) { + this.sendMessageOnChild(this.pendingMessage.context, this.pendingMessage.message); + } else if (this.pendingHalfClose) { + this.child.halfClose(); + } + }, (status) => { + this.outputStatus(status); + }); + } + reportResolverError(status) { + var _a; + if ((_a = this.metadata) === null || _a === void 0 ? void 0 : _a.getOptions().waitForReady) { + this.channel.queueCallForConfig(this); + } else { + this.outputStatus(status); + } + } + cancelWithStatus(status, details) { + var _a; + this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"'); + (_a = this.child) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(status, details); + this.outputStatus({ + code: status, + details, + metadata: new metadata_1.Metadata() + }); + } + getPeer() { + var _a, _b; + return (_b = (_a = this.child) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : this.channel.getTarget(); + } + start(metadata, listener) { + this.trace("start called"); + this.metadata = metadata.clone(); + this.listener = listener; + this.getConfig(); + } + sendMessageWithContext(context3, message) { + this.trace("write() called with message of length " + message.length); + if (this.child) { + this.sendMessageOnChild(context3, message); + } else { + this.pendingMessage = { context: context3, message }; + } + } + startRead() { + this.trace("startRead called"); + if (this.child) { + this.child.startRead(); + } else { + this.readPending = true; + } + } + halfClose() { + this.trace("halfClose called"); + if (this.child && !this.writeFilterPending) { + this.child.halfClose(); + } else { + this.pendingHalfClose = true; + } + } + setCredentials(credentials) { + this.credentials = credentials; + } + addStatusWatcher(watcher) { + this.statusWatchers.push(watcher); + } + getCallNumber() { + return this.callNumber; + } + getAuthContext() { + if (this.child) { + return this.child.getAuthContext(); + } else { + return null; + } + } + }; + exports2.ResolvingCall = ResolvingCall; + } +}); + +// node_modules/@grpc/grpc-js/build/src/retrying-call.js +var require_retrying_call = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/retrying-call.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.RetryingCall = exports2.MessageBufferTracker = exports2.RetryThrottler = void 0; + var constants_1 = require_constants7(); + var deadline_1 = require_deadline(); + var metadata_1 = require_metadata(); + var logging = require_logging(); + var TRACER_NAME = "retrying_call"; + var RetryThrottler = class { + constructor(maxTokens, tokenRatio, previousRetryThrottler) { + this.maxTokens = maxTokens; + this.tokenRatio = tokenRatio; + if (previousRetryThrottler) { + this.tokens = previousRetryThrottler.tokens * (maxTokens / previousRetryThrottler.maxTokens); + } else { + this.tokens = maxTokens; + } + } + addCallSucceeded() { + this.tokens = Math.min(this.tokens + this.tokenRatio, this.maxTokens); + } + addCallFailed() { + this.tokens = Math.max(this.tokens - 1, 0); + } + canRetryCall() { + return this.tokens > this.maxTokens / 2; + } + }; + exports2.RetryThrottler = RetryThrottler; + var MessageBufferTracker = class { + constructor(totalLimit, limitPerCall) { + this.totalLimit = totalLimit; + this.limitPerCall = limitPerCall; + this.totalAllocated = 0; + this.allocatedPerCall = /* @__PURE__ */ new Map(); + } + allocate(size, callId) { + var _a; + const currentPerCall = (_a = this.allocatedPerCall.get(callId)) !== null && _a !== void 0 ? _a : 0; + if (this.limitPerCall - currentPerCall < size || this.totalLimit - this.totalAllocated < size) { + return false; + } + this.allocatedPerCall.set(callId, currentPerCall + size); + this.totalAllocated += size; + return true; + } + free(size, callId) { + var _a; + if (this.totalAllocated < size) { + throw new Error(`Invalid buffer allocation state: call ${callId} freed ${size} > total allocated ${this.totalAllocated}`); + } + this.totalAllocated -= size; + const currentPerCall = (_a = this.allocatedPerCall.get(callId)) !== null && _a !== void 0 ? _a : 0; + if (currentPerCall < size) { + throw new Error(`Invalid buffer allocation state: call ${callId} freed ${size} > allocated for call ${currentPerCall}`); + } + this.allocatedPerCall.set(callId, currentPerCall - size); + } + freeAll(callId) { + var _a; + const currentPerCall = (_a = this.allocatedPerCall.get(callId)) !== null && _a !== void 0 ? _a : 0; + if (this.totalAllocated < currentPerCall) { + throw new Error(`Invalid buffer allocation state: call ${callId} allocated ${currentPerCall} > total allocated ${this.totalAllocated}`); + } + this.totalAllocated -= currentPerCall; + this.allocatedPerCall.delete(callId); + } + }; + exports2.MessageBufferTracker = MessageBufferTracker; + var PREVIONS_RPC_ATTEMPTS_METADATA_KEY = "grpc-previous-rpc-attempts"; + var DEFAULT_MAX_ATTEMPTS_LIMIT = 5; + var RetryingCall = class { + constructor(channel, callConfig, methodName, host, credentials, deadline, callNumber, bufferTracker, retryThrottler) { + var _a; + this.channel = channel; + this.callConfig = callConfig; + this.methodName = methodName; + this.host = host; + this.credentials = credentials; + this.deadline = deadline; + this.callNumber = callNumber; + this.bufferTracker = bufferTracker; + this.retryThrottler = retryThrottler; + this.listener = null; + this.initialMetadata = null; + this.underlyingCalls = []; + this.writeBuffer = []; + this.writeBufferOffset = 0; + this.readStarted = false; + this.transparentRetryUsed = false; + this.attempts = 0; + this.hedgingTimer = null; + this.committedCallIndex = null; + this.initialRetryBackoffSec = 0; + this.nextRetryBackoffSec = 0; + const maxAttemptsLimit = (_a = channel.getOptions()["grpc-node.retry_max_attempts_limit"]) !== null && _a !== void 0 ? _a : DEFAULT_MAX_ATTEMPTS_LIMIT; + if (channel.getOptions()["grpc.enable_retries"] === 0) { + this.state = "NO_RETRY"; + this.maxAttempts = 1; + } else if (callConfig.methodConfig.retryPolicy) { + this.state = "RETRY"; + const retryPolicy = callConfig.methodConfig.retryPolicy; + this.nextRetryBackoffSec = this.initialRetryBackoffSec = Number(retryPolicy.initialBackoff.substring(0, retryPolicy.initialBackoff.length - 1)); + this.maxAttempts = Math.min(retryPolicy.maxAttempts, maxAttemptsLimit); + } else if (callConfig.methodConfig.hedgingPolicy) { + this.state = "HEDGING"; + this.maxAttempts = Math.min(callConfig.methodConfig.hedgingPolicy.maxAttempts, maxAttemptsLimit); + } else { + this.state = "TRANSPARENT_ONLY"; + this.maxAttempts = 1; + } + this.startTime = /* @__PURE__ */ new Date(); + } + getDeadlineInfo() { + if (this.underlyingCalls.length === 0) { + return []; + } + const deadlineInfo = []; + const latestCall = this.underlyingCalls[this.underlyingCalls.length - 1]; + if (this.underlyingCalls.length > 1) { + deadlineInfo.push(`previous attempts: ${this.underlyingCalls.length - 1}`); + } + if (latestCall.startTime > this.startTime) { + deadlineInfo.push(`time to current attempt start: ${(0, deadline_1.formatDateDifference)(this.startTime, latestCall.startTime)}`); + } + deadlineInfo.push(...latestCall.call.getDeadlineInfo()); + return deadlineInfo; + } + getCallNumber() { + return this.callNumber; + } + trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callNumber + "] " + text); + } + reportStatus(statusObject) { + this.trace("ended with status: code=" + statusObject.code + ' details="' + statusObject.details + '" start time=' + this.startTime.toISOString()); + this.bufferTracker.freeAll(this.callNumber); + this.writeBufferOffset = this.writeBufferOffset + this.writeBuffer.length; + this.writeBuffer = []; + process.nextTick(() => { + var _a; + (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onReceiveStatus({ + code: statusObject.code, + details: statusObject.details, + metadata: statusObject.metadata + }); + }); + } + cancelWithStatus(status, details) { + this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"'); + this.reportStatus({ code: status, details, metadata: new metadata_1.Metadata() }); + for (const { call } of this.underlyingCalls) { + call.cancelWithStatus(status, details); + } + } + getPeer() { + if (this.committedCallIndex !== null) { + return this.underlyingCalls[this.committedCallIndex].call.getPeer(); + } else { + return "unknown"; + } + } + getBufferEntry(messageIndex) { + var _a; + return (_a = this.writeBuffer[messageIndex - this.writeBufferOffset]) !== null && _a !== void 0 ? _a : { + entryType: "FREED", + allocated: false + }; + } + getNextBufferIndex() { + return this.writeBufferOffset + this.writeBuffer.length; + } + clearSentMessages() { + if (this.state !== "COMMITTED") { + return; + } + let earliestNeededMessageIndex; + if (this.underlyingCalls[this.committedCallIndex].state === "COMPLETED") { + earliestNeededMessageIndex = this.getNextBufferIndex(); + } else { + earliestNeededMessageIndex = this.underlyingCalls[this.committedCallIndex].nextMessageToSend; + } + for (let messageIndex = this.writeBufferOffset; messageIndex < earliestNeededMessageIndex; messageIndex++) { + const bufferEntry = this.getBufferEntry(messageIndex); + if (bufferEntry.allocated) { + this.bufferTracker.free(bufferEntry.message.message.length, this.callNumber); + } + } + this.writeBuffer = this.writeBuffer.slice(earliestNeededMessageIndex - this.writeBufferOffset); + this.writeBufferOffset = earliestNeededMessageIndex; + } + commitCall(index) { + var _a, _b; + if (this.state === "COMMITTED") { + return; + } + this.trace("Committing call [" + this.underlyingCalls[index].call.getCallNumber() + "] at index " + index); + this.state = "COMMITTED"; + (_b = (_a = this.callConfig).onCommitted) === null || _b === void 0 ? void 0 : _b.call(_a); + this.committedCallIndex = index; + for (let i = 0; i < this.underlyingCalls.length; i++) { + if (i === index) { + continue; + } + if (this.underlyingCalls[i].state === "COMPLETED") { + continue; + } + this.underlyingCalls[i].state = "COMPLETED"; + this.underlyingCalls[i].call.cancelWithStatus(constants_1.Status.CANCELLED, "Discarded in favor of other hedged attempt"); + } + this.clearSentMessages(); + } + commitCallWithMostMessages() { + if (this.state === "COMMITTED") { + return; + } + let mostMessages = -1; + let callWithMostMessages = -1; + for (const [index, childCall] of this.underlyingCalls.entries()) { + if (childCall.state === "ACTIVE" && childCall.nextMessageToSend > mostMessages) { + mostMessages = childCall.nextMessageToSend; + callWithMostMessages = index; + } + } + if (callWithMostMessages === -1) { + this.state = "TRANSPARENT_ONLY"; + } else { + this.commitCall(callWithMostMessages); + } + } + isStatusCodeInList(list, code) { + return list.some((value) => { + var _a; + return value === code || value.toString().toLowerCase() === ((_a = constants_1.Status[code]) === null || _a === void 0 ? void 0 : _a.toLowerCase()); + }); + } + getNextRetryJitter() { + return Math.random() * (1.2 - 0.8) + 0.8; + } + getNextRetryBackoffMs() { + var _a; + const retryPolicy = (_a = this.callConfig) === null || _a === void 0 ? void 0 : _a.methodConfig.retryPolicy; + if (!retryPolicy) { + return 0; + } + const jitter = this.getNextRetryJitter(); + const nextBackoffMs = jitter * this.nextRetryBackoffSec * 1e3; + const maxBackoffSec = Number(retryPolicy.maxBackoff.substring(0, retryPolicy.maxBackoff.length - 1)); + this.nextRetryBackoffSec = Math.min(this.nextRetryBackoffSec * retryPolicy.backoffMultiplier, maxBackoffSec); + return nextBackoffMs; + } + maybeRetryCall(pushback, callback) { + if (this.state !== "RETRY") { + callback(false); + return; + } + if (this.attempts >= this.maxAttempts) { + callback(false); + return; + } + let retryDelayMs; + if (pushback === null) { + retryDelayMs = this.getNextRetryBackoffMs(); + } else if (pushback < 0) { + this.state = "TRANSPARENT_ONLY"; + callback(false); + return; + } else { + retryDelayMs = pushback; + this.nextRetryBackoffSec = this.initialRetryBackoffSec; + } + setTimeout(() => { + var _a, _b; + if (this.state !== "RETRY") { + callback(false); + return; + } + if ((_b = (_a = this.retryThrottler) === null || _a === void 0 ? void 0 : _a.canRetryCall()) !== null && _b !== void 0 ? _b : true) { + callback(true); + this.attempts += 1; + this.startNewAttempt(); + } else { + this.trace("Retry attempt denied by throttling policy"); + callback(false); + } + }, retryDelayMs); + } + countActiveCalls() { + let count = 0; + for (const call of this.underlyingCalls) { + if ((call === null || call === void 0 ? void 0 : call.state) === "ACTIVE") { + count += 1; + } + } + return count; + } + handleProcessedStatus(status, callIndex, pushback) { + var _a, _b, _c; + switch (this.state) { + case "COMMITTED": + case "NO_RETRY": + case "TRANSPARENT_ONLY": + this.commitCall(callIndex); + this.reportStatus(status); + break; + case "HEDGING": + if (this.isStatusCodeInList((_a = this.callConfig.methodConfig.hedgingPolicy.nonFatalStatusCodes) !== null && _a !== void 0 ? _a : [], status.code)) { + (_b = this.retryThrottler) === null || _b === void 0 ? void 0 : _b.addCallFailed(); + let delayMs; + if (pushback === null) { + delayMs = 0; + } else if (pushback < 0) { + this.state = "TRANSPARENT_ONLY"; + this.commitCall(callIndex); + this.reportStatus(status); + return; + } else { + delayMs = pushback; + } + setTimeout(() => { + this.maybeStartHedgingAttempt(); + if (this.countActiveCalls() === 0) { + this.commitCall(callIndex); + this.reportStatus(status); + } + }, delayMs); + } else { + this.commitCall(callIndex); + this.reportStatus(status); + } + break; + case "RETRY": + if (this.isStatusCodeInList(this.callConfig.methodConfig.retryPolicy.retryableStatusCodes, status.code)) { + (_c = this.retryThrottler) === null || _c === void 0 ? void 0 : _c.addCallFailed(); + this.maybeRetryCall(pushback, (retried) => { + if (!retried) { + this.commitCall(callIndex); + this.reportStatus(status); + } + }); + } else { + this.commitCall(callIndex); + this.reportStatus(status); + } + break; + } + } + getPushback(metadata) { + const mdValue = metadata.get("grpc-retry-pushback-ms"); + if (mdValue.length === 0) { + return null; + } + try { + return parseInt(mdValue[0]); + } catch (e) { + return -1; + } + } + handleChildStatus(status, callIndex) { + var _a; + if (this.underlyingCalls[callIndex].state === "COMPLETED") { + return; + } + this.trace("state=" + this.state + " handling status with progress " + status.progress + " from child [" + this.underlyingCalls[callIndex].call.getCallNumber() + "] in state " + this.underlyingCalls[callIndex].state); + this.underlyingCalls[callIndex].state = "COMPLETED"; + if (status.code === constants_1.Status.OK) { + (_a = this.retryThrottler) === null || _a === void 0 ? void 0 : _a.addCallSucceeded(); + this.commitCall(callIndex); + this.reportStatus(status); + return; + } + if (this.state === "NO_RETRY") { + this.commitCall(callIndex); + this.reportStatus(status); + return; + } + if (this.state === "COMMITTED") { + this.reportStatus(status); + return; + } + const pushback = this.getPushback(status.metadata); + switch (status.progress) { + case "NOT_STARTED": + this.startNewAttempt(); + break; + case "REFUSED": + if (this.transparentRetryUsed) { + this.handleProcessedStatus(status, callIndex, pushback); + } else { + this.transparentRetryUsed = true; + this.startNewAttempt(); + } + break; + case "DROP": + this.commitCall(callIndex); + this.reportStatus(status); + break; + case "PROCESSED": + this.handleProcessedStatus(status, callIndex, pushback); + break; + } + } + maybeStartHedgingAttempt() { + if (this.state !== "HEDGING") { + return; + } + if (!this.callConfig.methodConfig.hedgingPolicy) { + return; + } + if (this.attempts >= this.maxAttempts) { + return; + } + this.attempts += 1; + this.startNewAttempt(); + this.maybeStartHedgingTimer(); + } + maybeStartHedgingTimer() { + var _a, _b, _c; + if (this.hedgingTimer) { + clearTimeout(this.hedgingTimer); + } + if (this.state !== "HEDGING") { + return; + } + if (!this.callConfig.methodConfig.hedgingPolicy) { + return; + } + const hedgingPolicy = this.callConfig.methodConfig.hedgingPolicy; + if (this.attempts >= this.maxAttempts) { + return; + } + const hedgingDelayString = (_a = hedgingPolicy.hedgingDelay) !== null && _a !== void 0 ? _a : "0s"; + const hedgingDelaySec = Number(hedgingDelayString.substring(0, hedgingDelayString.length - 1)); + this.hedgingTimer = setTimeout(() => { + this.maybeStartHedgingAttempt(); + }, hedgingDelaySec * 1e3); + (_c = (_b = this.hedgingTimer).unref) === null || _c === void 0 ? void 0 : _c.call(_b); + } + startNewAttempt() { + const child = this.channel.createLoadBalancingCall(this.callConfig, this.methodName, this.host, this.credentials, this.deadline); + this.trace("Created child call [" + child.getCallNumber() + "] for attempt " + this.attempts); + const index = this.underlyingCalls.length; + this.underlyingCalls.push({ + state: "ACTIVE", + call: child, + nextMessageToSend: 0, + startTime: /* @__PURE__ */ new Date() + }); + const previousAttempts = this.attempts - 1; + const initialMetadata = this.initialMetadata.clone(); + if (previousAttempts > 0) { + initialMetadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`); + } + let receivedMetadata = false; + child.start(initialMetadata, { + onReceiveMetadata: (metadata) => { + this.trace("Received metadata from child [" + child.getCallNumber() + "]"); + this.commitCall(index); + receivedMetadata = true; + if (previousAttempts > 0) { + metadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`); + } + if (this.underlyingCalls[index].state === "ACTIVE") { + this.listener.onReceiveMetadata(metadata); + } + }, + onReceiveMessage: (message) => { + this.trace("Received message from child [" + child.getCallNumber() + "]"); + this.commitCall(index); + if (this.underlyingCalls[index].state === "ACTIVE") { + this.listener.onReceiveMessage(message); + } + }, + onReceiveStatus: (status) => { + this.trace("Received status from child [" + child.getCallNumber() + "]"); + if (!receivedMetadata && previousAttempts > 0) { + status.metadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`); + } + this.handleChildStatus(status, index); + } + }); + this.sendNextChildMessage(index); + if (this.readStarted) { + child.startRead(); + } + } + start(metadata, listener) { + this.trace("start called"); + this.listener = listener; + this.initialMetadata = metadata; + this.attempts += 1; + this.startNewAttempt(); + this.maybeStartHedgingTimer(); + } + handleChildWriteCompleted(childIndex, messageIndex) { + var _a, _b; + (_b = (_a = this.getBufferEntry(messageIndex)).callback) === null || _b === void 0 ? void 0 : _b.call(_a); + this.clearSentMessages(); + const childCall = this.underlyingCalls[childIndex]; + childCall.nextMessageToSend += 1; + this.sendNextChildMessage(childIndex); + } + sendNextChildMessage(childIndex) { + const childCall = this.underlyingCalls[childIndex]; + if (childCall.state === "COMPLETED") { + return; + } + const messageIndex = childCall.nextMessageToSend; + if (this.getBufferEntry(messageIndex)) { + const bufferEntry = this.getBufferEntry(messageIndex); + switch (bufferEntry.entryType) { + case "MESSAGE": + childCall.call.sendMessageWithContext({ + callback: (error2) => { + this.handleChildWriteCompleted(childIndex, messageIndex); + } + }, bufferEntry.message.message); + const nextEntry = this.getBufferEntry(messageIndex + 1); + if (nextEntry.entryType === "HALF_CLOSE") { + this.trace("Sending halfClose immediately after message to child [" + childCall.call.getCallNumber() + "] - optimizing for unary/final message"); + childCall.nextMessageToSend += 1; + childCall.call.halfClose(); + } + break; + case "HALF_CLOSE": + childCall.nextMessageToSend += 1; + childCall.call.halfClose(); + break; + case "FREED": + break; + } + } + } + sendMessageWithContext(context3, message) { + this.trace("write() called with message of length " + message.length); + const writeObj = { + message, + flags: context3.flags + }; + const messageIndex = this.getNextBufferIndex(); + const bufferEntry = { + entryType: "MESSAGE", + message: writeObj, + allocated: this.bufferTracker.allocate(message.length, this.callNumber) + }; + this.writeBuffer.push(bufferEntry); + if (bufferEntry.allocated) { + process.nextTick(() => { + var _a; + (_a = context3.callback) === null || _a === void 0 ? void 0 : _a.call(context3); + }); + for (const [callIndex, call] of this.underlyingCalls.entries()) { + if (call.state === "ACTIVE" && call.nextMessageToSend === messageIndex) { + call.call.sendMessageWithContext({ + callback: (error2) => { + this.handleChildWriteCompleted(callIndex, messageIndex); + } + }, message); + } + } + } else { + this.commitCallWithMostMessages(); + if (this.committedCallIndex === null) { + return; + } + const call = this.underlyingCalls[this.committedCallIndex]; + bufferEntry.callback = context3.callback; + if (call.state === "ACTIVE" && call.nextMessageToSend === messageIndex) { + call.call.sendMessageWithContext({ + callback: (error2) => { + this.handleChildWriteCompleted(this.committedCallIndex, messageIndex); + } + }, message); + } + } + } + startRead() { + this.trace("startRead called"); + this.readStarted = true; + for (const underlyingCall of this.underlyingCalls) { + if ((underlyingCall === null || underlyingCall === void 0 ? void 0 : underlyingCall.state) === "ACTIVE") { + underlyingCall.call.startRead(); + } + } + } + halfClose() { + this.trace("halfClose called"); + const halfCloseIndex = this.getNextBufferIndex(); + this.writeBuffer.push({ + entryType: "HALF_CLOSE", + allocated: false + }); + for (const call of this.underlyingCalls) { + if ((call === null || call === void 0 ? void 0 : call.state) === "ACTIVE") { + if (call.nextMessageToSend === halfCloseIndex || call.nextMessageToSend === halfCloseIndex - 1) { + this.trace("Sending halfClose immediately to child [" + call.call.getCallNumber() + "] - all messages already sent"); + call.nextMessageToSend += 1; + call.call.halfClose(); + } + } + } + } + setCredentials(newCredentials) { + throw new Error("Method not implemented."); + } + getMethod() { + return this.methodName; + } + getHost() { + return this.host; + } + getAuthContext() { + if (this.committedCallIndex !== null) { + return this.underlyingCalls[this.committedCallIndex].call.getAuthContext(); + } else { + return null; + } + } + }; + exports2.RetryingCall = RetryingCall; + } +}); + +// node_modules/@grpc/grpc-js/build/src/subchannel-interface.js +var require_subchannel_interface = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/subchannel-interface.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.BaseSubchannelWrapper = void 0; + var BaseSubchannelWrapper = class { + constructor(child) { + this.child = child; + this.healthy = true; + this.healthListeners = /* @__PURE__ */ new Set(); + this.refcount = 0; + this.dataWatchers = /* @__PURE__ */ new Set(); + child.addHealthStateWatcher((childHealthy) => { + if (this.healthy) { + this.updateHealthListeners(); + } + }); + } + updateHealthListeners() { + for (const listener of this.healthListeners) { + listener(this.isHealthy()); + } + } + getConnectivityState() { + return this.child.getConnectivityState(); + } + addConnectivityStateListener(listener) { + this.child.addConnectivityStateListener(listener); + } + removeConnectivityStateListener(listener) { + this.child.removeConnectivityStateListener(listener); + } + startConnecting() { + this.child.startConnecting(); + } + getAddress() { + return this.child.getAddress(); + } + throttleKeepalive(newKeepaliveTime) { + this.child.throttleKeepalive(newKeepaliveTime); + } + ref() { + this.child.ref(); + this.refcount += 1; + } + unref() { + this.child.unref(); + this.refcount -= 1; + if (this.refcount === 0) { + this.destroy(); + } + } + destroy() { + for (const watcher of this.dataWatchers) { + watcher.destroy(); + } + } + getChannelzRef() { + return this.child.getChannelzRef(); + } + isHealthy() { + return this.healthy && this.child.isHealthy(); + } + addHealthStateWatcher(listener) { + this.healthListeners.add(listener); + } + removeHealthStateWatcher(listener) { + this.healthListeners.delete(listener); + } + addDataWatcher(dataWatcher) { + dataWatcher.setSubchannel(this.getRealSubchannel()); + this.dataWatchers.add(dataWatcher); + } + setHealthy(healthy) { + if (healthy !== this.healthy) { + this.healthy = healthy; + if (this.child.isHealthy()) { + this.updateHealthListeners(); + } + } + } + getRealSubchannel() { + return this.child.getRealSubchannel(); + } + realSubchannelEquals(other) { + return this.getRealSubchannel() === other.getRealSubchannel(); + } + getCallCredentials() { + return this.child.getCallCredentials(); + } + getChannel() { + return this.child.getChannel(); + } + }; + exports2.BaseSubchannelWrapper = BaseSubchannelWrapper; + } +}); + +// node_modules/@grpc/grpc-js/build/src/internal-channel.js +var require_internal_channel = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/internal-channel.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.InternalChannel = exports2.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = void 0; + var channel_credentials_1 = require_channel_credentials(); + var resolving_load_balancer_1 = require_resolving_load_balancer(); + var subchannel_pool_1 = require_subchannel_pool(); + var picker_1 = require_picker(); + var metadata_1 = require_metadata(); + var constants_1 = require_constants7(); + var filter_stack_1 = require_filter_stack(); + var compression_filter_1 = require_compression_filter(); + var resolver_1 = require_resolver(); + var logging_1 = require_logging(); + var http_proxy_1 = require_http_proxy(); + var uri_parser_1 = require_uri_parser(); + var connectivity_state_1 = require_connectivity_state(); + var channelz_1 = require_channelz(); + var load_balancing_call_1 = require_load_balancing_call(); + var deadline_1 = require_deadline(); + var resolving_call_1 = require_resolving_call(); + var call_number_1 = require_call_number(); + var control_plane_status_1 = require_control_plane_status(); + var retrying_call_1 = require_retrying_call(); + var subchannel_interface_1 = require_subchannel_interface(); + var MAX_TIMEOUT_TIME = 2147483647; + var MIN_IDLE_TIMEOUT_MS = 1e3; + var DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1e3; + var RETRY_THROTTLER_MAP = /* @__PURE__ */ new Map(); + var DEFAULT_RETRY_BUFFER_SIZE_BYTES = 1 << 24; + var DEFAULT_PER_RPC_RETRY_BUFFER_SIZE_BYTES = 1 << 20; + var ChannelSubchannelWrapper = class extends subchannel_interface_1.BaseSubchannelWrapper { + constructor(childSubchannel, channel) { + super(childSubchannel); + this.channel = channel; + this.refCount = 0; + this.subchannelStateListener = (subchannel, previousState, newState, keepaliveTime) => { + channel.throttleKeepalive(keepaliveTime); + }; + } + ref() { + if (this.refCount === 0) { + this.child.addConnectivityStateListener(this.subchannelStateListener); + this.channel.addWrappedSubchannel(this); + } + this.child.ref(); + this.refCount += 1; + } + unref() { + this.child.unref(); + this.refCount -= 1; + if (this.refCount <= 0) { + this.child.removeConnectivityStateListener(this.subchannelStateListener); + this.channel.removeWrappedSubchannel(this); + } + } + }; + var ShutdownPicker = class { + pick(pickArgs) { + return { + pickResultType: picker_1.PickResultType.DROP, + status: { + code: constants_1.Status.UNAVAILABLE, + details: "Channel closed before call started", + metadata: new metadata_1.Metadata() + }, + subchannel: null, + onCallStarted: null, + onCallEnded: null + }; + } + }; + exports2.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = "grpc.internal.no_subchannel"; + var ChannelzInfoTracker = class { + constructor(target) { + this.target = target; + this.trace = new channelz_1.ChannelzTrace(); + this.callTracker = new channelz_1.ChannelzCallTracker(); + this.childrenTracker = new channelz_1.ChannelzChildrenTracker(); + this.state = connectivity_state_1.ConnectivityState.IDLE; + } + getChannelzInfoCallback() { + return () => { + return { + target: this.target, + state: this.state, + trace: this.trace, + callTracker: this.callTracker, + children: this.childrenTracker.getChildLists() + }; + }; + } + }; + var InternalChannel = class { + constructor(target, credentials, options) { + var _a, _b, _c, _d, _e, _f; + this.credentials = credentials; + this.options = options; + this.connectivityState = connectivity_state_1.ConnectivityState.IDLE; + this.currentPicker = new picker_1.UnavailablePicker(); + this.configSelectionQueue = []; + this.pickQueue = []; + this.connectivityStateWatchers = []; + this.callRefTimer = null; + this.configSelector = null; + this.currentResolutionError = null; + this.wrappedSubchannels = /* @__PURE__ */ new Set(); + this.callCount = 0; + this.idleTimer = null; + this.channelzEnabled = true; + this.randomChannelId = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER); + if (typeof target !== "string") { + throw new TypeError("Channel target must be a string"); + } + if (!(credentials instanceof channel_credentials_1.ChannelCredentials)) { + throw new TypeError("Channel credentials must be a ChannelCredentials object"); + } + if (options) { + if (typeof options !== "object") { + throw new TypeError("Channel options must be an object"); + } + } + this.channelzInfoTracker = new ChannelzInfoTracker(target); + const originalTargetUri = (0, uri_parser_1.parseUri)(target); + if (originalTargetUri === null) { + throw new Error(`Could not parse target name "${target}"`); + } + const defaultSchemeMapResult = (0, resolver_1.mapUriDefaultScheme)(originalTargetUri); + if (defaultSchemeMapResult === null) { + throw new Error(`Could not find a default scheme for target name "${target}"`); + } + if (this.options["grpc.enable_channelz"] === 0) { + this.channelzEnabled = false; + } + this.channelzRef = (0, channelz_1.registerChannelzChannel)(target, this.channelzInfoTracker.getChannelzInfoCallback(), this.channelzEnabled); + if (this.channelzEnabled) { + this.channelzInfoTracker.trace.addTrace("CT_INFO", "Channel created"); + } + if (this.options["grpc.default_authority"]) { + this.defaultAuthority = this.options["grpc.default_authority"]; + } else { + this.defaultAuthority = (0, resolver_1.getDefaultAuthority)(defaultSchemeMapResult); + } + const proxyMapResult = (0, http_proxy_1.mapProxyName)(defaultSchemeMapResult, options); + this.target = proxyMapResult.target; + this.options = Object.assign({}, this.options, proxyMapResult.extraOptions); + this.subchannelPool = (0, subchannel_pool_1.getSubchannelPool)(((_a = this.options["grpc.use_local_subchannel_pool"]) !== null && _a !== void 0 ? _a : 0) === 0); + this.retryBufferTracker = new retrying_call_1.MessageBufferTracker((_b = this.options["grpc.retry_buffer_size"]) !== null && _b !== void 0 ? _b : DEFAULT_RETRY_BUFFER_SIZE_BYTES, (_c = this.options["grpc.per_rpc_retry_buffer_size"]) !== null && _c !== void 0 ? _c : DEFAULT_PER_RPC_RETRY_BUFFER_SIZE_BYTES); + this.keepaliveTime = (_d = this.options["grpc.keepalive_time_ms"]) !== null && _d !== void 0 ? _d : -1; + this.idleTimeoutMs = Math.max((_e = this.options["grpc.client_idle_timeout_ms"]) !== null && _e !== void 0 ? _e : DEFAULT_IDLE_TIMEOUT_MS, MIN_IDLE_TIMEOUT_MS); + const channelControlHelper = { + createSubchannel: (subchannelAddress, subchannelArgs) => { + const finalSubchannelArgs = {}; + for (const [key, value] of Object.entries(subchannelArgs)) { + if (!key.startsWith(exports2.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX)) { + finalSubchannelArgs[key] = value; + } + } + const subchannel = this.subchannelPool.getOrCreateSubchannel(this.target, subchannelAddress, finalSubchannelArgs, this.credentials); + subchannel.throttleKeepalive(this.keepaliveTime); + if (this.channelzEnabled) { + this.channelzInfoTracker.trace.addTrace("CT_INFO", "Created subchannel or used existing subchannel", subchannel.getChannelzRef()); + } + const wrappedSubchannel = new ChannelSubchannelWrapper(subchannel, this); + return wrappedSubchannel; + }, + updateState: (connectivityState, picker) => { + this.currentPicker = picker; + const queueCopy = this.pickQueue.slice(); + this.pickQueue = []; + if (queueCopy.length > 0) { + this.callRefTimerUnref(); + } + for (const call of queueCopy) { + call.doPick(); + } + this.updateState(connectivityState); + }, + requestReresolution: () => { + throw new Error("Resolving load balancer should never call requestReresolution"); + }, + addChannelzChild: (child) => { + if (this.channelzEnabled) { + this.channelzInfoTracker.childrenTracker.refChild(child); + } + }, + removeChannelzChild: (child) => { + if (this.channelzEnabled) { + this.channelzInfoTracker.childrenTracker.unrefChild(child); + } + } + }; + this.resolvingLoadBalancer = new resolving_load_balancer_1.ResolvingLoadBalancer(this.target, channelControlHelper, this.options, (serviceConfig, configSelector) => { + var _a2; + if (serviceConfig.retryThrottling) { + RETRY_THROTTLER_MAP.set(this.getTarget(), new retrying_call_1.RetryThrottler(serviceConfig.retryThrottling.maxTokens, serviceConfig.retryThrottling.tokenRatio, RETRY_THROTTLER_MAP.get(this.getTarget()))); + } else { + RETRY_THROTTLER_MAP.delete(this.getTarget()); + } + if (this.channelzEnabled) { + this.channelzInfoTracker.trace.addTrace("CT_INFO", "Address resolution succeeded"); + } + (_a2 = this.configSelector) === null || _a2 === void 0 ? void 0 : _a2.unref(); + this.configSelector = configSelector; + this.currentResolutionError = null; + process.nextTick(() => { + const localQueue = this.configSelectionQueue; + this.configSelectionQueue = []; + if (localQueue.length > 0) { + this.callRefTimerUnref(); + } + for (const call of localQueue) { + call.getConfig(); + } + }); + }, (status) => { + if (this.channelzEnabled) { + this.channelzInfoTracker.trace.addTrace("CT_WARNING", "Address resolution failed with code " + status.code + ' and details "' + status.details + '"'); + } + if (this.configSelectionQueue.length > 0) { + this.trace("Name resolution failed with calls queued for config selection"); + } + if (this.configSelector === null) { + this.currentResolutionError = Object.assign(Object.assign({}, (0, control_plane_status_1.restrictControlPlaneStatusCode)(status.code, status.details)), { metadata: status.metadata }); + } + const localQueue = this.configSelectionQueue; + this.configSelectionQueue = []; + if (localQueue.length > 0) { + this.callRefTimerUnref(); + } + for (const call of localQueue) { + call.reportResolverError(status); + } + }); + this.filterStackFactory = new filter_stack_1.FilterStackFactory([ + new compression_filter_1.CompressionFilterFactory(this, this.options) + ]); + this.trace("Channel constructed with options " + JSON.stringify(options, void 0, 2)); + const error2 = new Error(); + if ((0, logging_1.isTracerEnabled)("channel_stacktrace")) { + (0, logging_1.trace)(constants_1.LogVerbosity.DEBUG, "channel_stacktrace", "(" + this.channelzRef.id + ") Channel constructed \n" + ((_f = error2.stack) === null || _f === void 0 ? void 0 : _f.substring(error2.stack.indexOf("\n") + 1))); + } + this.lastActivityTimestamp = /* @__PURE__ */ new Date(); + } + trace(text, verbosityOverride) { + (0, logging_1.trace)(verbosityOverride !== null && verbosityOverride !== void 0 ? verbosityOverride : constants_1.LogVerbosity.DEBUG, "channel", "(" + this.channelzRef.id + ") " + (0, uri_parser_1.uriToString)(this.target) + " " + text); + } + callRefTimerRef() { + var _a, _b, _c, _d; + if (!this.callRefTimer) { + this.callRefTimer = setInterval(() => { + }, MAX_TIMEOUT_TIME); + } + if (!((_b = (_a = this.callRefTimer).hasRef) === null || _b === void 0 ? void 0 : _b.call(_a))) { + this.trace("callRefTimer.ref | configSelectionQueue.length=" + this.configSelectionQueue.length + " pickQueue.length=" + this.pickQueue.length); + (_d = (_c = this.callRefTimer).ref) === null || _d === void 0 ? void 0 : _d.call(_c); + } + } + callRefTimerUnref() { + var _a, _b, _c; + if (!((_a = this.callRefTimer) === null || _a === void 0 ? void 0 : _a.hasRef) || this.callRefTimer.hasRef()) { + this.trace("callRefTimer.unref | configSelectionQueue.length=" + this.configSelectionQueue.length + " pickQueue.length=" + this.pickQueue.length); + (_c = (_b = this.callRefTimer) === null || _b === void 0 ? void 0 : _b.unref) === null || _c === void 0 ? void 0 : _c.call(_b); + } + } + removeConnectivityStateWatcher(watcherObject) { + const watcherIndex = this.connectivityStateWatchers.findIndex((value) => value === watcherObject); + if (watcherIndex >= 0) { + this.connectivityStateWatchers.splice(watcherIndex, 1); + } + } + updateState(newState) { + (0, logging_1.trace)(constants_1.LogVerbosity.DEBUG, "connectivity_state", "(" + this.channelzRef.id + ") " + (0, uri_parser_1.uriToString)(this.target) + " " + connectivity_state_1.ConnectivityState[this.connectivityState] + " -> " + connectivity_state_1.ConnectivityState[newState]); + if (this.channelzEnabled) { + this.channelzInfoTracker.trace.addTrace("CT_INFO", "Connectivity state change to " + connectivity_state_1.ConnectivityState[newState]); + } + this.connectivityState = newState; + this.channelzInfoTracker.state = newState; + const watchersCopy = this.connectivityStateWatchers.slice(); + for (const watcherObject of watchersCopy) { + if (newState !== watcherObject.currentState) { + if (watcherObject.timer) { + clearTimeout(watcherObject.timer); + } + this.removeConnectivityStateWatcher(watcherObject); + watcherObject.callback(); + } + } + if (newState !== connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { + this.currentResolutionError = null; + } + } + throttleKeepalive(newKeepaliveTime) { + if (newKeepaliveTime > this.keepaliveTime) { + this.keepaliveTime = newKeepaliveTime; + for (const wrappedSubchannel of this.wrappedSubchannels) { + wrappedSubchannel.throttleKeepalive(newKeepaliveTime); + } + } + } + addWrappedSubchannel(wrappedSubchannel) { + this.wrappedSubchannels.add(wrappedSubchannel); + } + removeWrappedSubchannel(wrappedSubchannel) { + this.wrappedSubchannels.delete(wrappedSubchannel); + } + doPick(metadata, extraPickInfo) { + return this.currentPicker.pick({ + metadata, + extraPickInfo + }); + } + queueCallForPick(call) { + this.pickQueue.push(call); + this.callRefTimerRef(); + } + getConfig(method, metadata) { + if (this.connectivityState !== connectivity_state_1.ConnectivityState.SHUTDOWN) { + this.resolvingLoadBalancer.exitIdle(); + } + if (this.configSelector) { + return { + type: "SUCCESS", + config: this.configSelector.invoke(method, metadata, this.randomChannelId) + }; + } else { + if (this.currentResolutionError) { + return { + type: "ERROR", + error: this.currentResolutionError + }; + } else { + return { + type: "NONE" + }; + } + } + } + queueCallForConfig(call) { + this.configSelectionQueue.push(call); + this.callRefTimerRef(); + } + enterIdle() { + this.resolvingLoadBalancer.destroy(); + this.updateState(connectivity_state_1.ConnectivityState.IDLE); + this.currentPicker = new picker_1.QueuePicker(this.resolvingLoadBalancer); + if (this.idleTimer) { + clearTimeout(this.idleTimer); + this.idleTimer = null; + } + if (this.callRefTimer) { + clearInterval(this.callRefTimer); + this.callRefTimer = null; + } + } + startIdleTimeout(timeoutMs) { + var _a, _b; + this.idleTimer = setTimeout(() => { + if (this.callCount > 0) { + this.startIdleTimeout(this.idleTimeoutMs); + return; + } + const now = /* @__PURE__ */ new Date(); + const timeSinceLastActivity = now.valueOf() - this.lastActivityTimestamp.valueOf(); + if (timeSinceLastActivity >= this.idleTimeoutMs) { + this.trace("Idle timer triggered after " + this.idleTimeoutMs + "ms of inactivity"); + this.enterIdle(); + } else { + this.startIdleTimeout(this.idleTimeoutMs - timeSinceLastActivity); + } + }, timeoutMs); + (_b = (_a = this.idleTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); + } + maybeStartIdleTimer() { + if (this.connectivityState !== connectivity_state_1.ConnectivityState.SHUTDOWN && !this.idleTimer) { + this.startIdleTimeout(this.idleTimeoutMs); + } + } + onCallStart() { + if (this.channelzEnabled) { + this.channelzInfoTracker.callTracker.addCallStarted(); + } + this.callCount += 1; + } + onCallEnd(status) { + if (this.channelzEnabled) { + if (status.code === constants_1.Status.OK) { + this.channelzInfoTracker.callTracker.addCallSucceeded(); + } else { + this.channelzInfoTracker.callTracker.addCallFailed(); + } + } + this.callCount -= 1; + this.lastActivityTimestamp = /* @__PURE__ */ new Date(); + this.maybeStartIdleTimer(); + } + createLoadBalancingCall(callConfig, method, host, credentials, deadline) { + const callNumber = (0, call_number_1.getNextCallNumber)(); + this.trace("createLoadBalancingCall [" + callNumber + '] method="' + method + '"'); + return new load_balancing_call_1.LoadBalancingCall(this, callConfig, method, host, credentials, deadline, callNumber); + } + createRetryingCall(callConfig, method, host, credentials, deadline) { + const callNumber = (0, call_number_1.getNextCallNumber)(); + this.trace("createRetryingCall [" + callNumber + '] method="' + method + '"'); + return new retrying_call_1.RetryingCall(this, callConfig, method, host, credentials, deadline, callNumber, this.retryBufferTracker, RETRY_THROTTLER_MAP.get(this.getTarget())); + } + createResolvingCall(method, deadline, host, parentCall, propagateFlags) { + const callNumber = (0, call_number_1.getNextCallNumber)(); + this.trace("createResolvingCall [" + callNumber + '] method="' + method + '", deadline=' + (0, deadline_1.deadlineToString)(deadline)); + const finalOptions = { + deadline, + flags: propagateFlags !== null && propagateFlags !== void 0 ? propagateFlags : constants_1.Propagate.DEFAULTS, + host: host !== null && host !== void 0 ? host : this.defaultAuthority, + parentCall + }; + const call = new resolving_call_1.ResolvingCall(this, method, finalOptions, this.filterStackFactory.clone(), callNumber); + this.onCallStart(); + call.addStatusWatcher((status) => { + this.onCallEnd(status); + }); + return call; + } + close() { + var _a; + this.resolvingLoadBalancer.destroy(); + this.updateState(connectivity_state_1.ConnectivityState.SHUTDOWN); + this.currentPicker = new ShutdownPicker(); + for (const call of this.configSelectionQueue) { + call.cancelWithStatus(constants_1.Status.UNAVAILABLE, "Channel closed before call started"); + } + this.configSelectionQueue = []; + for (const call of this.pickQueue) { + call.cancelWithStatus(constants_1.Status.UNAVAILABLE, "Channel closed before call started"); + } + this.pickQueue = []; + if (this.callRefTimer) { + clearInterval(this.callRefTimer); + } + if (this.idleTimer) { + clearTimeout(this.idleTimer); + } + if (this.channelzEnabled) { + (0, channelz_1.unregisterChannelzRef)(this.channelzRef); + } + this.subchannelPool.unrefUnusedSubchannels(); + (_a = this.configSelector) === null || _a === void 0 ? void 0 : _a.unref(); + this.configSelector = null; + } + getTarget() { + return (0, uri_parser_1.uriToString)(this.target); + } + getConnectivityState(tryToConnect) { + const connectivityState = this.connectivityState; + if (tryToConnect) { + this.resolvingLoadBalancer.exitIdle(); + this.lastActivityTimestamp = /* @__PURE__ */ new Date(); + this.maybeStartIdleTimer(); + } + return connectivityState; + } + watchConnectivityState(currentState, deadline, callback) { + if (this.connectivityState === connectivity_state_1.ConnectivityState.SHUTDOWN) { + throw new Error("Channel has been shut down"); + } + let timer = null; + if (deadline !== Infinity) { + const deadlineDate = deadline instanceof Date ? deadline : new Date(deadline); + const now = /* @__PURE__ */ new Date(); + if (deadline === -Infinity || deadlineDate <= now) { + process.nextTick(callback, new Error("Deadline passed without connectivity state change")); + return; + } + timer = setTimeout(() => { + this.removeConnectivityStateWatcher(watcherObject); + callback(new Error("Deadline passed without connectivity state change")); + }, deadlineDate.getTime() - now.getTime()); + } + const watcherObject = { + currentState, + callback, + timer + }; + this.connectivityStateWatchers.push(watcherObject); + } + /** + * Get the channelz reference object for this channel. The returned value is + * garbage if channelz is disabled for this channel. + * @returns + */ + getChannelzRef() { + return this.channelzRef; + } + createCall(method, deadline, host, parentCall, propagateFlags) { + if (typeof method !== "string") { + throw new TypeError("Channel#createCall: method must be a string"); + } + if (!(typeof deadline === "number" || deadline instanceof Date)) { + throw new TypeError("Channel#createCall: deadline must be a number or Date"); + } + if (this.connectivityState === connectivity_state_1.ConnectivityState.SHUTDOWN) { + throw new Error("Channel has been shut down"); + } + return this.createResolvingCall(method, deadline, host, parentCall, propagateFlags); + } + getOptions() { + return this.options; + } + }; + exports2.InternalChannel = InternalChannel; + } +}); + +// node_modules/@grpc/grpc-js/build/src/channel.js +var require_channel = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/channel.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ChannelImplementation = void 0; + var channel_credentials_1 = require_channel_credentials(); + var internal_channel_1 = require_internal_channel(); + var ChannelImplementation = class { + constructor(target, credentials, options) { + if (typeof target !== "string") { + throw new TypeError("Channel target must be a string"); + } + if (!(credentials instanceof channel_credentials_1.ChannelCredentials)) { + throw new TypeError("Channel credentials must be a ChannelCredentials object"); + } + if (options) { + if (typeof options !== "object") { + throw new TypeError("Channel options must be an object"); + } + } + this.internalChannel = new internal_channel_1.InternalChannel(target, credentials, options); + } + close() { + this.internalChannel.close(); + } + getTarget() { + return this.internalChannel.getTarget(); + } + getConnectivityState(tryToConnect) { + return this.internalChannel.getConnectivityState(tryToConnect); + } + watchConnectivityState(currentState, deadline, callback) { + this.internalChannel.watchConnectivityState(currentState, deadline, callback); + } + /** + * Get the channelz reference object for this channel. The returned value is + * garbage if channelz is disabled for this channel. + * @returns + */ + getChannelzRef() { + return this.internalChannel.getChannelzRef(); + } + createCall(method, deadline, host, parentCall, propagateFlags) { + if (typeof method !== "string") { + throw new TypeError("Channel#createCall: method must be a string"); + } + if (!(typeof deadline === "number" || deadline instanceof Date)) { + throw new TypeError("Channel#createCall: deadline must be a number or Date"); + } + return this.internalChannel.createCall(method, deadline, host, parentCall, propagateFlags); + } + }; + exports2.ChannelImplementation = ChannelImplementation; + } +}); + +// node_modules/@grpc/grpc-js/build/src/server-call.js +var require_server_call = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/server-call.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ServerDuplexStreamImpl = exports2.ServerWritableStreamImpl = exports2.ServerReadableStreamImpl = exports2.ServerUnaryCallImpl = void 0; + exports2.serverErrorToStatus = serverErrorToStatus; + var events_1 = require("events"); + var stream_1 = require("stream"); + var constants_1 = require_constants7(); + var metadata_1 = require_metadata(); + function serverErrorToStatus(error2, overrideTrailers) { + var _a; + const status = { + code: constants_1.Status.UNKNOWN, + details: "message" in error2 ? error2.message : "Unknown Error", + metadata: (_a = overrideTrailers !== null && overrideTrailers !== void 0 ? overrideTrailers : error2.metadata) !== null && _a !== void 0 ? _a : null + }; + if ("code" in error2 && typeof error2.code === "number" && Number.isInteger(error2.code)) { + status.code = error2.code; + if ("details" in error2 && typeof error2.details === "string") { + status.details = error2.details; + } + } + return status; + } + var ServerUnaryCallImpl = class extends events_1.EventEmitter { + constructor(path, call, metadata, request2) { + super(); + this.path = path; + this.call = call; + this.metadata = metadata; + this.request = request2; + this.cancelled = false; + } + getPeer() { + return this.call.getPeer(); + } + sendMetadata(responseMetadata) { + this.call.sendMetadata(responseMetadata); + } + getDeadline() { + return this.call.getDeadline(); + } + getPath() { + return this.path; + } + getHost() { + return this.call.getHost(); + } + getAuthContext() { + return this.call.getAuthContext(); + } + getMetricsRecorder() { + return this.call.getMetricsRecorder(); + } + }; + exports2.ServerUnaryCallImpl = ServerUnaryCallImpl; + var ServerReadableStreamImpl = class extends stream_1.Readable { + constructor(path, call, metadata) { + super({ objectMode: true }); + this.path = path; + this.call = call; + this.metadata = metadata; + this.cancelled = false; + } + _read(size) { + this.call.startRead(); + } + getPeer() { + return this.call.getPeer(); + } + sendMetadata(responseMetadata) { + this.call.sendMetadata(responseMetadata); + } + getDeadline() { + return this.call.getDeadline(); + } + getPath() { + return this.path; + } + getHost() { + return this.call.getHost(); + } + getAuthContext() { + return this.call.getAuthContext(); + } + getMetricsRecorder() { + return this.call.getMetricsRecorder(); + } + }; + exports2.ServerReadableStreamImpl = ServerReadableStreamImpl; + var ServerWritableStreamImpl = class extends stream_1.Writable { + constructor(path, call, metadata, request2) { + super({ objectMode: true }); + this.path = path; + this.call = call; + this.metadata = metadata; + this.request = request2; + this.pendingStatus = { + code: constants_1.Status.OK, + details: "OK" + }; + this.cancelled = false; + this.trailingMetadata = new metadata_1.Metadata(); + this.on("error", (err) => { + this.pendingStatus = serverErrorToStatus(err); + this.end(); + }); + } + getPeer() { + return this.call.getPeer(); + } + sendMetadata(responseMetadata) { + this.call.sendMetadata(responseMetadata); + } + getDeadline() { + return this.call.getDeadline(); + } + getPath() { + return this.path; + } + getHost() { + return this.call.getHost(); + } + getAuthContext() { + return this.call.getAuthContext(); + } + getMetricsRecorder() { + return this.call.getMetricsRecorder(); + } + _write(chunk, encoding, callback) { + this.call.sendMessage(chunk, callback); + } + _final(callback) { + var _a; + callback(null); + this.call.sendStatus(Object.assign(Object.assign({}, this.pendingStatus), { metadata: (_a = this.pendingStatus.metadata) !== null && _a !== void 0 ? _a : this.trailingMetadata })); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + end(metadata) { + if (metadata) { + this.trailingMetadata = metadata; + } + return super.end(); + } + }; + exports2.ServerWritableStreamImpl = ServerWritableStreamImpl; + var ServerDuplexStreamImpl = class extends stream_1.Duplex { + constructor(path, call, metadata) { + super({ objectMode: true }); + this.path = path; + this.call = call; + this.metadata = metadata; + this.pendingStatus = { + code: constants_1.Status.OK, + details: "OK" + }; + this.cancelled = false; + this.trailingMetadata = new metadata_1.Metadata(); + this.on("error", (err) => { + this.pendingStatus = serverErrorToStatus(err); + this.end(); + }); + } + getPeer() { + return this.call.getPeer(); + } + sendMetadata(responseMetadata) { + this.call.sendMetadata(responseMetadata); + } + getDeadline() { + return this.call.getDeadline(); + } + getPath() { + return this.path; + } + getHost() { + return this.call.getHost(); + } + getAuthContext() { + return this.call.getAuthContext(); + } + getMetricsRecorder() { + return this.call.getMetricsRecorder(); + } + _read(size) { + this.call.startRead(); + } + _write(chunk, encoding, callback) { + this.call.sendMessage(chunk, callback); + } + _final(callback) { + var _a; + callback(null); + this.call.sendStatus(Object.assign(Object.assign({}, this.pendingStatus), { metadata: (_a = this.pendingStatus.metadata) !== null && _a !== void 0 ? _a : this.trailingMetadata })); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + end(metadata) { + if (metadata) { + this.trailingMetadata = metadata; + } + return super.end(); + } + }; + exports2.ServerDuplexStreamImpl = ServerDuplexStreamImpl; + } +}); + +// node_modules/@grpc/grpc-js/build/src/server-credentials.js +var require_server_credentials = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/server-credentials.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ServerCredentials = void 0; + exports2.createCertificateProviderServerCredentials = createCertificateProviderServerCredentials; + exports2.createServerCredentialsWithInterceptors = createServerCredentialsWithInterceptors; + var tls_helpers_1 = require_tls_helpers(); + var ServerCredentials = class { + constructor(serverConstructorOptions, contextOptions) { + this.serverConstructorOptions = serverConstructorOptions; + this.watchers = /* @__PURE__ */ new Set(); + this.latestContextOptions = null; + this.latestContextOptions = contextOptions !== null && contextOptions !== void 0 ? contextOptions : null; + } + _addWatcher(watcher) { + this.watchers.add(watcher); + } + _removeWatcher(watcher) { + this.watchers.delete(watcher); + } + getWatcherCount() { + return this.watchers.size; + } + updateSecureContextOptions(options) { + this.latestContextOptions = options; + for (const watcher of this.watchers) { + watcher(this.latestContextOptions); + } + } + _isSecure() { + return this.serverConstructorOptions !== null; + } + _getSecureContextOptions() { + return this.latestContextOptions; + } + _getConstructorOptions() { + return this.serverConstructorOptions; + } + _getInterceptors() { + return []; + } + static createInsecure() { + return new InsecureServerCredentials(); + } + static createSsl(rootCerts, keyCertPairs, checkClientCertificate = false) { + var _a; + if (rootCerts !== null && !Buffer.isBuffer(rootCerts)) { + throw new TypeError("rootCerts must be null or a Buffer"); + } + if (!Array.isArray(keyCertPairs)) { + throw new TypeError("keyCertPairs must be an array"); + } + if (typeof checkClientCertificate !== "boolean") { + throw new TypeError("checkClientCertificate must be a boolean"); + } + const cert = []; + const key = []; + for (let i = 0; i < keyCertPairs.length; i++) { + const pair = keyCertPairs[i]; + if (pair === null || typeof pair !== "object") { + throw new TypeError(`keyCertPair[${i}] must be an object`); + } + if (!Buffer.isBuffer(pair.private_key)) { + throw new TypeError(`keyCertPair[${i}].private_key must be a Buffer`); + } + if (!Buffer.isBuffer(pair.cert_chain)) { + throw new TypeError(`keyCertPair[${i}].cert_chain must be a Buffer`); + } + cert.push(pair.cert_chain); + key.push(pair.private_key); + } + return new SecureServerCredentials({ + requestCert: checkClientCertificate, + ciphers: tls_helpers_1.CIPHER_SUITES + }, { + ca: (_a = rootCerts !== null && rootCerts !== void 0 ? rootCerts : (0, tls_helpers_1.getDefaultRootsData)()) !== null && _a !== void 0 ? _a : void 0, + cert, + key + }); + } + }; + exports2.ServerCredentials = ServerCredentials; + var InsecureServerCredentials = class _InsecureServerCredentials extends ServerCredentials { + constructor() { + super(null); + } + _getSettings() { + return null; + } + _equals(other) { + return other instanceof _InsecureServerCredentials; + } + }; + var SecureServerCredentials = class _SecureServerCredentials extends ServerCredentials { + constructor(constructorOptions, contextOptions) { + super(constructorOptions, contextOptions); + this.options = Object.assign(Object.assign({}, constructorOptions), contextOptions); + } + /** + * Checks equality by checking the options that are actually set by + * createSsl. + * @param other + * @returns + */ + _equals(other) { + if (this === other) { + return true; + } + if (!(other instanceof _SecureServerCredentials)) { + return false; + } + if (Buffer.isBuffer(this.options.ca) && Buffer.isBuffer(other.options.ca)) { + if (!this.options.ca.equals(other.options.ca)) { + return false; + } + } else { + if (this.options.ca !== other.options.ca) { + return false; + } + } + if (Array.isArray(this.options.cert) && Array.isArray(other.options.cert)) { + if (this.options.cert.length !== other.options.cert.length) { + return false; + } + for (let i = 0; i < this.options.cert.length; i++) { + const thisCert = this.options.cert[i]; + const otherCert = other.options.cert[i]; + if (Buffer.isBuffer(thisCert) && Buffer.isBuffer(otherCert)) { + if (!thisCert.equals(otherCert)) { + return false; + } + } else { + if (thisCert !== otherCert) { + return false; + } + } + } + } else { + if (this.options.cert !== other.options.cert) { + return false; + } + } + if (Array.isArray(this.options.key) && Array.isArray(other.options.key)) { + if (this.options.key.length !== other.options.key.length) { + return false; + } + for (let i = 0; i < this.options.key.length; i++) { + const thisKey = this.options.key[i]; + const otherKey = other.options.key[i]; + if (Buffer.isBuffer(thisKey) && Buffer.isBuffer(otherKey)) { + if (!thisKey.equals(otherKey)) { + return false; + } + } else { + if (thisKey !== otherKey) { + return false; + } + } + } + } else { + if (this.options.key !== other.options.key) { + return false; + } + } + if (this.options.requestCert !== other.options.requestCert) { + return false; + } + return true; + } + }; + var CertificateProviderServerCredentials = class _CertificateProviderServerCredentials extends ServerCredentials { + constructor(identityCertificateProvider, caCertificateProvider, requireClientCertificate) { + super({ + requestCert: caCertificateProvider !== null, + rejectUnauthorized: requireClientCertificate, + ciphers: tls_helpers_1.CIPHER_SUITES + }); + this.identityCertificateProvider = identityCertificateProvider; + this.caCertificateProvider = caCertificateProvider; + this.requireClientCertificate = requireClientCertificate; + this.latestCaUpdate = null; + this.latestIdentityUpdate = null; + this.caCertificateUpdateListener = this.handleCaCertificateUpdate.bind(this); + this.identityCertificateUpdateListener = this.handleIdentityCertitificateUpdate.bind(this); + } + _addWatcher(watcher) { + var _a; + if (this.getWatcherCount() === 0) { + (_a = this.caCertificateProvider) === null || _a === void 0 ? void 0 : _a.addCaCertificateListener(this.caCertificateUpdateListener); + this.identityCertificateProvider.addIdentityCertificateListener(this.identityCertificateUpdateListener); + } + super._addWatcher(watcher); + } + _removeWatcher(watcher) { + var _a; + super._removeWatcher(watcher); + if (this.getWatcherCount() === 0) { + (_a = this.caCertificateProvider) === null || _a === void 0 ? void 0 : _a.removeCaCertificateListener(this.caCertificateUpdateListener); + this.identityCertificateProvider.removeIdentityCertificateListener(this.identityCertificateUpdateListener); + } + } + _equals(other) { + if (this === other) { + return true; + } + if (!(other instanceof _CertificateProviderServerCredentials)) { + return false; + } + return this.caCertificateProvider === other.caCertificateProvider && this.identityCertificateProvider === other.identityCertificateProvider && this.requireClientCertificate === other.requireClientCertificate; + } + calculateSecureContextOptions() { + var _a; + if (this.latestIdentityUpdate === null) { + return null; + } + if (this.caCertificateProvider !== null && this.latestCaUpdate === null) { + return null; + } + return { + ca: (_a = this.latestCaUpdate) === null || _a === void 0 ? void 0 : _a.caCertificate, + cert: [this.latestIdentityUpdate.certificate], + key: [this.latestIdentityUpdate.privateKey] + }; + } + finalizeUpdate() { + const secureContextOptions = this.calculateSecureContextOptions(); + this.updateSecureContextOptions(secureContextOptions); + } + handleCaCertificateUpdate(update) { + this.latestCaUpdate = update; + this.finalizeUpdate(); + } + handleIdentityCertitificateUpdate(update) { + this.latestIdentityUpdate = update; + this.finalizeUpdate(); + } + }; + function createCertificateProviderServerCredentials(caCertificateProvider, identityCertificateProvider, requireClientCertificate) { + return new CertificateProviderServerCredentials(caCertificateProvider, identityCertificateProvider, requireClientCertificate); + } + var InterceptorServerCredentials = class _InterceptorServerCredentials extends ServerCredentials { + constructor(childCredentials, interceptors) { + super({}); + this.childCredentials = childCredentials; + this.interceptors = interceptors; + } + _isSecure() { + return this.childCredentials._isSecure(); + } + _equals(other) { + if (!(other instanceof _InterceptorServerCredentials)) { + return false; + } + if (!this.childCredentials._equals(other.childCredentials)) { + return false; + } + if (this.interceptors.length !== other.interceptors.length) { + return false; + } + for (let i = 0; i < this.interceptors.length; i++) { + if (this.interceptors[i] !== other.interceptors[i]) { + return false; + } + } + return true; + } + _getInterceptors() { + return this.interceptors; + } + _addWatcher(watcher) { + this.childCredentials._addWatcher(watcher); + } + _removeWatcher(watcher) { + this.childCredentials._removeWatcher(watcher); + } + _getConstructorOptions() { + return this.childCredentials._getConstructorOptions(); + } + _getSecureContextOptions() { + return this.childCredentials._getSecureContextOptions(); + } + }; + function createServerCredentialsWithInterceptors(credentials, interceptors) { + return new InterceptorServerCredentials(credentials, interceptors); + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/duration.js +var require_duration = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/duration.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.durationMessageToDuration = durationMessageToDuration; + exports2.msToDuration = msToDuration; + exports2.durationToMs = durationToMs; + exports2.isDuration = isDuration; + exports2.isDurationMessage = isDurationMessage; + exports2.parseDuration = parseDuration; + exports2.durationToString = durationToString; + function durationMessageToDuration(message) { + return { + seconds: Number.parseInt(message.seconds), + nanos: message.nanos + }; + } + function msToDuration(millis) { + return { + seconds: millis / 1e3 | 0, + nanos: millis % 1e3 * 1e6 | 0 + }; + } + function durationToMs(duration) { + return duration.seconds * 1e3 + duration.nanos / 1e6 | 0; + } + function isDuration(value) { + return typeof value.seconds === "number" && typeof value.nanos === "number"; + } + function isDurationMessage(value) { + return typeof value.seconds === "string" && typeof value.nanos === "number"; + } + var durationRegex = /^(\d+)(?:\.(\d+))?s$/; + function parseDuration(value) { + const match = value.match(durationRegex); + if (!match) { + return null; + } + return { + seconds: Number.parseInt(match[1], 10), + nanos: match[2] ? Number.parseInt(match[2].padEnd(9, "0"), 10) : 0 + }; + } + function durationToString(duration) { + if (duration.nanos === 0) { + return `${duration.seconds}s`; + } + let scaleFactor; + if (duration.nanos % 1e6 === 0) { + scaleFactor = 1e6; + } else if (duration.nanos % 1e3 === 0) { + scaleFactor = 1e3; + } else { + scaleFactor = 1; + } + return `${duration.seconds}.${duration.nanos / scaleFactor}s`; + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/orca.js +var require_orca = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/orca.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.OrcaOobMetricsSubchannelWrapper = exports2.GRPC_METRICS_HEADER = exports2.ServerMetricRecorder = exports2.PerRequestMetricRecorder = void 0; + exports2.createOrcaClient = createOrcaClient; + exports2.createMetricsReader = createMetricsReader; + var make_client_1 = require_make_client(); + var duration_1 = require_duration(); + var channel_credentials_1 = require_channel_credentials(); + var subchannel_interface_1 = require_subchannel_interface(); + var constants_1 = require_constants7(); + var backoff_timeout_1 = require_backoff_timeout(); + var connectivity_state_1 = require_connectivity_state(); + var loadedOrcaProto = null; + function loadOrcaProto() { + if (loadedOrcaProto) { + return loadedOrcaProto; + } + const loaderLoadSync = require_src3().loadSync; + const loadedProto = loaderLoadSync("xds/service/orca/v3/orca.proto", { + keepCase: true, + longs: String, + enums: String, + defaults: true, + oneofs: true, + includeDirs: [ + `${__dirname}/../../proto/xds`, + `${__dirname}/../../proto/protoc-gen-validate` + ] + }); + return (0, make_client_1.loadPackageDefinition)(loadedProto); + } + var PerRequestMetricRecorder = class { + constructor() { + this.message = {}; + } + /** + * Records a request cost metric measurement for the call. + * @param name + * @param value + */ + recordRequestCostMetric(name, value) { + if (!this.message.request_cost) { + this.message.request_cost = {}; + } + this.message.request_cost[name] = value; + } + /** + * Records a request cost metric measurement for the call. + * @param name + * @param value + */ + recordUtilizationMetric(name, value) { + if (!this.message.utilization) { + this.message.utilization = {}; + } + this.message.utilization[name] = value; + } + /** + * Records an opaque named metric measurement for the call. + * @param name + * @param value + */ + recordNamedMetric(name, value) { + if (!this.message.named_metrics) { + this.message.named_metrics = {}; + } + this.message.named_metrics[name] = value; + } + /** + * Records the CPU utilization metric measurement for the call. + * @param value + */ + recordCPUUtilizationMetric(value) { + this.message.cpu_utilization = value; + } + /** + * Records the memory utilization metric measurement for the call. + * @param value + */ + recordMemoryUtilizationMetric(value) { + this.message.mem_utilization = value; + } + /** + * Records the memory utilization metric measurement for the call. + * @param value + */ + recordApplicationUtilizationMetric(value) { + this.message.application_utilization = value; + } + /** + * Records the queries per second measurement. + * @param value + */ + recordQpsMetric(value) { + this.message.rps_fractional = value; + } + /** + * Records the errors per second measurement. + * @param value + */ + recordEpsMetric(value) { + this.message.eps = value; + } + serialize() { + const orcaProto = loadOrcaProto(); + return orcaProto.xds.data.orca.v3.OrcaLoadReport.serialize(this.message); + } + }; + exports2.PerRequestMetricRecorder = PerRequestMetricRecorder; + var DEFAULT_REPORT_INTERVAL_MS = 3e4; + var ServerMetricRecorder = class { + constructor() { + this.message = {}; + this.serviceImplementation = { + StreamCoreMetrics: (call) => { + const reportInterval = call.request.report_interval ? (0, duration_1.durationToMs)((0, duration_1.durationMessageToDuration)(call.request.report_interval)) : DEFAULT_REPORT_INTERVAL_MS; + const reportTimer = setInterval(() => { + call.write(this.message); + }, reportInterval); + call.on("cancelled", () => { + clearInterval(reportTimer); + }); + } + }; + } + putUtilizationMetric(name, value) { + if (!this.message.utilization) { + this.message.utilization = {}; + } + this.message.utilization[name] = value; + } + setAllUtilizationMetrics(metrics) { + this.message.utilization = Object.assign({}, metrics); + } + deleteUtilizationMetric(name) { + var _a; + (_a = this.message.utilization) === null || _a === void 0 ? true : delete _a[name]; + } + setCpuUtilizationMetric(value) { + this.message.cpu_utilization = value; + } + deleteCpuUtilizationMetric() { + delete this.message.cpu_utilization; + } + setApplicationUtilizationMetric(value) { + this.message.application_utilization = value; + } + deleteApplicationUtilizationMetric() { + delete this.message.application_utilization; + } + setQpsMetric(value) { + this.message.rps_fractional = value; + } + deleteQpsMetric() { + delete this.message.rps_fractional; + } + setEpsMetric(value) { + this.message.eps = value; + } + deleteEpsMetric() { + delete this.message.eps; + } + addToServer(server) { + const serviceDefinition = loadOrcaProto().xds.service.orca.v3.OpenRcaService.service; + server.addService(serviceDefinition, this.serviceImplementation); + } + }; + exports2.ServerMetricRecorder = ServerMetricRecorder; + function createOrcaClient(channel) { + const ClientClass = loadOrcaProto().xds.service.orca.v3.OpenRcaService; + return new ClientClass("unused", channel_credentials_1.ChannelCredentials.createInsecure(), { channelOverride: channel }); + } + exports2.GRPC_METRICS_HEADER = "endpoint-load-metrics-bin"; + var PARSED_LOAD_REPORT_KEY = "grpc_orca_load_report"; + function createMetricsReader(listener, previousOnCallEnded) { + return (code, details, metadata) => { + let parsedLoadReport = metadata.getOpaque(PARSED_LOAD_REPORT_KEY); + if (parsedLoadReport) { + listener(parsedLoadReport); + } else { + const serializedLoadReport = metadata.get(exports2.GRPC_METRICS_HEADER); + if (serializedLoadReport.length > 0) { + const orcaProto = loadOrcaProto(); + parsedLoadReport = orcaProto.xds.data.orca.v3.OrcaLoadReport.deserialize(serializedLoadReport[0]); + listener(parsedLoadReport); + metadata.setOpaque(PARSED_LOAD_REPORT_KEY, parsedLoadReport); + } + } + if (previousOnCallEnded) { + previousOnCallEnded(code, details, metadata); + } + }; + } + var DATA_PRODUCER_KEY = "orca_oob_metrics"; + var OobMetricsDataWatcher = class { + constructor(metricsListener, intervalMs) { + this.metricsListener = metricsListener; + this.intervalMs = intervalMs; + this.dataProducer = null; + } + setSubchannel(subchannel) { + const producer = subchannel.getOrCreateDataProducer(DATA_PRODUCER_KEY, createOobMetricsDataProducer); + this.dataProducer = producer; + producer.addDataWatcher(this); + } + destroy() { + var _a; + (_a = this.dataProducer) === null || _a === void 0 ? void 0 : _a.removeDataWatcher(this); + } + getInterval() { + return this.intervalMs; + } + onMetricsUpdate(metrics) { + this.metricsListener(metrics); + } + }; + var OobMetricsDataProducer = class { + constructor(subchannel) { + this.subchannel = subchannel; + this.dataWatchers = /* @__PURE__ */ new Set(); + this.orcaSupported = true; + this.metricsCall = null; + this.currentInterval = Infinity; + this.backoffTimer = new backoff_timeout_1.BackoffTimeout(() => this.updateMetricsSubscription()); + this.subchannelStateListener = () => this.updateMetricsSubscription(); + const channel = subchannel.getChannel(); + this.client = createOrcaClient(channel); + subchannel.addConnectivityStateListener(this.subchannelStateListener); + } + addDataWatcher(dataWatcher) { + this.dataWatchers.add(dataWatcher); + this.updateMetricsSubscription(); + } + removeDataWatcher(dataWatcher) { + var _a; + this.dataWatchers.delete(dataWatcher); + if (this.dataWatchers.size === 0) { + this.subchannel.removeDataProducer(DATA_PRODUCER_KEY); + (_a = this.metricsCall) === null || _a === void 0 ? void 0 : _a.cancel(); + this.metricsCall = null; + this.client.close(); + this.subchannel.removeConnectivityStateListener(this.subchannelStateListener); + } else { + this.updateMetricsSubscription(); + } + } + updateMetricsSubscription() { + var _a; + if (this.dataWatchers.size === 0 || !this.orcaSupported || this.subchannel.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) { + return; + } + const newInterval = Math.min(...Array.from(this.dataWatchers).map((watcher) => watcher.getInterval())); + if (!this.metricsCall || newInterval !== this.currentInterval) { + (_a = this.metricsCall) === null || _a === void 0 ? void 0 : _a.cancel(); + this.currentInterval = newInterval; + const metricsCall = this.client.streamCoreMetrics({ report_interval: (0, duration_1.msToDuration)(newInterval) }); + this.metricsCall = metricsCall; + metricsCall.on("data", (report) => { + this.dataWatchers.forEach((watcher) => { + watcher.onMetricsUpdate(report); + }); + }); + metricsCall.on("error", (error2) => { + this.metricsCall = null; + if (error2.code === constants_1.Status.UNIMPLEMENTED) { + this.orcaSupported = false; + return; + } + if (error2.code === constants_1.Status.CANCELLED) { + return; + } + this.backoffTimer.runOnce(); + }); + } + } + }; + var OrcaOobMetricsSubchannelWrapper = class extends subchannel_interface_1.BaseSubchannelWrapper { + constructor(child, metricsListener, intervalMs) { + super(child); + this.addDataWatcher(new OobMetricsDataWatcher(metricsListener, intervalMs)); + } + getWrappedSubchannel() { + return this.child; + } + }; + exports2.OrcaOobMetricsSubchannelWrapper = OrcaOobMetricsSubchannelWrapper; + function createOobMetricsDataProducer(subchannel) { + return new OobMetricsDataProducer(subchannel); + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/server-interceptors.js +var require_server_interceptors = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/server-interceptors.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.BaseServerInterceptingCall = exports2.ServerInterceptingCall = exports2.ResponderBuilder = exports2.ServerListenerBuilder = void 0; + exports2.isInterceptingServerListener = isInterceptingServerListener; + exports2.getServerInterceptingCall = getServerInterceptingCall; + var metadata_1 = require_metadata(); + var constants_1 = require_constants7(); + var http2 = require("http2"); + var error_1 = require_error(); + var zlib = require("zlib"); + var stream_decoder_1 = require_stream_decoder(); + var logging = require_logging(); + var tls_1 = require("tls"); + var orca_1 = require_orca(); + var TRACER_NAME = "server_call"; + function trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); + } + var ServerListenerBuilder = class { + constructor() { + this.metadata = void 0; + this.message = void 0; + this.halfClose = void 0; + this.cancel = void 0; + } + withOnReceiveMetadata(onReceiveMetadata) { + this.metadata = onReceiveMetadata; + return this; + } + withOnReceiveMessage(onReceiveMessage) { + this.message = onReceiveMessage; + return this; + } + withOnReceiveHalfClose(onReceiveHalfClose) { + this.halfClose = onReceiveHalfClose; + return this; + } + withOnCancel(onCancel) { + this.cancel = onCancel; + return this; + } + build() { + return { + onReceiveMetadata: this.metadata, + onReceiveMessage: this.message, + onReceiveHalfClose: this.halfClose, + onCancel: this.cancel + }; + } + }; + exports2.ServerListenerBuilder = ServerListenerBuilder; + function isInterceptingServerListener(listener) { + return listener.onReceiveMetadata !== void 0 && listener.onReceiveMetadata.length === 1; + } + var InterceptingServerListenerImpl = class { + constructor(listener, nextListener) { + this.listener = listener; + this.nextListener = nextListener; + this.cancelled = false; + this.processingMetadata = false; + this.hasPendingMessage = false; + this.pendingMessage = null; + this.processingMessage = false; + this.hasPendingHalfClose = false; + } + processPendingMessage() { + if (this.hasPendingMessage) { + this.nextListener.onReceiveMessage(this.pendingMessage); + this.pendingMessage = null; + this.hasPendingMessage = false; + } + } + processPendingHalfClose() { + if (this.hasPendingHalfClose) { + this.nextListener.onReceiveHalfClose(); + this.hasPendingHalfClose = false; + } + } + onReceiveMetadata(metadata) { + if (this.cancelled) { + return; + } + this.processingMetadata = true; + this.listener.onReceiveMetadata(metadata, (interceptedMetadata) => { + this.processingMetadata = false; + if (this.cancelled) { + return; + } + this.nextListener.onReceiveMetadata(interceptedMetadata); + this.processPendingMessage(); + this.processPendingHalfClose(); + }); + } + onReceiveMessage(message) { + if (this.cancelled) { + return; + } + this.processingMessage = true; + this.listener.onReceiveMessage(message, (msg) => { + this.processingMessage = false; + if (this.cancelled) { + return; + } + if (this.processingMetadata) { + this.pendingMessage = msg; + this.hasPendingMessage = true; + } else { + this.nextListener.onReceiveMessage(msg); + this.processPendingHalfClose(); + } + }); + } + onReceiveHalfClose() { + if (this.cancelled) { + return; + } + this.listener.onReceiveHalfClose(() => { + if (this.cancelled) { + return; + } + if (this.processingMetadata || this.processingMessage) { + this.hasPendingHalfClose = true; + } else { + this.nextListener.onReceiveHalfClose(); + } + }); + } + onCancel() { + this.cancelled = true; + this.listener.onCancel(); + this.nextListener.onCancel(); + } + }; + var ResponderBuilder = class { + constructor() { + this.start = void 0; + this.metadata = void 0; + this.message = void 0; + this.status = void 0; + } + withStart(start) { + this.start = start; + return this; + } + withSendMetadata(sendMetadata) { + this.metadata = sendMetadata; + return this; + } + withSendMessage(sendMessage) { + this.message = sendMessage; + return this; + } + withSendStatus(sendStatus) { + this.status = sendStatus; + return this; + } + build() { + return { + start: this.start, + sendMetadata: this.metadata, + sendMessage: this.message, + sendStatus: this.status + }; + } + }; + exports2.ResponderBuilder = ResponderBuilder; + var defaultServerListener = { + onReceiveMetadata: (metadata, next) => { + next(metadata); + }, + onReceiveMessage: (message, next) => { + next(message); + }, + onReceiveHalfClose: (next) => { + next(); + }, + onCancel: () => { + } + }; + var defaultResponder = { + start: (next) => { + next(); + }, + sendMetadata: (metadata, next) => { + next(metadata); + }, + sendMessage: (message, next) => { + next(message); + }, + sendStatus: (status, next) => { + next(status); + } + }; + var ServerInterceptingCall = class { + constructor(nextCall, responder) { + var _a, _b, _c, _d; + this.nextCall = nextCall; + this.processingMetadata = false; + this.sentMetadata = false; + this.processingMessage = false; + this.pendingMessage = null; + this.pendingMessageCallback = null; + this.pendingStatus = null; + this.responder = { + start: (_a = responder === null || responder === void 0 ? void 0 : responder.start) !== null && _a !== void 0 ? _a : defaultResponder.start, + sendMetadata: (_b = responder === null || responder === void 0 ? void 0 : responder.sendMetadata) !== null && _b !== void 0 ? _b : defaultResponder.sendMetadata, + sendMessage: (_c = responder === null || responder === void 0 ? void 0 : responder.sendMessage) !== null && _c !== void 0 ? _c : defaultResponder.sendMessage, + sendStatus: (_d = responder === null || responder === void 0 ? void 0 : responder.sendStatus) !== null && _d !== void 0 ? _d : defaultResponder.sendStatus + }; + } + processPendingMessage() { + if (this.pendingMessageCallback) { + this.nextCall.sendMessage(this.pendingMessage, this.pendingMessageCallback); + this.pendingMessage = null; + this.pendingMessageCallback = null; + } + } + processPendingStatus() { + if (this.pendingStatus) { + this.nextCall.sendStatus(this.pendingStatus); + this.pendingStatus = null; + } + } + start(listener) { + this.responder.start((interceptedListener) => { + var _a, _b, _c, _d; + const fullInterceptedListener = { + onReceiveMetadata: (_a = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onReceiveMetadata) !== null && _a !== void 0 ? _a : defaultServerListener.onReceiveMetadata, + onReceiveMessage: (_b = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onReceiveMessage) !== null && _b !== void 0 ? _b : defaultServerListener.onReceiveMessage, + onReceiveHalfClose: (_c = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onReceiveHalfClose) !== null && _c !== void 0 ? _c : defaultServerListener.onReceiveHalfClose, + onCancel: (_d = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onCancel) !== null && _d !== void 0 ? _d : defaultServerListener.onCancel + }; + const finalInterceptingListener = new InterceptingServerListenerImpl(fullInterceptedListener, listener); + this.nextCall.start(finalInterceptingListener); + }); + } + sendMetadata(metadata) { + this.processingMetadata = true; + this.sentMetadata = true; + this.responder.sendMetadata(metadata, (interceptedMetadata) => { + this.processingMetadata = false; + this.nextCall.sendMetadata(interceptedMetadata); + this.processPendingMessage(); + this.processPendingStatus(); + }); + } + sendMessage(message, callback) { + this.processingMessage = true; + if (!this.sentMetadata) { + this.sendMetadata(new metadata_1.Metadata()); + } + this.responder.sendMessage(message, (interceptedMessage) => { + this.processingMessage = false; + if (this.processingMetadata) { + this.pendingMessage = interceptedMessage; + this.pendingMessageCallback = callback; + } else { + this.nextCall.sendMessage(interceptedMessage, callback); + } + }); + } + sendStatus(status) { + this.responder.sendStatus(status, (interceptedStatus) => { + if (this.processingMetadata || this.processingMessage) { + this.pendingStatus = interceptedStatus; + } else { + this.nextCall.sendStatus(interceptedStatus); + } + }); + } + startRead() { + this.nextCall.startRead(); + } + getPeer() { + return this.nextCall.getPeer(); + } + getDeadline() { + return this.nextCall.getDeadline(); + } + getHost() { + return this.nextCall.getHost(); + } + getAuthContext() { + return this.nextCall.getAuthContext(); + } + getConnectionInfo() { + return this.nextCall.getConnectionInfo(); + } + getMetricsRecorder() { + return this.nextCall.getMetricsRecorder(); + } + }; + exports2.ServerInterceptingCall = ServerInterceptingCall; + var GRPC_ACCEPT_ENCODING_HEADER = "grpc-accept-encoding"; + var GRPC_ENCODING_HEADER = "grpc-encoding"; + var GRPC_MESSAGE_HEADER = "grpc-message"; + var GRPC_STATUS_HEADER = "grpc-status"; + var GRPC_TIMEOUT_HEADER = "grpc-timeout"; + var DEADLINE_REGEX = /(\d{1,8})\s*([HMSmun])/; + var deadlineUnitsToMs = { + H: 36e5, + M: 6e4, + S: 1e3, + m: 1, + u: 1e-3, + n: 1e-6 + }; + var defaultCompressionHeaders = { + // TODO(cjihrig): Remove these encoding headers from the default response + // once compression is integrated. + [GRPC_ACCEPT_ENCODING_HEADER]: "identity,deflate,gzip", + [GRPC_ENCODING_HEADER]: "identity" + }; + var defaultResponseHeaders = { + [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_OK, + [http2.constants.HTTP2_HEADER_CONTENT_TYPE]: "application/grpc+proto" + }; + var defaultResponseOptions = { + waitForTrailers: true + }; + var BaseServerInterceptingCall = class { + constructor(stream2, headers, callEventTracker, handler2, options) { + var _a, _b; + this.stream = stream2; + this.callEventTracker = callEventTracker; + this.handler = handler2; + this.listener = null; + this.deadlineTimer = null; + this.deadline = Infinity; + this.maxSendMessageSize = constants_1.DEFAULT_MAX_SEND_MESSAGE_LENGTH; + this.maxReceiveMessageSize = constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH; + this.cancelled = false; + this.metadataSent = false; + this.wantTrailers = false; + this.cancelNotified = false; + this.incomingEncoding = "identity"; + this.readQueue = []; + this.isReadPending = false; + this.receivedHalfClose = false; + this.streamEnded = false; + this.metricsRecorder = new orca_1.PerRequestMetricRecorder(); + this.stream.once("close", () => { + var _a2; + trace("Request to method " + ((_a2 = this.handler) === null || _a2 === void 0 ? void 0 : _a2.path) + " stream closed with rstCode " + this.stream.rstCode); + if (this.callEventTracker && !this.streamEnded) { + this.streamEnded = true; + this.callEventTracker.onStreamEnd(false); + this.callEventTracker.onCallEnd({ + code: constants_1.Status.CANCELLED, + details: "Stream closed before sending status", + metadata: null + }); + } + this.notifyOnCancel(); + }); + this.stream.on("data", (data) => { + this.handleDataFrame(data); + }); + this.stream.pause(); + this.stream.on("end", () => { + this.handleEndEvent(); + }); + if ("grpc.max_send_message_length" in options) { + this.maxSendMessageSize = options["grpc.max_send_message_length"]; + } + if ("grpc.max_receive_message_length" in options) { + this.maxReceiveMessageSize = options["grpc.max_receive_message_length"]; + } + this.host = (_a = headers[":authority"]) !== null && _a !== void 0 ? _a : headers.host; + this.decoder = new stream_decoder_1.StreamDecoder(this.maxReceiveMessageSize); + const metadata = metadata_1.Metadata.fromHttp2Headers(headers); + if (logging.isTracerEnabled(TRACER_NAME)) { + trace("Request to " + this.handler.path + " received headers " + JSON.stringify(metadata.toJSON())); + } + const timeoutHeader = metadata.get(GRPC_TIMEOUT_HEADER); + if (timeoutHeader.length > 0) { + this.handleTimeoutHeader(timeoutHeader[0]); + } + const encodingHeader = metadata.get(GRPC_ENCODING_HEADER); + if (encodingHeader.length > 0) { + this.incomingEncoding = encodingHeader[0]; + } + metadata.remove(GRPC_TIMEOUT_HEADER); + metadata.remove(GRPC_ENCODING_HEADER); + metadata.remove(GRPC_ACCEPT_ENCODING_HEADER); + metadata.remove(http2.constants.HTTP2_HEADER_ACCEPT_ENCODING); + metadata.remove(http2.constants.HTTP2_HEADER_TE); + metadata.remove(http2.constants.HTTP2_HEADER_CONTENT_TYPE); + this.metadata = metadata; + const socket = (_b = stream2.session) === null || _b === void 0 ? void 0 : _b.socket; + this.connectionInfo = { + localAddress: socket === null || socket === void 0 ? void 0 : socket.localAddress, + localPort: socket === null || socket === void 0 ? void 0 : socket.localPort, + remoteAddress: socket === null || socket === void 0 ? void 0 : socket.remoteAddress, + remotePort: socket === null || socket === void 0 ? void 0 : socket.remotePort + }; + this.shouldSendMetrics = !!options["grpc.server_call_metric_recording"]; + } + handleTimeoutHeader(timeoutHeader) { + const match = timeoutHeader.toString().match(DEADLINE_REGEX); + if (match === null) { + const status = { + code: constants_1.Status.INTERNAL, + details: `Invalid ${GRPC_TIMEOUT_HEADER} value "${timeoutHeader}"`, + metadata: null + }; + process.nextTick(() => { + this.sendStatus(status); + }); + return; + } + const timeout = +match[1] * deadlineUnitsToMs[match[2]] | 0; + const now = /* @__PURE__ */ new Date(); + this.deadline = now.setMilliseconds(now.getMilliseconds() + timeout); + this.deadlineTimer = setTimeout(() => { + const status = { + code: constants_1.Status.DEADLINE_EXCEEDED, + details: "Deadline exceeded", + metadata: null + }; + this.sendStatus(status); + }, timeout); + } + checkCancelled() { + if (!this.cancelled && (this.stream.destroyed || this.stream.closed)) { + this.notifyOnCancel(); + this.cancelled = true; + } + return this.cancelled; + } + notifyOnCancel() { + if (this.cancelNotified) { + return; + } + this.cancelNotified = true; + this.cancelled = true; + process.nextTick(() => { + var _a; + (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onCancel(); + }); + if (this.deadlineTimer) { + clearTimeout(this.deadlineTimer); + } + this.stream.resume(); + } + /** + * A server handler can start sending messages without explicitly sending + * metadata. In that case, we need to send headers before sending any + * messages. This function does that if necessary. + */ + maybeSendMetadata() { + if (!this.metadataSent) { + this.sendMetadata(new metadata_1.Metadata()); + } + } + /** + * Serialize a message to a length-delimited byte string. + * @param value + * @returns + */ + serializeMessage(value) { + const messageBuffer = this.handler.serialize(value); + const byteLength = messageBuffer.byteLength; + const output = Buffer.allocUnsafe(byteLength + 5); + output.writeUInt8(0, 0); + output.writeUInt32BE(byteLength, 1); + messageBuffer.copy(output, 5); + return output; + } + decompressMessage(message, encoding) { + const messageContents = message.subarray(5); + if (encoding === "identity") { + return messageContents; + } else if (encoding === "deflate" || encoding === "gzip") { + let decompresser; + if (encoding === "deflate") { + decompresser = zlib.createInflate(); + } else { + decompresser = zlib.createGunzip(); + } + return new Promise((resolve, reject) => { + let totalLength = 0; + const messageParts = []; + decompresser.on("error", (error2) => { + reject({ + code: constants_1.Status.INTERNAL, + details: "Failed to decompress message" + }); + }); + decompresser.on("data", (chunk) => { + messageParts.push(chunk); + totalLength += chunk.byteLength; + if (this.maxReceiveMessageSize !== -1 && totalLength > this.maxReceiveMessageSize) { + decompresser.destroy(); + reject({ + code: constants_1.Status.RESOURCE_EXHAUSTED, + details: `Received message that decompresses to a size larger than ${this.maxReceiveMessageSize}` + }); + } + }); + decompresser.on("end", () => { + resolve(Buffer.concat(messageParts)); + }); + decompresser.write(messageContents); + decompresser.end(); + }); + } else { + return Promise.reject({ + code: constants_1.Status.UNIMPLEMENTED, + details: `Received message compressed with unsupported encoding "${encoding}"` + }); + } + } + async decompressAndMaybePush(queueEntry) { + if (queueEntry.type !== "COMPRESSED") { + throw new Error(`Invalid queue entry type: ${queueEntry.type}`); + } + const compressed = queueEntry.compressedMessage.readUInt8(0) === 1; + const compressedMessageEncoding = compressed ? this.incomingEncoding : "identity"; + let decompressedMessage; + try { + decompressedMessage = await this.decompressMessage(queueEntry.compressedMessage, compressedMessageEncoding); + } catch (err) { + this.sendStatus(err); + return; + } + try { + queueEntry.parsedMessage = this.handler.deserialize(decompressedMessage); + } catch (err) { + this.sendStatus({ + code: constants_1.Status.INTERNAL, + details: `Error deserializing request: ${err.message}` + }); + return; + } + queueEntry.type = "READABLE"; + this.maybePushNextMessage(); + } + maybePushNextMessage() { + if (this.listener && this.isReadPending && this.readQueue.length > 0 && this.readQueue[0].type !== "COMPRESSED") { + this.isReadPending = false; + const nextQueueEntry = this.readQueue.shift(); + if (nextQueueEntry.type === "READABLE") { + this.listener.onReceiveMessage(nextQueueEntry.parsedMessage); + } else { + this.listener.onReceiveHalfClose(); + } + } + } + handleDataFrame(data) { + var _a; + if (this.checkCancelled()) { + return; + } + trace("Request to " + this.handler.path + " received data frame of size " + data.length); + let rawMessages; + try { + rawMessages = this.decoder.write(data); + } catch (e) { + this.sendStatus({ code: constants_1.Status.RESOURCE_EXHAUSTED, details: e.message }); + return; + } + for (const messageBytes of rawMessages) { + this.stream.pause(); + const queueEntry = { + type: "COMPRESSED", + compressedMessage: messageBytes, + parsedMessage: null + }; + this.readQueue.push(queueEntry); + this.decompressAndMaybePush(queueEntry); + (_a = this.callEventTracker) === null || _a === void 0 ? void 0 : _a.addMessageReceived(); + } + } + handleEndEvent() { + this.readQueue.push({ + type: "HALF_CLOSE", + compressedMessage: null, + parsedMessage: null + }); + this.receivedHalfClose = true; + this.maybePushNextMessage(); + } + start(listener) { + trace("Request to " + this.handler.path + " start called"); + if (this.checkCancelled()) { + return; + } + this.listener = listener; + listener.onReceiveMetadata(this.metadata); + } + sendMetadata(metadata) { + if (this.checkCancelled()) { + return; + } + if (this.metadataSent) { + return; + } + this.metadataSent = true; + const custom = metadata ? metadata.toHttp2Headers() : null; + const headers = Object.assign(Object.assign(Object.assign({}, defaultResponseHeaders), defaultCompressionHeaders), custom); + this.stream.respond(headers, defaultResponseOptions); + } + sendMessage(message, callback) { + if (this.checkCancelled()) { + return; + } + let response; + try { + response = this.serializeMessage(message); + } catch (e) { + this.sendStatus({ + code: constants_1.Status.INTERNAL, + details: `Error serializing response: ${(0, error_1.getErrorMessage)(e)}`, + metadata: null + }); + return; + } + if (this.maxSendMessageSize !== -1 && response.length - 5 > this.maxSendMessageSize) { + this.sendStatus({ + code: constants_1.Status.RESOURCE_EXHAUSTED, + details: `Sent message larger than max (${response.length} vs. ${this.maxSendMessageSize})`, + metadata: null + }); + return; + } + this.maybeSendMetadata(); + trace("Request to " + this.handler.path + " sent data frame of size " + response.length); + this.stream.write(response, (error2) => { + var _a; + if (error2) { + this.sendStatus({ + code: constants_1.Status.INTERNAL, + details: `Error writing message: ${(0, error_1.getErrorMessage)(error2)}`, + metadata: null + }); + return; + } + (_a = this.callEventTracker) === null || _a === void 0 ? void 0 : _a.addMessageSent(); + callback(); + }); + } + sendStatus(status) { + var _a, _b, _c; + if (this.checkCancelled()) { + return; + } + trace("Request to method " + ((_a = this.handler) === null || _a === void 0 ? void 0 : _a.path) + " ended with status code: " + constants_1.Status[status.code] + " details: " + status.details); + const statusMetadata = (_c = (_b = status.metadata) === null || _b === void 0 ? void 0 : _b.clone()) !== null && _c !== void 0 ? _c : new metadata_1.Metadata(); + if (this.shouldSendMetrics) { + statusMetadata.set(orca_1.GRPC_METRICS_HEADER, this.metricsRecorder.serialize()); + } + if (this.metadataSent) { + if (!this.wantTrailers) { + this.wantTrailers = true; + this.stream.once("wantTrailers", () => { + if (this.callEventTracker && !this.streamEnded) { + this.streamEnded = true; + this.callEventTracker.onStreamEnd(true); + this.callEventTracker.onCallEnd(status); + } + const trailersToSend = Object.assign({ [GRPC_STATUS_HEADER]: status.code, [GRPC_MESSAGE_HEADER]: encodeURI(status.details) }, statusMetadata.toHttp2Headers()); + this.stream.sendTrailers(trailersToSend); + this.notifyOnCancel(); + }); + this.stream.end(); + } else { + this.notifyOnCancel(); + } + } else { + if (this.callEventTracker && !this.streamEnded) { + this.streamEnded = true; + this.callEventTracker.onStreamEnd(true); + this.callEventTracker.onCallEnd(status); + } + const trailersToSend = Object.assign(Object.assign({ [GRPC_STATUS_HEADER]: status.code, [GRPC_MESSAGE_HEADER]: encodeURI(status.details) }, defaultResponseHeaders), statusMetadata.toHttp2Headers()); + this.stream.respond(trailersToSend, { endStream: true }); + this.notifyOnCancel(); + } + } + startRead() { + trace("Request to " + this.handler.path + " startRead called"); + if (this.checkCancelled()) { + return; + } + this.isReadPending = true; + if (this.readQueue.length === 0) { + if (!this.receivedHalfClose) { + this.stream.resume(); + } + } else { + this.maybePushNextMessage(); + } + } + getPeer() { + var _a; + const socket = (_a = this.stream.session) === null || _a === void 0 ? void 0 : _a.socket; + if (socket === null || socket === void 0 ? void 0 : socket.remoteAddress) { + if (socket.remotePort) { + return `${socket.remoteAddress}:${socket.remotePort}`; + } else { + return socket.remoteAddress; + } + } else { + return "unknown"; + } + } + getDeadline() { + return this.deadline; + } + getHost() { + return this.host; + } + getAuthContext() { + var _a; + if (((_a = this.stream.session) === null || _a === void 0 ? void 0 : _a.socket) instanceof tls_1.TLSSocket) { + const peerCertificate = this.stream.session.socket.getPeerCertificate(); + return { + transportSecurityType: "ssl", + sslPeerCertificate: peerCertificate.raw ? peerCertificate : void 0 + }; + } else { + return {}; + } + } + getConnectionInfo() { + return this.connectionInfo; + } + getMetricsRecorder() { + return this.metricsRecorder; + } + }; + exports2.BaseServerInterceptingCall = BaseServerInterceptingCall; + function getServerInterceptingCall(interceptors, stream2, headers, callEventTracker, handler2, options) { + const methodDefinition = { + path: handler2.path, + requestStream: handler2.type === "clientStream" || handler2.type === "bidi", + responseStream: handler2.type === "serverStream" || handler2.type === "bidi", + requestDeserialize: handler2.deserialize, + responseSerialize: handler2.serialize + }; + const baseCall = new BaseServerInterceptingCall(stream2, headers, callEventTracker, handler2, options); + return interceptors.reduce((call, interceptor) => { + return interceptor(methodDefinition, call); + }, baseCall); + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/server.js +var require_server2 = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/server.js"(exports2) { + "use strict"; + var __runInitializers = exports2 && exports2.__runInitializers || function(thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; + }; + var __esDecorate = exports2 && exports2.__esDecorate || function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { + if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); + return f; + } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context3 = {}; + for (var p in contextIn) context3[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context3.access[p] = contextIn.access[p]; + context3.addInitializer = function(f) { + if (done) throw new TypeError("Cannot add initializers after decoration has completed"); + extraInitializers.push(accept(f || null)); + }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context3); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Server = void 0; + var http2 = require("http2"); + var util = require("util"); + var constants_1 = require_constants7(); + var server_call_1 = require_server_call(); + var server_credentials_1 = require_server_credentials(); + var resolver_1 = require_resolver(); + var logging = require_logging(); + var subchannel_address_1 = require_subchannel_address(); + var uri_parser_1 = require_uri_parser(); + var channelz_1 = require_channelz(); + var server_interceptors_1 = require_server_interceptors(); + var UNLIMITED_CONNECTION_AGE_MS = ~(1 << 31); + var KEEPALIVE_MAX_TIME_MS = ~(1 << 31); + var KEEPALIVE_TIMEOUT_MS = 2e4; + var MAX_CONNECTION_IDLE_MS = ~(1 << 31); + var { HTTP2_HEADER_PATH } = http2.constants; + var TRACER_NAME = "server"; + var kMaxAge = Buffer.from("max_age"); + function serverCallTrace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, "server_call", text); + } + function noop3() { + } + function deprecate(message) { + return function(target, context3) { + return util.deprecate(target, message); + }; + } + function getUnimplementedStatusResponse(methodName) { + return { + code: constants_1.Status.UNIMPLEMENTED, + details: `The server does not implement the method ${methodName}` + }; + } + function getDefaultHandler(handlerType, methodName) { + const unimplementedStatusResponse = getUnimplementedStatusResponse(methodName); + switch (handlerType) { + case "unary": + return (call, callback) => { + callback(unimplementedStatusResponse, null); + }; + case "clientStream": + return (call, callback) => { + callback(unimplementedStatusResponse, null); + }; + case "serverStream": + return (call) => { + call.emit("error", unimplementedStatusResponse); + }; + case "bidi": + return (call) => { + call.emit("error", unimplementedStatusResponse); + }; + default: + throw new Error(`Invalid handlerType ${handlerType}`); + } + } + var Server = (() => { + var _a; + let _instanceExtraInitializers = []; + let _start_decorators; + return _a = class Server { + constructor(options) { + var _b, _c, _d, _e, _f, _g; + this.boundPorts = (__runInitializers(this, _instanceExtraInitializers), /* @__PURE__ */ new Map()); + this.http2Servers = /* @__PURE__ */ new Map(); + this.sessionIdleTimeouts = /* @__PURE__ */ new Map(); + this.handlers = /* @__PURE__ */ new Map(); + this.sessions = /* @__PURE__ */ new Map(); + this.started = false; + this.shutdown = false; + this.serverAddressString = "null"; + this.channelzEnabled = true; + this.options = options !== null && options !== void 0 ? options : {}; + if (this.options["grpc.enable_channelz"] === 0) { + this.channelzEnabled = false; + this.channelzTrace = new channelz_1.ChannelzTraceStub(); + this.callTracker = new channelz_1.ChannelzCallTrackerStub(); + this.listenerChildrenTracker = new channelz_1.ChannelzChildrenTrackerStub(); + this.sessionChildrenTracker = new channelz_1.ChannelzChildrenTrackerStub(); + } else { + this.channelzTrace = new channelz_1.ChannelzTrace(); + this.callTracker = new channelz_1.ChannelzCallTracker(); + this.listenerChildrenTracker = new channelz_1.ChannelzChildrenTracker(); + this.sessionChildrenTracker = new channelz_1.ChannelzChildrenTracker(); + } + this.channelzRef = (0, channelz_1.registerChannelzServer)("server", () => this.getChannelzInfo(), this.channelzEnabled); + this.channelzTrace.addTrace("CT_INFO", "Server created"); + this.maxConnectionAgeMs = (_b = this.options["grpc.max_connection_age_ms"]) !== null && _b !== void 0 ? _b : UNLIMITED_CONNECTION_AGE_MS; + this.maxConnectionAgeGraceMs = (_c = this.options["grpc.max_connection_age_grace_ms"]) !== null && _c !== void 0 ? _c : UNLIMITED_CONNECTION_AGE_MS; + this.keepaliveTimeMs = (_d = this.options["grpc.keepalive_time_ms"]) !== null && _d !== void 0 ? _d : KEEPALIVE_MAX_TIME_MS; + this.keepaliveTimeoutMs = (_e = this.options["grpc.keepalive_timeout_ms"]) !== null && _e !== void 0 ? _e : KEEPALIVE_TIMEOUT_MS; + this.sessionIdleTimeout = (_f = this.options["grpc.max_connection_idle_ms"]) !== null && _f !== void 0 ? _f : MAX_CONNECTION_IDLE_MS; + this.commonServerOptions = { + maxSendHeaderBlockLength: Number.MAX_SAFE_INTEGER + }; + if ("grpc-node.max_session_memory" in this.options) { + this.commonServerOptions.maxSessionMemory = this.options["grpc-node.max_session_memory"]; + } else { + this.commonServerOptions.maxSessionMemory = Number.MAX_SAFE_INTEGER; + } + if ("grpc.max_concurrent_streams" in this.options) { + this.commonServerOptions.settings = { + maxConcurrentStreams: this.options["grpc.max_concurrent_streams"] + }; + } + this.interceptors = (_g = this.options.interceptors) !== null && _g !== void 0 ? _g : []; + this.trace("Server constructed"); + } + getChannelzInfo() { + return { + trace: this.channelzTrace, + callTracker: this.callTracker, + listenerChildren: this.listenerChildrenTracker.getChildLists(), + sessionChildren: this.sessionChildrenTracker.getChildLists() + }; + } + getChannelzSessionInfo(session) { + var _b, _c, _d; + const sessionInfo = this.sessions.get(session); + const sessionSocket = session.socket; + const remoteAddress = sessionSocket.remoteAddress ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.remoteAddress, sessionSocket.remotePort) : null; + const localAddress = sessionSocket.localAddress ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.localAddress, sessionSocket.localPort) : null; + let tlsInfo; + if (session.encrypted) { + const tlsSocket = sessionSocket; + const cipherInfo = tlsSocket.getCipher(); + const certificate = tlsSocket.getCertificate(); + const peerCertificate = tlsSocket.getPeerCertificate(); + tlsInfo = { + cipherSuiteStandardName: (_b = cipherInfo.standardName) !== null && _b !== void 0 ? _b : null, + cipherSuiteOtherName: cipherInfo.standardName ? null : cipherInfo.name, + localCertificate: certificate && "raw" in certificate ? certificate.raw : null, + remoteCertificate: peerCertificate && "raw" in peerCertificate ? peerCertificate.raw : null + }; + } else { + tlsInfo = null; + } + const socketInfo = { + remoteAddress, + localAddress, + security: tlsInfo, + remoteName: null, + streamsStarted: sessionInfo.streamTracker.callsStarted, + streamsSucceeded: sessionInfo.streamTracker.callsSucceeded, + streamsFailed: sessionInfo.streamTracker.callsFailed, + messagesSent: sessionInfo.messagesSent, + messagesReceived: sessionInfo.messagesReceived, + keepAlivesSent: sessionInfo.keepAlivesSent, + lastLocalStreamCreatedTimestamp: null, + lastRemoteStreamCreatedTimestamp: sessionInfo.streamTracker.lastCallStartedTimestamp, + lastMessageSentTimestamp: sessionInfo.lastMessageSentTimestamp, + lastMessageReceivedTimestamp: sessionInfo.lastMessageReceivedTimestamp, + localFlowControlWindow: (_c = session.state.localWindowSize) !== null && _c !== void 0 ? _c : null, + remoteFlowControlWindow: (_d = session.state.remoteWindowSize) !== null && _d !== void 0 ? _d : null + }; + return socketInfo; + } + trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "(" + this.channelzRef.id + ") " + text); + } + keepaliveTrace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, "keepalive", "(" + this.channelzRef.id + ") " + text); + } + addProtoService() { + throw new Error("Not implemented. Use addService() instead"); + } + addService(service, implementation) { + if (service === null || typeof service !== "object" || implementation === null || typeof implementation !== "object") { + throw new Error("addService() requires two objects as arguments"); + } + const serviceKeys = Object.keys(service); + if (serviceKeys.length === 0) { + throw new Error("Cannot add an empty service to a server"); + } + serviceKeys.forEach((name) => { + const attrs = service[name]; + let methodType; + if (attrs.requestStream) { + if (attrs.responseStream) { + methodType = "bidi"; + } else { + methodType = "clientStream"; + } + } else { + if (attrs.responseStream) { + methodType = "serverStream"; + } else { + methodType = "unary"; + } + } + let implFn = implementation[name]; + let impl; + if (implFn === void 0 && typeof attrs.originalName === "string") { + implFn = implementation[attrs.originalName]; + } + if (implFn !== void 0) { + impl = implFn.bind(implementation); + } else { + impl = getDefaultHandler(methodType, name); + } + const success = this.register(attrs.path, impl, attrs.responseSerialize, attrs.requestDeserialize, methodType); + if (success === false) { + throw new Error(`Method handler for ${attrs.path} already provided.`); + } + }); + } + removeService(service) { + if (service === null || typeof service !== "object") { + throw new Error("removeService() requires object as argument"); + } + const serviceKeys = Object.keys(service); + serviceKeys.forEach((name) => { + const attrs = service[name]; + this.unregister(attrs.path); + }); + } + bind(port, creds) { + throw new Error("Not implemented. Use bindAsync() instead"); + } + /** + * This API is experimental, so API stability is not guaranteed across minor versions. + * @param boundAddress + * @returns + */ + experimentalRegisterListenerToChannelz(boundAddress) { + return (0, channelz_1.registerChannelzSocket)((0, subchannel_address_1.subchannelAddressToString)(boundAddress), () => { + return { + localAddress: boundAddress, + remoteAddress: null, + security: null, + remoteName: null, + streamsStarted: 0, + streamsSucceeded: 0, + streamsFailed: 0, + messagesSent: 0, + messagesReceived: 0, + keepAlivesSent: 0, + lastLocalStreamCreatedTimestamp: null, + lastRemoteStreamCreatedTimestamp: null, + lastMessageSentTimestamp: null, + lastMessageReceivedTimestamp: null, + localFlowControlWindow: null, + remoteFlowControlWindow: null + }; + }, this.channelzEnabled); + } + experimentalUnregisterListenerFromChannelz(channelzRef) { + (0, channelz_1.unregisterChannelzRef)(channelzRef); + } + createHttp2Server(credentials) { + let http2Server; + if (credentials._isSecure()) { + const constructorOptions = credentials._getConstructorOptions(); + const contextOptions = credentials._getSecureContextOptions(); + const secureServerOptions = Object.assign(Object.assign(Object.assign(Object.assign({}, this.commonServerOptions), constructorOptions), contextOptions), { enableTrace: this.options["grpc-node.tls_enable_trace"] === 1 }); + let areCredentialsValid = contextOptions !== null; + this.trace("Initial credentials valid: " + areCredentialsValid); + http2Server = http2.createSecureServer(secureServerOptions); + http2Server.prependListener("connection", (socket) => { + if (!areCredentialsValid) { + this.trace("Dropped connection from " + JSON.stringify(socket.address()) + " due to unloaded credentials"); + socket.destroy(); + } + }); + http2Server.on("secureConnection", (socket) => { + socket.on("error", (e) => { + this.trace("An incoming TLS connection closed with error: " + e.message); + }); + }); + const credsWatcher = (options) => { + if (options) { + const secureServer = http2Server; + try { + secureServer.setSecureContext(options); + } catch (e) { + logging.log(constants_1.LogVerbosity.ERROR, "Failed to set secure context with error " + e.message); + options = null; + } + } + areCredentialsValid = options !== null; + this.trace("Post-update credentials valid: " + areCredentialsValid); + }; + credentials._addWatcher(credsWatcher); + http2Server.on("close", () => { + credentials._removeWatcher(credsWatcher); + }); + } else { + http2Server = http2.createServer(this.commonServerOptions); + } + http2Server.setTimeout(0, noop3); + this._setupHandlers(http2Server, credentials._getInterceptors()); + return http2Server; + } + bindOneAddress(address, boundPortObject) { + this.trace("Attempting to bind " + (0, subchannel_address_1.subchannelAddressToString)(address)); + const http2Server = this.createHttp2Server(boundPortObject.credentials); + return new Promise((resolve, reject) => { + const onError = (err) => { + this.trace("Failed to bind " + (0, subchannel_address_1.subchannelAddressToString)(address) + " with error " + err.message); + resolve({ + port: "port" in address ? address.port : 1, + error: err.message + }); + }; + http2Server.once("error", onError); + http2Server.listen(address, () => { + const boundAddress = http2Server.address(); + let boundSubchannelAddress; + if (typeof boundAddress === "string") { + boundSubchannelAddress = { + path: boundAddress + }; + } else { + boundSubchannelAddress = { + host: boundAddress.address, + port: boundAddress.port + }; + } + const channelzRef = this.experimentalRegisterListenerToChannelz(boundSubchannelAddress); + this.listenerChildrenTracker.refChild(channelzRef); + this.http2Servers.set(http2Server, { + channelzRef, + sessions: /* @__PURE__ */ new Set(), + ownsChannelzRef: true + }); + boundPortObject.listeningServers.add(http2Server); + this.trace("Successfully bound " + (0, subchannel_address_1.subchannelAddressToString)(boundSubchannelAddress)); + resolve({ + port: "port" in boundSubchannelAddress ? boundSubchannelAddress.port : 1 + }); + http2Server.removeListener("error", onError); + }); + }); + } + async bindManyPorts(addressList, boundPortObject) { + if (addressList.length === 0) { + return { + count: 0, + port: 0, + errors: [] + }; + } + if ((0, subchannel_address_1.isTcpSubchannelAddress)(addressList[0]) && addressList[0].port === 0) { + const firstAddressResult = await this.bindOneAddress(addressList[0], boundPortObject); + if (firstAddressResult.error) { + const restAddressResult = await this.bindManyPorts(addressList.slice(1), boundPortObject); + return Object.assign(Object.assign({}, restAddressResult), { errors: [firstAddressResult.error, ...restAddressResult.errors] }); + } else { + const restAddresses = addressList.slice(1).map((address) => (0, subchannel_address_1.isTcpSubchannelAddress)(address) ? { host: address.host, port: firstAddressResult.port } : address); + const restAddressResult = await Promise.all(restAddresses.map((address) => this.bindOneAddress(address, boundPortObject))); + const allResults = [firstAddressResult, ...restAddressResult]; + return { + count: allResults.filter((result) => result.error === void 0).length, + port: firstAddressResult.port, + errors: allResults.filter((result) => result.error).map((result) => result.error) + }; + } + } else { + const allResults = await Promise.all(addressList.map((address) => this.bindOneAddress(address, boundPortObject))); + return { + count: allResults.filter((result) => result.error === void 0).length, + port: allResults[0].port, + errors: allResults.filter((result) => result.error).map((result) => result.error) + }; + } + } + async bindAddressList(addressList, boundPortObject) { + const bindResult = await this.bindManyPorts(addressList, boundPortObject); + if (bindResult.count > 0) { + if (bindResult.count < addressList.length) { + logging.log(constants_1.LogVerbosity.INFO, `WARNING Only ${bindResult.count} addresses added out of total ${addressList.length} resolved`); + } + return bindResult.port; + } else { + const errorString = `No address added out of total ${addressList.length} resolved`; + logging.log(constants_1.LogVerbosity.ERROR, errorString); + throw new Error(`${errorString} errors: [${bindResult.errors.join(",")}]`); + } + } + resolvePort(port) { + return new Promise((resolve, reject) => { + let seenResolution = false; + const resolverListener = (endpointList, attributes, serviceConfig, resolutionNote) => { + if (seenResolution) { + return true; + } + seenResolution = true; + if (!endpointList.ok) { + reject(new Error(endpointList.error.details)); + return true; + } + const addressList = [].concat(...endpointList.value.map((endpoint2) => endpoint2.addresses)); + if (addressList.length === 0) { + reject(new Error(`No addresses resolved for port ${port}`)); + return true; + } + resolve(addressList); + return true; + }; + const resolver = (0, resolver_1.createResolver)(port, resolverListener, this.options); + resolver.updateResolution(); + }); + } + async bindPort(port, boundPortObject) { + const addressList = await this.resolvePort(port); + if (boundPortObject.cancelled) { + this.completeUnbind(boundPortObject); + throw new Error("bindAsync operation cancelled by unbind call"); + } + const portNumber = await this.bindAddressList(addressList, boundPortObject); + if (boundPortObject.cancelled) { + this.completeUnbind(boundPortObject); + throw new Error("bindAsync operation cancelled by unbind call"); + } + return portNumber; + } + normalizePort(port) { + const initialPortUri = (0, uri_parser_1.parseUri)(port); + if (initialPortUri === null) { + throw new Error(`Could not parse port "${port}"`); + } + const portUri = (0, resolver_1.mapUriDefaultScheme)(initialPortUri); + if (portUri === null) { + throw new Error(`Could not get a default scheme for port "${port}"`); + } + return portUri; + } + bindAsync(port, creds, callback) { + if (this.shutdown) { + throw new Error("bindAsync called after shutdown"); + } + if (typeof port !== "string") { + throw new TypeError("port must be a string"); + } + if (creds === null || !(creds instanceof server_credentials_1.ServerCredentials)) { + throw new TypeError("creds must be a ServerCredentials object"); + } + if (typeof callback !== "function") { + throw new TypeError("callback must be a function"); + } + this.trace("bindAsync port=" + port); + const portUri = this.normalizePort(port); + const deferredCallback = (error2, port2) => { + process.nextTick(() => callback(error2, port2)); + }; + let boundPortObject = this.boundPorts.get((0, uri_parser_1.uriToString)(portUri)); + if (boundPortObject) { + if (!creds._equals(boundPortObject.credentials)) { + deferredCallback(new Error(`${port} already bound with incompatible credentials`), 0); + return; + } + boundPortObject.cancelled = false; + if (boundPortObject.completionPromise) { + boundPortObject.completionPromise.then((portNum) => callback(null, portNum), (error2) => callback(error2, 0)); + } else { + deferredCallback(null, boundPortObject.portNumber); + } + return; + } + boundPortObject = { + mapKey: (0, uri_parser_1.uriToString)(portUri), + originalUri: portUri, + completionPromise: null, + cancelled: false, + portNumber: 0, + credentials: creds, + listeningServers: /* @__PURE__ */ new Set() + }; + const splitPort = (0, uri_parser_1.splitHostPort)(portUri.path); + const completionPromise = this.bindPort(portUri, boundPortObject); + boundPortObject.completionPromise = completionPromise; + if ((splitPort === null || splitPort === void 0 ? void 0 : splitPort.port) === 0) { + completionPromise.then((portNum) => { + const finalUri = { + scheme: portUri.scheme, + authority: portUri.authority, + path: (0, uri_parser_1.combineHostPort)({ host: splitPort.host, port: portNum }) + }; + boundPortObject.mapKey = (0, uri_parser_1.uriToString)(finalUri); + boundPortObject.completionPromise = null; + boundPortObject.portNumber = portNum; + this.boundPorts.set(boundPortObject.mapKey, boundPortObject); + callback(null, portNum); + }, (error2) => { + callback(error2, 0); + }); + } else { + this.boundPorts.set(boundPortObject.mapKey, boundPortObject); + completionPromise.then((portNum) => { + boundPortObject.completionPromise = null; + boundPortObject.portNumber = portNum; + callback(null, portNum); + }, (error2) => { + callback(error2, 0); + }); + } + } + registerInjectorToChannelz() { + return (0, channelz_1.registerChannelzSocket)("injector", () => { + return { + localAddress: null, + remoteAddress: null, + security: null, + remoteName: null, + streamsStarted: 0, + streamsSucceeded: 0, + streamsFailed: 0, + messagesSent: 0, + messagesReceived: 0, + keepAlivesSent: 0, + lastLocalStreamCreatedTimestamp: null, + lastRemoteStreamCreatedTimestamp: null, + lastMessageSentTimestamp: null, + lastMessageReceivedTimestamp: null, + localFlowControlWindow: null, + remoteFlowControlWindow: null + }; + }, this.channelzEnabled); + } + /** + * This API is experimental, so API stability is not guaranteed across minor versions. + * @param credentials + * @param channelzRef + * @returns + */ + experimentalCreateConnectionInjectorWithChannelzRef(credentials, channelzRef, ownsChannelzRef = false) { + if (credentials === null || !(credentials instanceof server_credentials_1.ServerCredentials)) { + throw new TypeError("creds must be a ServerCredentials object"); + } + if (this.channelzEnabled) { + this.listenerChildrenTracker.refChild(channelzRef); + } + const server = this.createHttp2Server(credentials); + const sessionsSet = /* @__PURE__ */ new Set(); + this.http2Servers.set(server, { + channelzRef, + sessions: sessionsSet, + ownsChannelzRef + }); + return { + injectConnection: (connection) => { + server.emit("connection", connection); + }, + drain: (graceTimeMs) => { + var _b, _c; + for (const session of sessionsSet) { + this.closeSession(session); + } + (_c = (_b = setTimeout(() => { + for (const session of sessionsSet) { + session.destroy(http2.constants.NGHTTP2_CANCEL); + } + }, graceTimeMs)).unref) === null || _c === void 0 ? void 0 : _c.call(_b); + }, + destroy: () => { + this.closeServer(server); + for (const session of sessionsSet) { + this.closeSession(session); + } + } + }; + } + createConnectionInjector(credentials) { + if (credentials === null || !(credentials instanceof server_credentials_1.ServerCredentials)) { + throw new TypeError("creds must be a ServerCredentials object"); + } + const channelzRef = this.registerInjectorToChannelz(); + return this.experimentalCreateConnectionInjectorWithChannelzRef(credentials, channelzRef, true); + } + closeServer(server, callback) { + this.trace("Closing server with address " + JSON.stringify(server.address())); + const serverInfo = this.http2Servers.get(server); + server.close(() => { + if (serverInfo && serverInfo.ownsChannelzRef) { + this.listenerChildrenTracker.unrefChild(serverInfo.channelzRef); + (0, channelz_1.unregisterChannelzRef)(serverInfo.channelzRef); + } + this.http2Servers.delete(server); + callback === null || callback === void 0 ? void 0 : callback(); + }); + } + closeSession(session, callback) { + var _b; + this.trace("Closing session initiated by " + ((_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress)); + const sessionInfo = this.sessions.get(session); + const closeCallback = () => { + if (sessionInfo) { + this.sessionChildrenTracker.unrefChild(sessionInfo.ref); + (0, channelz_1.unregisterChannelzRef)(sessionInfo.ref); + } + callback === null || callback === void 0 ? void 0 : callback(); + }; + if (session.closed) { + queueMicrotask(closeCallback); + } else { + session.close(closeCallback); + } + } + completeUnbind(boundPortObject) { + for (const server of boundPortObject.listeningServers) { + const serverInfo = this.http2Servers.get(server); + this.closeServer(server, () => { + boundPortObject.listeningServers.delete(server); + }); + if (serverInfo) { + for (const session of serverInfo.sessions) { + this.closeSession(session); + } + } + } + this.boundPorts.delete(boundPortObject.mapKey); + } + /** + * Unbind a previously bound port, or cancel an in-progress bindAsync + * operation. If port 0 was bound, only the actual bound port can be + * unbound. For example, if bindAsync was called with "localhost:0" and the + * bound port result was 54321, it can be unbound as "localhost:54321". + * @param port + */ + unbind(port) { + this.trace("unbind port=" + port); + const portUri = this.normalizePort(port); + const splitPort = (0, uri_parser_1.splitHostPort)(portUri.path); + if ((splitPort === null || splitPort === void 0 ? void 0 : splitPort.port) === 0) { + throw new Error("Cannot unbind port 0"); + } + const boundPortObject = this.boundPorts.get((0, uri_parser_1.uriToString)(portUri)); + if (boundPortObject) { + this.trace("unbinding " + boundPortObject.mapKey + " originally bound as " + (0, uri_parser_1.uriToString)(boundPortObject.originalUri)); + if (boundPortObject.completionPromise) { + boundPortObject.cancelled = true; + } else { + this.completeUnbind(boundPortObject); + } + } + } + /** + * Gracefully close all connections associated with a previously bound port. + * After the grace time, forcefully close all remaining open connections. + * + * If port 0 was bound, only the actual bound port can be + * drained. For example, if bindAsync was called with "localhost:0" and the + * bound port result was 54321, it can be drained as "localhost:54321". + * @param port + * @param graceTimeMs + * @returns + */ + drain(port, graceTimeMs) { + var _b, _c; + this.trace("drain port=" + port + " graceTimeMs=" + graceTimeMs); + const portUri = this.normalizePort(port); + const splitPort = (0, uri_parser_1.splitHostPort)(portUri.path); + if ((splitPort === null || splitPort === void 0 ? void 0 : splitPort.port) === 0) { + throw new Error("Cannot drain port 0"); + } + const boundPortObject = this.boundPorts.get((0, uri_parser_1.uriToString)(portUri)); + if (!boundPortObject) { + return; + } + const allSessions = /* @__PURE__ */ new Set(); + for (const http2Server of boundPortObject.listeningServers) { + const serverEntry = this.http2Servers.get(http2Server); + if (serverEntry) { + for (const session of serverEntry.sessions) { + allSessions.add(session); + this.closeSession(session, () => { + allSessions.delete(session); + }); + } + } + } + (_c = (_b = setTimeout(() => { + for (const session of allSessions) { + session.destroy(http2.constants.NGHTTP2_CANCEL); + } + }, graceTimeMs)).unref) === null || _c === void 0 ? void 0 : _c.call(_b); + } + forceShutdown() { + for (const boundPortObject of this.boundPorts.values()) { + boundPortObject.cancelled = true; + } + this.boundPorts.clear(); + for (const server of this.http2Servers.keys()) { + this.closeServer(server); + } + this.sessions.forEach((channelzInfo, session) => { + this.closeSession(session); + session.destroy(http2.constants.NGHTTP2_CANCEL); + }); + this.sessions.clear(); + (0, channelz_1.unregisterChannelzRef)(this.channelzRef); + this.shutdown = true; + } + register(name, handler2, serialize, deserialize, type) { + if (this.handlers.has(name)) { + return false; + } + this.handlers.set(name, { + func: handler2, + serialize, + deserialize, + type, + path: name + }); + return true; + } + unregister(name) { + return this.handlers.delete(name); + } + /** + * @deprecated No longer needed as of version 1.10.x + */ + start() { + if (this.http2Servers.size === 0 || [...this.http2Servers.keys()].every((server) => !server.listening)) { + throw new Error("server must be bound in order to start"); + } + if (this.started === true) { + throw new Error("server is already started"); + } + this.started = true; + } + tryShutdown(callback) { + var _b; + const wrappedCallback = (error2) => { + (0, channelz_1.unregisterChannelzRef)(this.channelzRef); + callback(error2); + }; + let pendingChecks = 0; + function maybeCallback() { + pendingChecks--; + if (pendingChecks === 0) { + wrappedCallback(); + } + } + this.shutdown = true; + for (const [serverKey, server] of this.http2Servers.entries()) { + pendingChecks++; + const serverString = server.channelzRef.name; + this.trace("Waiting for server " + serverString + " to close"); + this.closeServer(serverKey, () => { + this.trace("Server " + serverString + " finished closing"); + maybeCallback(); + }); + for (const session of server.sessions.keys()) { + pendingChecks++; + const sessionString = (_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress; + this.trace("Waiting for session " + sessionString + " to close"); + this.closeSession(session, () => { + this.trace("Session " + sessionString + " finished closing"); + maybeCallback(); + }); + } + } + if (pendingChecks === 0) { + wrappedCallback(); + } + } + addHttp2Port() { + throw new Error("Not yet implemented"); + } + /** + * Get the channelz reference object for this server. The returned value is + * garbage if channelz is disabled for this server. + * @returns + */ + getChannelzRef() { + return this.channelzRef; + } + _verifyContentType(stream2, headers) { + const contentType = headers[http2.constants.HTTP2_HEADER_CONTENT_TYPE]; + if (typeof contentType !== "string" || !contentType.startsWith("application/grpc")) { + stream2.respond({ + [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE + }, { endStream: true }); + return false; + } + return true; + } + _retrieveHandler(path) { + serverCallTrace("Received call to method " + path + " at address " + this.serverAddressString); + const handler2 = this.handlers.get(path); + if (handler2 === void 0) { + serverCallTrace("No handler registered for method " + path + ". Sending UNIMPLEMENTED status."); + return null; + } + return handler2; + } + _respondWithError(err, stream2, channelzSessionInfo = null) { + var _b, _c; + const trailersToSend = Object.assign({ "grpc-status": (_b = err.code) !== null && _b !== void 0 ? _b : constants_1.Status.INTERNAL, "grpc-message": err.details, [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_OK, [http2.constants.HTTP2_HEADER_CONTENT_TYPE]: "application/grpc+proto" }, (_c = err.metadata) === null || _c === void 0 ? void 0 : _c.toHttp2Headers()); + stream2.respond(trailersToSend, { endStream: true }); + this.callTracker.addCallFailed(); + channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed(); + } + _channelzHandler(extraInterceptors, stream2, headers) { + stream2.once("error", (err) => { + }); + this.onStreamOpened(stream2); + const channelzSessionInfo = this.sessions.get(stream2.session); + this.callTracker.addCallStarted(); + channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallStarted(); + if (!this._verifyContentType(stream2, headers)) { + this.callTracker.addCallFailed(); + channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed(); + return; + } + const path = headers[HTTP2_HEADER_PATH]; + const handler2 = this._retrieveHandler(path); + if (!handler2) { + this._respondWithError(getUnimplementedStatusResponse(path), stream2, channelzSessionInfo); + return; + } + const callEventTracker = { + addMessageSent: () => { + if (channelzSessionInfo) { + channelzSessionInfo.messagesSent += 1; + channelzSessionInfo.lastMessageSentTimestamp = /* @__PURE__ */ new Date(); + } + }, + addMessageReceived: () => { + if (channelzSessionInfo) { + channelzSessionInfo.messagesReceived += 1; + channelzSessionInfo.lastMessageReceivedTimestamp = /* @__PURE__ */ new Date(); + } + }, + onCallEnd: (status) => { + if (status.code === constants_1.Status.OK) { + this.callTracker.addCallSucceeded(); + } else { + this.callTracker.addCallFailed(); + } + }, + onStreamEnd: (success) => { + if (channelzSessionInfo) { + if (success) { + channelzSessionInfo.streamTracker.addCallSucceeded(); + } else { + channelzSessionInfo.streamTracker.addCallFailed(); + } + } + } + }; + const call = (0, server_interceptors_1.getServerInterceptingCall)([...extraInterceptors, ...this.interceptors], stream2, headers, callEventTracker, handler2, this.options); + if (!this._runHandlerForCall(call, handler2)) { + this.callTracker.addCallFailed(); + channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed(); + call.sendStatus({ + code: constants_1.Status.INTERNAL, + details: `Unknown handler type: ${handler2.type}` + }); + } + } + _streamHandler(extraInterceptors, stream2, headers) { + stream2.once("error", (err) => { + }); + this.onStreamOpened(stream2); + if (this._verifyContentType(stream2, headers) !== true) { + return; + } + const path = headers[HTTP2_HEADER_PATH]; + const handler2 = this._retrieveHandler(path); + if (!handler2) { + this._respondWithError(getUnimplementedStatusResponse(path), stream2, null); + return; + } + const call = (0, server_interceptors_1.getServerInterceptingCall)([...extraInterceptors, ...this.interceptors], stream2, headers, null, handler2, this.options); + if (!this._runHandlerForCall(call, handler2)) { + call.sendStatus({ + code: constants_1.Status.INTERNAL, + details: `Unknown handler type: ${handler2.type}` + }); + } + } + _runHandlerForCall(call, handler2) { + const { type } = handler2; + if (type === "unary") { + handleUnary(call, handler2); + } else if (type === "clientStream") { + handleClientStreaming(call, handler2); + } else if (type === "serverStream") { + handleServerStreaming(call, handler2); + } else if (type === "bidi") { + handleBidiStreaming(call, handler2); + } else { + return false; + } + return true; + } + _setupHandlers(http2Server, extraInterceptors) { + if (http2Server === null) { + return; + } + const serverAddress = http2Server.address(); + let serverAddressString = "null"; + if (serverAddress) { + if (typeof serverAddress === "string") { + serverAddressString = serverAddress; + } else { + serverAddressString = serverAddress.address + ":" + serverAddress.port; + } + } + this.serverAddressString = serverAddressString; + const handler2 = this.channelzEnabled ? this._channelzHandler : this._streamHandler; + const sessionHandler = this.channelzEnabled ? this._channelzSessionHandler(http2Server) : this._sessionHandler(http2Server); + http2Server.on("stream", handler2.bind(this, extraInterceptors)); + http2Server.on("session", sessionHandler); + } + _sessionHandler(http2Server) { + return (session) => { + var _b, _c; + (_b = this.http2Servers.get(http2Server)) === null || _b === void 0 ? void 0 : _b.sessions.add(session); + let connectionAgeTimer = null; + let connectionAgeGraceTimer = null; + let keepaliveTimer = null; + let sessionClosedByServer = false; + const idleTimeoutObj = this.enableIdleTimeout(session); + if (this.maxConnectionAgeMs !== UNLIMITED_CONNECTION_AGE_MS) { + const jitterMagnitude = this.maxConnectionAgeMs / 10; + const jitter = Math.random() * jitterMagnitude * 2 - jitterMagnitude; + connectionAgeTimer = setTimeout(() => { + var _b2, _c2; + sessionClosedByServer = true; + this.trace("Connection dropped by max connection age: " + ((_b2 = session.socket) === null || _b2 === void 0 ? void 0 : _b2.remoteAddress)); + try { + session.goaway(http2.constants.NGHTTP2_NO_ERROR, ~(1 << 31), kMaxAge); + } catch (e) { + session.destroy(); + return; + } + session.close(); + if (this.maxConnectionAgeGraceMs !== UNLIMITED_CONNECTION_AGE_MS) { + connectionAgeGraceTimer = setTimeout(() => { + session.destroy(); + }, this.maxConnectionAgeGraceMs); + (_c2 = connectionAgeGraceTimer.unref) === null || _c2 === void 0 ? void 0 : _c2.call(connectionAgeGraceTimer); + } + }, this.maxConnectionAgeMs + jitter); + (_c = connectionAgeTimer.unref) === null || _c === void 0 ? void 0 : _c.call(connectionAgeTimer); + } + const clearKeepaliveTimeout = () => { + if (keepaliveTimer) { + clearTimeout(keepaliveTimer); + keepaliveTimer = null; + } + }; + const canSendPing = () => { + return !session.destroyed && this.keepaliveTimeMs < KEEPALIVE_MAX_TIME_MS && this.keepaliveTimeMs > 0; + }; + let sendPing; + const maybeStartKeepalivePingTimer = () => { + var _b2; + if (!canSendPing()) { + return; + } + this.keepaliveTrace("Starting keepalive timer for " + this.keepaliveTimeMs + "ms"); + keepaliveTimer = setTimeout(() => { + clearKeepaliveTimeout(); + sendPing(); + }, this.keepaliveTimeMs); + (_b2 = keepaliveTimer.unref) === null || _b2 === void 0 ? void 0 : _b2.call(keepaliveTimer); + }; + sendPing = () => { + var _b2; + if (!canSendPing()) { + return; + } + this.keepaliveTrace("Sending ping with timeout " + this.keepaliveTimeoutMs + "ms"); + let pingSendError = ""; + try { + const pingSentSuccessfully = session.ping((err, duration, payload) => { + clearKeepaliveTimeout(); + if (err) { + this.keepaliveTrace("Ping failed with error: " + err.message); + sessionClosedByServer = true; + session.destroy(); + } else { + this.keepaliveTrace("Received ping response"); + maybeStartKeepalivePingTimer(); + } + }); + if (!pingSentSuccessfully) { + pingSendError = "Ping returned false"; + } + } catch (e) { + pingSendError = (e instanceof Error ? e.message : "") || "Unknown error"; + } + if (pingSendError) { + this.keepaliveTrace("Ping send failed: " + pingSendError); + this.trace("Connection dropped due to ping send error: " + pingSendError); + sessionClosedByServer = true; + session.destroy(); + return; + } + keepaliveTimer = setTimeout(() => { + clearKeepaliveTimeout(); + this.keepaliveTrace("Ping timeout passed without response"); + this.trace("Connection dropped by keepalive timeout"); + sessionClosedByServer = true; + session.destroy(); + }, this.keepaliveTimeoutMs); + (_b2 = keepaliveTimer.unref) === null || _b2 === void 0 ? void 0 : _b2.call(keepaliveTimer); + }; + maybeStartKeepalivePingTimer(); + session.on("close", () => { + var _b2, _c2; + if (!sessionClosedByServer) { + this.trace(`Connection dropped by client ${(_b2 = session.socket) === null || _b2 === void 0 ? void 0 : _b2.remoteAddress}`); + } + if (connectionAgeTimer) { + clearTimeout(connectionAgeTimer); + } + if (connectionAgeGraceTimer) { + clearTimeout(connectionAgeGraceTimer); + } + clearKeepaliveTimeout(); + if (idleTimeoutObj !== null) { + clearTimeout(idleTimeoutObj.timeout); + this.sessionIdleTimeouts.delete(session); + } + (_c2 = this.http2Servers.get(http2Server)) === null || _c2 === void 0 ? void 0 : _c2.sessions.delete(session); + }); + }; + } + _channelzSessionHandler(http2Server) { + return (session) => { + var _b, _c, _d, _e; + const channelzRef = (0, channelz_1.registerChannelzSocket)((_c = (_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress) !== null && _c !== void 0 ? _c : "unknown", this.getChannelzSessionInfo.bind(this, session), this.channelzEnabled); + const channelzSessionInfo = { + ref: channelzRef, + streamTracker: new channelz_1.ChannelzCallTracker(), + messagesSent: 0, + messagesReceived: 0, + keepAlivesSent: 0, + lastMessageSentTimestamp: null, + lastMessageReceivedTimestamp: null + }; + (_d = this.http2Servers.get(http2Server)) === null || _d === void 0 ? void 0 : _d.sessions.add(session); + this.sessions.set(session, channelzSessionInfo); + const clientAddress = `${session.socket.remoteAddress}:${session.socket.remotePort}`; + this.channelzTrace.addTrace("CT_INFO", "Connection established by client " + clientAddress); + this.trace("Connection established by client " + clientAddress); + this.sessionChildrenTracker.refChild(channelzRef); + let connectionAgeTimer = null; + let connectionAgeGraceTimer = null; + let keepaliveTimeout = null; + let sessionClosedByServer = false; + const idleTimeoutObj = this.enableIdleTimeout(session); + if (this.maxConnectionAgeMs !== UNLIMITED_CONNECTION_AGE_MS) { + const jitterMagnitude = this.maxConnectionAgeMs / 10; + const jitter = Math.random() * jitterMagnitude * 2 - jitterMagnitude; + connectionAgeTimer = setTimeout(() => { + var _b2; + sessionClosedByServer = true; + this.channelzTrace.addTrace("CT_INFO", "Connection dropped by max connection age from " + clientAddress); + try { + session.goaway(http2.constants.NGHTTP2_NO_ERROR, ~(1 << 31), kMaxAge); + } catch (e) { + session.destroy(); + return; + } + session.close(); + if (this.maxConnectionAgeGraceMs !== UNLIMITED_CONNECTION_AGE_MS) { + connectionAgeGraceTimer = setTimeout(() => { + session.destroy(); + }, this.maxConnectionAgeGraceMs); + (_b2 = connectionAgeGraceTimer.unref) === null || _b2 === void 0 ? void 0 : _b2.call(connectionAgeGraceTimer); + } + }, this.maxConnectionAgeMs + jitter); + (_e = connectionAgeTimer.unref) === null || _e === void 0 ? void 0 : _e.call(connectionAgeTimer); + } + const clearKeepaliveTimeout = () => { + if (keepaliveTimeout) { + clearTimeout(keepaliveTimeout); + keepaliveTimeout = null; + } + }; + const canSendPing = () => { + return !session.destroyed && this.keepaliveTimeMs < KEEPALIVE_MAX_TIME_MS && this.keepaliveTimeMs > 0; + }; + let sendPing; + const maybeStartKeepalivePingTimer = () => { + var _b2; + if (!canSendPing()) { + return; + } + this.keepaliveTrace("Starting keepalive timer for " + this.keepaliveTimeMs + "ms"); + keepaliveTimeout = setTimeout(() => { + clearKeepaliveTimeout(); + sendPing(); + }, this.keepaliveTimeMs); + (_b2 = keepaliveTimeout.unref) === null || _b2 === void 0 ? void 0 : _b2.call(keepaliveTimeout); + }; + sendPing = () => { + var _b2; + if (!canSendPing()) { + return; + } + this.keepaliveTrace("Sending ping with timeout " + this.keepaliveTimeoutMs + "ms"); + let pingSendError = ""; + try { + const pingSentSuccessfully = session.ping((err, duration, payload) => { + clearKeepaliveTimeout(); + if (err) { + this.keepaliveTrace("Ping failed with error: " + err.message); + this.channelzTrace.addTrace("CT_INFO", "Connection dropped due to error of a ping frame " + err.message + " return in " + duration); + sessionClosedByServer = true; + session.destroy(); + } else { + this.keepaliveTrace("Received ping response"); + maybeStartKeepalivePingTimer(); + } + }); + if (!pingSentSuccessfully) { + pingSendError = "Ping returned false"; + } + } catch (e) { + pingSendError = (e instanceof Error ? e.message : "") || "Unknown error"; + } + if (pingSendError) { + this.keepaliveTrace("Ping send failed: " + pingSendError); + this.channelzTrace.addTrace("CT_INFO", "Connection dropped due to ping send error: " + pingSendError); + sessionClosedByServer = true; + session.destroy(); + return; + } + channelzSessionInfo.keepAlivesSent += 1; + keepaliveTimeout = setTimeout(() => { + clearKeepaliveTimeout(); + this.keepaliveTrace("Ping timeout passed without response"); + this.channelzTrace.addTrace("CT_INFO", "Connection dropped by keepalive timeout from " + clientAddress); + sessionClosedByServer = true; + session.destroy(); + }, this.keepaliveTimeoutMs); + (_b2 = keepaliveTimeout.unref) === null || _b2 === void 0 ? void 0 : _b2.call(keepaliveTimeout); + }; + maybeStartKeepalivePingTimer(); + session.on("close", () => { + var _b2; + if (!sessionClosedByServer) { + this.channelzTrace.addTrace("CT_INFO", "Connection dropped by client " + clientAddress); + } + this.sessionChildrenTracker.unrefChild(channelzRef); + (0, channelz_1.unregisterChannelzRef)(channelzRef); + if (connectionAgeTimer) { + clearTimeout(connectionAgeTimer); + } + if (connectionAgeGraceTimer) { + clearTimeout(connectionAgeGraceTimer); + } + clearKeepaliveTimeout(); + if (idleTimeoutObj !== null) { + clearTimeout(idleTimeoutObj.timeout); + this.sessionIdleTimeouts.delete(session); + } + (_b2 = this.http2Servers.get(http2Server)) === null || _b2 === void 0 ? void 0 : _b2.sessions.delete(session); + this.sessions.delete(session); + }); + }; + } + enableIdleTimeout(session) { + var _b, _c; + if (this.sessionIdleTimeout >= MAX_CONNECTION_IDLE_MS) { + return null; + } + const idleTimeoutObj = { + activeStreams: 0, + lastIdle: Date.now(), + onClose: this.onStreamClose.bind(this, session), + timeout: setTimeout(this.onIdleTimeout, this.sessionIdleTimeout, this, session) + }; + (_c = (_b = idleTimeoutObj.timeout).unref) === null || _c === void 0 ? void 0 : _c.call(_b); + this.sessionIdleTimeouts.set(session, idleTimeoutObj); + const { socket } = session; + this.trace("Enable idle timeout for " + socket.remoteAddress + ":" + socket.remotePort); + return idleTimeoutObj; + } + onIdleTimeout(ctx, session) { + const { socket } = session; + const sessionInfo = ctx.sessionIdleTimeouts.get(session); + if (sessionInfo !== void 0 && sessionInfo.activeStreams === 0) { + if (Date.now() - sessionInfo.lastIdle >= ctx.sessionIdleTimeout) { + ctx.trace("Session idle timeout triggered for " + (socket === null || socket === void 0 ? void 0 : socket.remoteAddress) + ":" + (socket === null || socket === void 0 ? void 0 : socket.remotePort) + " last idle at " + sessionInfo.lastIdle); + ctx.closeSession(session); + } else { + sessionInfo.timeout.refresh(); + } + } + } + onStreamOpened(stream2) { + const session = stream2.session; + const idleTimeoutObj = this.sessionIdleTimeouts.get(session); + if (idleTimeoutObj) { + idleTimeoutObj.activeStreams += 1; + stream2.once("close", idleTimeoutObj.onClose); + } + } + onStreamClose(session) { + var _b, _c; + const idleTimeoutObj = this.sessionIdleTimeouts.get(session); + if (idleTimeoutObj) { + idleTimeoutObj.activeStreams -= 1; + if (idleTimeoutObj.activeStreams === 0) { + idleTimeoutObj.lastIdle = Date.now(); + idleTimeoutObj.timeout.refresh(); + this.trace("Session onStreamClose" + ((_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress) + ":" + ((_c = session.socket) === null || _c === void 0 ? void 0 : _c.remotePort) + " at " + idleTimeoutObj.lastIdle); + } + } + } + }, (() => { + const _metadata = typeof Symbol === "function" && Symbol.metadata ? /* @__PURE__ */ Object.create(null) : void 0; + _start_decorators = [deprecate("Calling start() is no longer necessary. It can be safely omitted.")]; + __esDecorate(_a, null, _start_decorators, { kind: "method", name: "start", static: false, private: false, access: { has: (obj) => "start" in obj, get: (obj) => obj.start }, metadata: _metadata }, null, _instanceExtraInitializers); + if (_metadata) Object.defineProperty(_a, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); + })(), _a; + })(); + exports2.Server = Server; + async function handleUnary(call, handler2) { + let stream2; + function respond(err, value, trailer, flags) { + if (err) { + call.sendStatus((0, server_call_1.serverErrorToStatus)(err, trailer)); + return; + } + call.sendMessage(value, () => { + call.sendStatus({ + code: constants_1.Status.OK, + details: "OK", + metadata: trailer !== null && trailer !== void 0 ? trailer : null + }); + }); + } + let requestMetadata; + let requestMessage = null; + call.start({ + onReceiveMetadata(metadata) { + requestMetadata = metadata; + call.startRead(); + }, + onReceiveMessage(message) { + if (requestMessage) { + call.sendStatus({ + code: constants_1.Status.UNIMPLEMENTED, + details: `Received a second request message for server streaming method ${handler2.path}`, + metadata: null + }); + return; + } + requestMessage = message; + call.startRead(); + }, + onReceiveHalfClose() { + if (!requestMessage) { + call.sendStatus({ + code: constants_1.Status.UNIMPLEMENTED, + details: `Received no request message for server streaming method ${handler2.path}`, + metadata: null + }); + return; + } + stream2 = new server_call_1.ServerWritableStreamImpl(handler2.path, call, requestMetadata, requestMessage); + try { + handler2.func(stream2, respond); + } catch (err) { + call.sendStatus({ + code: constants_1.Status.UNKNOWN, + details: `Server method handler threw error ${err.message}`, + metadata: null + }); + } + }, + onCancel() { + if (stream2) { + stream2.cancelled = true; + stream2.emit("cancelled", "cancelled"); + } + } + }); + } + function handleClientStreaming(call, handler2) { + let stream2; + function respond(err, value, trailer, flags) { + if (err) { + call.sendStatus((0, server_call_1.serverErrorToStatus)(err, trailer)); + return; + } + call.sendMessage(value, () => { + call.sendStatus({ + code: constants_1.Status.OK, + details: "OK", + metadata: trailer !== null && trailer !== void 0 ? trailer : null + }); + }); + } + call.start({ + onReceiveMetadata(metadata) { + stream2 = new server_call_1.ServerDuplexStreamImpl(handler2.path, call, metadata); + try { + handler2.func(stream2, respond); + } catch (err) { + call.sendStatus({ + code: constants_1.Status.UNKNOWN, + details: `Server method handler threw error ${err.message}`, + metadata: null + }); + } + }, + onReceiveMessage(message) { + stream2.push(message); + }, + onReceiveHalfClose() { + stream2.push(null); + }, + onCancel() { + if (stream2) { + stream2.cancelled = true; + stream2.emit("cancelled", "cancelled"); + stream2.destroy(); + } + } + }); + } + function handleServerStreaming(call, handler2) { + let stream2; + let requestMetadata; + let requestMessage = null; + call.start({ + onReceiveMetadata(metadata) { + requestMetadata = metadata; + call.startRead(); + }, + onReceiveMessage(message) { + if (requestMessage) { + call.sendStatus({ + code: constants_1.Status.UNIMPLEMENTED, + details: `Received a second request message for server streaming method ${handler2.path}`, + metadata: null + }); + return; + } + requestMessage = message; + call.startRead(); + }, + onReceiveHalfClose() { + if (!requestMessage) { + call.sendStatus({ + code: constants_1.Status.UNIMPLEMENTED, + details: `Received no request message for server streaming method ${handler2.path}`, + metadata: null + }); + return; + } + stream2 = new server_call_1.ServerWritableStreamImpl(handler2.path, call, requestMetadata, requestMessage); + try { + handler2.func(stream2); + } catch (err) { + call.sendStatus({ + code: constants_1.Status.UNKNOWN, + details: `Server method handler threw error ${err.message}`, + metadata: null + }); + } + }, + onCancel() { + if (stream2) { + stream2.cancelled = true; + stream2.emit("cancelled", "cancelled"); + stream2.destroy(); + } + } + }); + } + function handleBidiStreaming(call, handler2) { + let stream2; + call.start({ + onReceiveMetadata(metadata) { + stream2 = new server_call_1.ServerDuplexStreamImpl(handler2.path, call, metadata); + try { + handler2.func(stream2); + } catch (err) { + call.sendStatus({ + code: constants_1.Status.UNKNOWN, + details: `Server method handler threw error ${err.message}`, + metadata: null + }); + } + }, + onReceiveMessage(message) { + stream2.push(message); + }, + onReceiveHalfClose() { + stream2.push(null); + }, + onCancel() { + if (stream2) { + stream2.cancelled = true; + stream2.emit("cancelled", "cancelled"); + stream2.destroy(); + } + } + }); + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/status-builder.js +var require_status_builder = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/status-builder.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.StatusBuilder = void 0; + var StatusBuilder = class { + constructor() { + this.code = null; + this.details = null; + this.metadata = null; + } + /** + * Adds a status code to the builder. + */ + withCode(code) { + this.code = code; + return this; + } + /** + * Adds details to the builder. + */ + withDetails(details) { + this.details = details; + return this; + } + /** + * Adds metadata to the builder. + */ + withMetadata(metadata) { + this.metadata = metadata; + return this; + } + /** + * Builds the status object. + */ + build() { + const status = {}; + if (this.code !== null) { + status.code = this.code; + } + if (this.details !== null) { + status.details = this.details; + } + if (this.metadata !== null) { + status.metadata = this.metadata; + } + return status; + } + }; + exports2.StatusBuilder = StatusBuilder; + } +}); + +// node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.js +var require_load_balancer_pick_first = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.LeafLoadBalancer = exports2.PickFirstLoadBalancer = exports2.PickFirstLoadBalancingConfig = void 0; + exports2.shuffled = shuffled; + exports2.setup = setup; + var load_balancer_1 = require_load_balancer(); + var connectivity_state_1 = require_connectivity_state(); + var picker_1 = require_picker(); + var subchannel_address_1 = require_subchannel_address(); + var logging = require_logging(); + var constants_1 = require_constants7(); + var subchannel_address_2 = require_subchannel_address(); + var net_1 = require("net"); + var call_interface_1 = require_call_interface(); + var TRACER_NAME = "pick_first"; + function trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); + } + var TYPE_NAME = "pick_first"; + var CONNECTION_DELAY_INTERVAL_MS = 250; + var PickFirstLoadBalancingConfig = class _PickFirstLoadBalancingConfig { + constructor(shuffleAddressList) { + this.shuffleAddressList = shuffleAddressList; + } + getLoadBalancerName() { + return TYPE_NAME; + } + toJsonObject() { + return { + [TYPE_NAME]: { + shuffleAddressList: this.shuffleAddressList + } + }; + } + getShuffleAddressList() { + return this.shuffleAddressList; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static createFromJson(obj) { + if ("shuffleAddressList" in obj && !(typeof obj.shuffleAddressList === "boolean")) { + throw new Error("pick_first config field shuffleAddressList must be a boolean if provided"); + } + return new _PickFirstLoadBalancingConfig(obj.shuffleAddressList === true); + } + }; + exports2.PickFirstLoadBalancingConfig = PickFirstLoadBalancingConfig; + var PickFirstPicker = class { + constructor(subchannel) { + this.subchannel = subchannel; + } + pick(pickArgs) { + return { + pickResultType: picker_1.PickResultType.COMPLETE, + subchannel: this.subchannel, + status: null, + onCallStarted: null, + onCallEnded: null + }; + } + }; + function shuffled(list) { + const result = list.slice(); + for (let i = result.length - 1; i > 1; i--) { + const j = Math.floor(Math.random() * (i + 1)); + const temp = result[i]; + result[i] = result[j]; + result[j] = temp; + } + return result; + } + function interleaveAddressFamilies(addressList) { + if (addressList.length === 0) { + return []; + } + const result = []; + const ipv6Addresses = []; + const ipv4Addresses = []; + const ipv6First = (0, subchannel_address_2.isTcpSubchannelAddress)(addressList[0]) && (0, net_1.isIPv6)(addressList[0].host); + for (const address of addressList) { + if ((0, subchannel_address_2.isTcpSubchannelAddress)(address) && (0, net_1.isIPv6)(address.host)) { + ipv6Addresses.push(address); + } else { + ipv4Addresses.push(address); + } + } + const firstList = ipv6First ? ipv6Addresses : ipv4Addresses; + const secondList = ipv6First ? ipv4Addresses : ipv6Addresses; + for (let i = 0; i < Math.max(firstList.length, secondList.length); i++) { + if (i < firstList.length) { + result.push(firstList[i]); + } + if (i < secondList.length) { + result.push(secondList[i]); + } + } + return result; + } + var REPORT_HEALTH_STATUS_OPTION_NAME = "grpc-node.internal.pick-first.report_health_status"; + var PickFirstLoadBalancer = class { + /** + * Load balancer that attempts to connect to each backend in the address list + * in order, and picks the first one that connects, using it for every + * request. + * @param channelControlHelper `ChannelControlHelper` instance provided by + * this load balancer's owner. + */ + constructor(channelControlHelper) { + this.channelControlHelper = channelControlHelper; + this.children = []; + this.currentState = connectivity_state_1.ConnectivityState.IDLE; + this.currentSubchannelIndex = 0; + this.currentPick = null; + this.subchannelStateListener = (subchannel, previousState, newState, keepaliveTime, errorMessage) => { + this.onSubchannelStateUpdate(subchannel, previousState, newState, errorMessage); + }; + this.pickedSubchannelHealthListener = () => this.calculateAndReportNewState(); + this.stickyTransientFailureMode = false; + this.reportHealthStatus = false; + this.lastError = null; + this.latestAddressList = null; + this.latestOptions = {}; + this.latestResolutionNote = ""; + this.connectionDelayTimeout = setTimeout(() => { + }, 0); + clearTimeout(this.connectionDelayTimeout); + } + allChildrenHaveReportedTF() { + return this.children.every((child) => child.hasReportedTransientFailure); + } + resetChildrenReportedTF() { + this.children.every((child) => child.hasReportedTransientFailure = false); + } + calculateAndReportNewState() { + var _a; + if (this.currentPick) { + if (this.reportHealthStatus && !this.currentPick.isHealthy()) { + const errorMessage = `Picked subchannel ${this.currentPick.getAddress()} is unhealthy`; + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ + details: errorMessage + }), errorMessage); + } else { + this.updateState(connectivity_state_1.ConnectivityState.READY, new PickFirstPicker(this.currentPick), null); + } + } else if (((_a = this.latestAddressList) === null || _a === void 0 ? void 0 : _a.length) === 0) { + const errorMessage = `No connection established. Last error: ${this.lastError}. Resolution note: ${this.latestResolutionNote}`; + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ + details: errorMessage + }), errorMessage); + } else if (this.children.length === 0) { + this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null); + } else { + if (this.stickyTransientFailureMode) { + const errorMessage = `No connection established. Last error: ${this.lastError}. Resolution note: ${this.latestResolutionNote}`; + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ + details: errorMessage + }), errorMessage); + } else { + this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this), null); + } + } + } + requestReresolution() { + this.channelControlHelper.requestReresolution(); + } + maybeEnterStickyTransientFailureMode() { + if (!this.allChildrenHaveReportedTF()) { + return; + } + this.requestReresolution(); + this.resetChildrenReportedTF(); + if (this.stickyTransientFailureMode) { + this.calculateAndReportNewState(); + return; + } + this.stickyTransientFailureMode = true; + for (const { subchannel } of this.children) { + subchannel.startConnecting(); + } + this.calculateAndReportNewState(); + } + removeCurrentPick() { + if (this.currentPick !== null) { + this.currentPick.removeConnectivityStateListener(this.subchannelStateListener); + this.channelControlHelper.removeChannelzChild(this.currentPick.getChannelzRef()); + this.currentPick.removeHealthStateWatcher(this.pickedSubchannelHealthListener); + this.currentPick.unref(); + this.currentPick = null; + } + } + onSubchannelStateUpdate(subchannel, previousState, newState, errorMessage) { + var _a; + if ((_a = this.currentPick) === null || _a === void 0 ? void 0 : _a.realSubchannelEquals(subchannel)) { + if (newState !== connectivity_state_1.ConnectivityState.READY) { + this.removeCurrentPick(); + this.calculateAndReportNewState(); + } + return; + } + for (const [index, child] of this.children.entries()) { + if (subchannel.realSubchannelEquals(child.subchannel)) { + if (newState === connectivity_state_1.ConnectivityState.READY) { + this.pickSubchannel(child.subchannel); + } + if (newState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { + child.hasReportedTransientFailure = true; + if (errorMessage) { + this.lastError = errorMessage; + } + this.maybeEnterStickyTransientFailureMode(); + if (index === this.currentSubchannelIndex) { + this.startNextSubchannelConnecting(index + 1); + } + } + child.subchannel.startConnecting(); + return; + } + } + } + startNextSubchannelConnecting(startIndex) { + clearTimeout(this.connectionDelayTimeout); + for (const [index, child] of this.children.entries()) { + if (index >= startIndex) { + const subchannelState = child.subchannel.getConnectivityState(); + if (subchannelState === connectivity_state_1.ConnectivityState.IDLE || subchannelState === connectivity_state_1.ConnectivityState.CONNECTING) { + this.startConnecting(index); + return; + } + } + } + this.maybeEnterStickyTransientFailureMode(); + } + /** + * Have a single subchannel in the `subchannels` list start connecting. + * @param subchannelIndex The index into the `subchannels` list. + */ + startConnecting(subchannelIndex) { + var _a, _b; + clearTimeout(this.connectionDelayTimeout); + this.currentSubchannelIndex = subchannelIndex; + if (this.children[subchannelIndex].subchannel.getConnectivityState() === connectivity_state_1.ConnectivityState.IDLE) { + trace("Start connecting to subchannel with address " + this.children[subchannelIndex].subchannel.getAddress()); + process.nextTick(() => { + var _a2; + (_a2 = this.children[subchannelIndex]) === null || _a2 === void 0 ? void 0 : _a2.subchannel.startConnecting(); + }); + } + this.connectionDelayTimeout = setTimeout(() => { + this.startNextSubchannelConnecting(subchannelIndex + 1); + }, CONNECTION_DELAY_INTERVAL_MS); + (_b = (_a = this.connectionDelayTimeout).unref) === null || _b === void 0 ? void 0 : _b.call(_a); + } + /** + * Declare that the specified subchannel should be used to make requests. + * This functions the same independent of whether subchannel is a member of + * this.children and whether it is equal to this.currentPick. + * Prerequisite: subchannel.getConnectivityState() === READY. + * @param subchannel + */ + pickSubchannel(subchannel) { + trace("Pick subchannel with address " + subchannel.getAddress()); + this.stickyTransientFailureMode = false; + subchannel.ref(); + this.channelControlHelper.addChannelzChild(subchannel.getChannelzRef()); + this.removeCurrentPick(); + this.resetSubchannelList(); + subchannel.addConnectivityStateListener(this.subchannelStateListener); + subchannel.addHealthStateWatcher(this.pickedSubchannelHealthListener); + this.currentPick = subchannel; + clearTimeout(this.connectionDelayTimeout); + this.calculateAndReportNewState(); + } + updateState(newState, picker, errorMessage) { + trace(connectivity_state_1.ConnectivityState[this.currentState] + " -> " + connectivity_state_1.ConnectivityState[newState]); + this.currentState = newState; + this.channelControlHelper.updateState(newState, picker, errorMessage); + } + resetSubchannelList() { + for (const child of this.children) { + child.subchannel.removeConnectivityStateListener(this.subchannelStateListener); + child.subchannel.unref(); + this.channelControlHelper.removeChannelzChild(child.subchannel.getChannelzRef()); + } + this.currentSubchannelIndex = 0; + this.children = []; + } + connectToAddressList(addressList, options) { + trace("connectToAddressList([" + addressList.map((address) => (0, subchannel_address_1.subchannelAddressToString)(address)) + "])"); + const newChildrenList = addressList.map((address) => ({ + subchannel: this.channelControlHelper.createSubchannel(address, options), + hasReportedTransientFailure: false + })); + for (const { subchannel } of newChildrenList) { + if (subchannel.getConnectivityState() === connectivity_state_1.ConnectivityState.READY) { + this.pickSubchannel(subchannel); + return; + } + } + for (const { subchannel } of newChildrenList) { + subchannel.ref(); + this.channelControlHelper.addChannelzChild(subchannel.getChannelzRef()); + } + this.resetSubchannelList(); + this.children = newChildrenList; + for (const { subchannel } of this.children) { + subchannel.addConnectivityStateListener(this.subchannelStateListener); + } + for (const child of this.children) { + if (child.subchannel.getConnectivityState() === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { + child.hasReportedTransientFailure = true; + } + } + this.startNextSubchannelConnecting(0); + this.calculateAndReportNewState(); + } + updateAddressList(maybeEndpointList, lbConfig, options, resolutionNote) { + if (!(lbConfig instanceof PickFirstLoadBalancingConfig)) { + return false; + } + if (!maybeEndpointList.ok) { + if (this.children.length === 0 && this.currentPick === null) { + this.channelControlHelper.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(maybeEndpointList.error), maybeEndpointList.error.details); + } + return true; + } + let endpointList = maybeEndpointList.value; + this.reportHealthStatus = options[REPORT_HEALTH_STATUS_OPTION_NAME]; + if (lbConfig.getShuffleAddressList()) { + endpointList = shuffled(endpointList); + } + const rawAddressList = [].concat(...endpointList.map((endpoint2) => endpoint2.addresses)); + trace("updateAddressList([" + rawAddressList.map((address) => (0, subchannel_address_1.subchannelAddressToString)(address)) + "])"); + const addressList = interleaveAddressFamilies(rawAddressList); + this.latestAddressList = addressList; + this.latestOptions = options; + this.connectToAddressList(addressList, options); + this.latestResolutionNote = resolutionNote; + if (rawAddressList.length > 0) { + return true; + } else { + this.lastError = "No addresses resolved"; + return false; + } + } + exitIdle() { + if (this.currentState === connectivity_state_1.ConnectivityState.IDLE && this.latestAddressList) { + this.connectToAddressList(this.latestAddressList, this.latestOptions); + } + } + resetBackoff() { + } + destroy() { + this.resetSubchannelList(); + this.removeCurrentPick(); + } + getTypeName() { + return TYPE_NAME; + } + }; + exports2.PickFirstLoadBalancer = PickFirstLoadBalancer; + var LEAF_CONFIG = new PickFirstLoadBalancingConfig(false); + var LeafLoadBalancer = class { + constructor(endpoint2, channelControlHelper, options, resolutionNote) { + this.endpoint = endpoint2; + this.options = options; + this.resolutionNote = resolutionNote; + this.latestState = connectivity_state_1.ConnectivityState.IDLE; + const childChannelControlHelper = (0, load_balancer_1.createChildChannelControlHelper)(channelControlHelper, { + updateState: (connectivityState, picker, errorMessage) => { + this.latestState = connectivityState; + this.latestPicker = picker; + channelControlHelper.updateState(connectivityState, picker, errorMessage); + } + }); + this.pickFirstBalancer = new PickFirstLoadBalancer(childChannelControlHelper); + this.latestPicker = new picker_1.QueuePicker(this.pickFirstBalancer); + } + startConnecting() { + this.pickFirstBalancer.updateAddressList((0, call_interface_1.statusOrFromValue)([this.endpoint]), LEAF_CONFIG, Object.assign(Object.assign({}, this.options), { [REPORT_HEALTH_STATUS_OPTION_NAME]: true }), this.resolutionNote); + } + /** + * Update the endpoint associated with this LeafLoadBalancer to a new + * endpoint. Does not trigger connection establishment if a connection + * attempt is not already in progress. + * @param newEndpoint + */ + updateEndpoint(newEndpoint, newOptions) { + this.options = newOptions; + this.endpoint = newEndpoint; + if (this.latestState !== connectivity_state_1.ConnectivityState.IDLE) { + this.startConnecting(); + } + } + getConnectivityState() { + return this.latestState; + } + getPicker() { + return this.latestPicker; + } + getEndpoint() { + return this.endpoint; + } + exitIdle() { + this.pickFirstBalancer.exitIdle(); + } + destroy() { + this.pickFirstBalancer.destroy(); + } + }; + exports2.LeafLoadBalancer = LeafLoadBalancer; + function setup() { + (0, load_balancer_1.registerLoadBalancerType)(TYPE_NAME, PickFirstLoadBalancer, PickFirstLoadBalancingConfig); + (0, load_balancer_1.registerDefaultLoadBalancerType)(TYPE_NAME); + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/certificate-provider.js +var require_certificate_provider = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/certificate-provider.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.FileWatcherCertificateProvider = void 0; + var fs4 = require("fs"); + var logging = require_logging(); + var constants_1 = require_constants7(); + var util_1 = require("util"); + var TRACER_NAME = "certificate_provider"; + function trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); + } + var readFilePromise = (0, util_1.promisify)(fs4.readFile); + var FileWatcherCertificateProvider = class { + constructor(config) { + this.config = config; + this.refreshTimer = null; + this.fileResultPromise = null; + this.latestCaUpdate = void 0; + this.caListeners = /* @__PURE__ */ new Set(); + this.latestIdentityUpdate = void 0; + this.identityListeners = /* @__PURE__ */ new Set(); + this.lastUpdateTime = null; + if (config.certificateFile === void 0 !== (config.privateKeyFile === void 0)) { + throw new Error("certificateFile and privateKeyFile must be set or unset together"); + } + if (config.certificateFile === void 0 && config.caCertificateFile === void 0) { + throw new Error("At least one of certificateFile and caCertificateFile must be set"); + } + trace("File watcher constructed with config " + JSON.stringify(config)); + } + updateCertificates() { + if (this.fileResultPromise) { + return; + } + this.fileResultPromise = Promise.allSettled([ + this.config.certificateFile ? readFilePromise(this.config.certificateFile) : Promise.reject(), + this.config.privateKeyFile ? readFilePromise(this.config.privateKeyFile) : Promise.reject(), + this.config.caCertificateFile ? readFilePromise(this.config.caCertificateFile) : Promise.reject() + ]); + this.fileResultPromise.then(([certificateResult, privateKeyResult, caCertificateResult]) => { + if (!this.refreshTimer) { + return; + } + trace("File watcher read certificates certificate " + certificateResult.status + ", privateKey " + privateKeyResult.status + ", CA certificate " + caCertificateResult.status); + this.lastUpdateTime = /* @__PURE__ */ new Date(); + this.fileResultPromise = null; + if (certificateResult.status === "fulfilled" && privateKeyResult.status === "fulfilled") { + this.latestIdentityUpdate = { + certificate: certificateResult.value, + privateKey: privateKeyResult.value + }; + } else { + this.latestIdentityUpdate = null; + } + if (caCertificateResult.status === "fulfilled") { + this.latestCaUpdate = { + caCertificate: caCertificateResult.value + }; + } else { + this.latestCaUpdate = null; + } + for (const listener of this.identityListeners) { + listener(this.latestIdentityUpdate); + } + for (const listener of this.caListeners) { + listener(this.latestCaUpdate); + } + }); + trace("File watcher initiated certificate update"); + } + maybeStartWatchingFiles() { + if (!this.refreshTimer) { + const timeSinceLastUpdate = this.lastUpdateTime ? (/* @__PURE__ */ new Date()).getTime() - this.lastUpdateTime.getTime() : Infinity; + if (timeSinceLastUpdate > this.config.refreshIntervalMs) { + this.updateCertificates(); + } + if (timeSinceLastUpdate > this.config.refreshIntervalMs * 2) { + this.latestCaUpdate = void 0; + this.latestIdentityUpdate = void 0; + } + this.refreshTimer = setInterval(() => this.updateCertificates(), this.config.refreshIntervalMs); + trace("File watcher started watching"); + } + } + maybeStopWatchingFiles() { + if (this.caListeners.size === 0 && this.identityListeners.size === 0) { + this.fileResultPromise = null; + if (this.refreshTimer) { + clearInterval(this.refreshTimer); + this.refreshTimer = null; + } + } + } + addCaCertificateListener(listener) { + this.caListeners.add(listener); + this.maybeStartWatchingFiles(); + if (this.latestCaUpdate !== void 0) { + process.nextTick(listener, this.latestCaUpdate); + } + } + removeCaCertificateListener(listener) { + this.caListeners.delete(listener); + this.maybeStopWatchingFiles(); + } + addIdentityCertificateListener(listener) { + this.identityListeners.add(listener); + this.maybeStartWatchingFiles(); + if (this.latestIdentityUpdate !== void 0) { + process.nextTick(listener, this.latestIdentityUpdate); + } + } + removeIdentityCertificateListener(listener) { + this.identityListeners.delete(listener); + this.maybeStopWatchingFiles(); + } + }; + exports2.FileWatcherCertificateProvider = FileWatcherCertificateProvider; + } +}); + +// node_modules/@grpc/grpc-js/build/src/experimental.js +var require_experimental = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/experimental.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = exports2.createCertificateProviderChannelCredentials = exports2.FileWatcherCertificateProvider = exports2.createCertificateProviderServerCredentials = exports2.createServerCredentialsWithInterceptors = exports2.BaseSubchannelWrapper = exports2.registerAdminService = exports2.FilterStackFactory = exports2.BaseFilter = exports2.statusOrFromError = exports2.statusOrFromValue = exports2.PickResultType = exports2.QueuePicker = exports2.UnavailablePicker = exports2.ChildLoadBalancerHandler = exports2.EndpointMap = exports2.endpointHasAddress = exports2.endpointToString = exports2.subchannelAddressToString = exports2.LeafLoadBalancer = exports2.isLoadBalancerNameRegistered = exports2.parseLoadBalancingConfig = exports2.selectLbConfigFromList = exports2.registerLoadBalancerType = exports2.createChildChannelControlHelper = exports2.BackoffTimeout = exports2.parseDuration = exports2.durationToMs = exports2.splitHostPort = exports2.uriToString = exports2.CHANNEL_ARGS_CONFIG_SELECTOR_KEY = exports2.createResolver = exports2.registerResolver = exports2.log = exports2.trace = void 0; + var logging_1 = require_logging(); + Object.defineProperty(exports2, "trace", { enumerable: true, get: function() { + return logging_1.trace; + } }); + Object.defineProperty(exports2, "log", { enumerable: true, get: function() { + return logging_1.log; + } }); + var resolver_1 = require_resolver(); + Object.defineProperty(exports2, "registerResolver", { enumerable: true, get: function() { + return resolver_1.registerResolver; + } }); + Object.defineProperty(exports2, "createResolver", { enumerable: true, get: function() { + return resolver_1.createResolver; + } }); + Object.defineProperty(exports2, "CHANNEL_ARGS_CONFIG_SELECTOR_KEY", { enumerable: true, get: function() { + return resolver_1.CHANNEL_ARGS_CONFIG_SELECTOR_KEY; + } }); + var uri_parser_1 = require_uri_parser(); + Object.defineProperty(exports2, "uriToString", { enumerable: true, get: function() { + return uri_parser_1.uriToString; + } }); + Object.defineProperty(exports2, "splitHostPort", { enumerable: true, get: function() { + return uri_parser_1.splitHostPort; + } }); + var duration_1 = require_duration(); + Object.defineProperty(exports2, "durationToMs", { enumerable: true, get: function() { + return duration_1.durationToMs; + } }); + Object.defineProperty(exports2, "parseDuration", { enumerable: true, get: function() { + return duration_1.parseDuration; + } }); + var backoff_timeout_1 = require_backoff_timeout(); + Object.defineProperty(exports2, "BackoffTimeout", { enumerable: true, get: function() { + return backoff_timeout_1.BackoffTimeout; + } }); + var load_balancer_1 = require_load_balancer(); + Object.defineProperty(exports2, "createChildChannelControlHelper", { enumerable: true, get: function() { + return load_balancer_1.createChildChannelControlHelper; + } }); + Object.defineProperty(exports2, "registerLoadBalancerType", { enumerable: true, get: function() { + return load_balancer_1.registerLoadBalancerType; + } }); + Object.defineProperty(exports2, "selectLbConfigFromList", { enumerable: true, get: function() { + return load_balancer_1.selectLbConfigFromList; + } }); + Object.defineProperty(exports2, "parseLoadBalancingConfig", { enumerable: true, get: function() { + return load_balancer_1.parseLoadBalancingConfig; + } }); + Object.defineProperty(exports2, "isLoadBalancerNameRegistered", { enumerable: true, get: function() { + return load_balancer_1.isLoadBalancerNameRegistered; + } }); + var load_balancer_pick_first_1 = require_load_balancer_pick_first(); + Object.defineProperty(exports2, "LeafLoadBalancer", { enumerable: true, get: function() { + return load_balancer_pick_first_1.LeafLoadBalancer; + } }); + var subchannel_address_1 = require_subchannel_address(); + Object.defineProperty(exports2, "subchannelAddressToString", { enumerable: true, get: function() { + return subchannel_address_1.subchannelAddressToString; + } }); + Object.defineProperty(exports2, "endpointToString", { enumerable: true, get: function() { + return subchannel_address_1.endpointToString; + } }); + Object.defineProperty(exports2, "endpointHasAddress", { enumerable: true, get: function() { + return subchannel_address_1.endpointHasAddress; + } }); + Object.defineProperty(exports2, "EndpointMap", { enumerable: true, get: function() { + return subchannel_address_1.EndpointMap; + } }); + var load_balancer_child_handler_1 = require_load_balancer_child_handler(); + Object.defineProperty(exports2, "ChildLoadBalancerHandler", { enumerable: true, get: function() { + return load_balancer_child_handler_1.ChildLoadBalancerHandler; + } }); + var picker_1 = require_picker(); + Object.defineProperty(exports2, "UnavailablePicker", { enumerable: true, get: function() { + return picker_1.UnavailablePicker; + } }); + Object.defineProperty(exports2, "QueuePicker", { enumerable: true, get: function() { + return picker_1.QueuePicker; + } }); + Object.defineProperty(exports2, "PickResultType", { enumerable: true, get: function() { + return picker_1.PickResultType; + } }); + var call_interface_1 = require_call_interface(); + Object.defineProperty(exports2, "statusOrFromValue", { enumerable: true, get: function() { + return call_interface_1.statusOrFromValue; + } }); + Object.defineProperty(exports2, "statusOrFromError", { enumerable: true, get: function() { + return call_interface_1.statusOrFromError; + } }); + var filter_1 = require_filter(); + Object.defineProperty(exports2, "BaseFilter", { enumerable: true, get: function() { + return filter_1.BaseFilter; + } }); + var filter_stack_1 = require_filter_stack(); + Object.defineProperty(exports2, "FilterStackFactory", { enumerable: true, get: function() { + return filter_stack_1.FilterStackFactory; + } }); + var admin_1 = require_admin(); + Object.defineProperty(exports2, "registerAdminService", { enumerable: true, get: function() { + return admin_1.registerAdminService; + } }); + var subchannel_interface_1 = require_subchannel_interface(); + Object.defineProperty(exports2, "BaseSubchannelWrapper", { enumerable: true, get: function() { + return subchannel_interface_1.BaseSubchannelWrapper; + } }); + var server_credentials_1 = require_server_credentials(); + Object.defineProperty(exports2, "createServerCredentialsWithInterceptors", { enumerable: true, get: function() { + return server_credentials_1.createServerCredentialsWithInterceptors; + } }); + Object.defineProperty(exports2, "createCertificateProviderServerCredentials", { enumerable: true, get: function() { + return server_credentials_1.createCertificateProviderServerCredentials; + } }); + var certificate_provider_1 = require_certificate_provider(); + Object.defineProperty(exports2, "FileWatcherCertificateProvider", { enumerable: true, get: function() { + return certificate_provider_1.FileWatcherCertificateProvider; + } }); + var channel_credentials_1 = require_channel_credentials(); + Object.defineProperty(exports2, "createCertificateProviderChannelCredentials", { enumerable: true, get: function() { + return channel_credentials_1.createCertificateProviderChannelCredentials; + } }); + var internal_channel_1 = require_internal_channel(); + Object.defineProperty(exports2, "SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX", { enumerable: true, get: function() { + return internal_channel_1.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX; + } }); + } +}); + +// node_modules/@grpc/grpc-js/build/src/resolver-uds.js +var require_resolver_uds = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/resolver-uds.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.setup = setup; + var resolver_1 = require_resolver(); + var call_interface_1 = require_call_interface(); + var UdsResolver = class { + constructor(target, listener, channelOptions) { + this.listener = listener; + this.hasReturnedResult = false; + this.endpoints = []; + let path; + if (target.authority === "") { + path = "/" + target.path; + } else { + path = target.path; + } + this.endpoints = [{ addresses: [{ path }] }]; + } + updateResolution() { + if (!this.hasReturnedResult) { + this.hasReturnedResult = true; + process.nextTick(this.listener, (0, call_interface_1.statusOrFromValue)(this.endpoints), {}, null, ""); + } + } + destroy() { + this.hasReturnedResult = false; + } + static getDefaultAuthority(target) { + return "localhost"; + } + }; + function setup() { + (0, resolver_1.registerResolver)("unix", UdsResolver); + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/resolver-ip.js +var require_resolver_ip = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/resolver-ip.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.setup = setup; + var net_1 = require("net"); + var call_interface_1 = require_call_interface(); + var constants_1 = require_constants7(); + var metadata_1 = require_metadata(); + var resolver_1 = require_resolver(); + var subchannel_address_1 = require_subchannel_address(); + var uri_parser_1 = require_uri_parser(); + var logging = require_logging(); + var TRACER_NAME = "ip_resolver"; + function trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); + } + var IPV4_SCHEME = "ipv4"; + var IPV6_SCHEME = "ipv6"; + var DEFAULT_PORT = 443; + var IpResolver = class { + constructor(target, listener, channelOptions) { + var _a; + this.listener = listener; + this.endpoints = []; + this.error = null; + this.hasReturnedResult = false; + trace("Resolver constructed for target " + (0, uri_parser_1.uriToString)(target)); + const addresses = []; + if (!(target.scheme === IPV4_SCHEME || target.scheme === IPV6_SCHEME)) { + this.error = { + code: constants_1.Status.UNAVAILABLE, + details: `Unrecognized scheme ${target.scheme} in IP resolver`, + metadata: new metadata_1.Metadata() + }; + return; + } + const pathList = target.path.split(","); + for (const path of pathList) { + const hostPort = (0, uri_parser_1.splitHostPort)(path); + if (hostPort === null) { + this.error = { + code: constants_1.Status.UNAVAILABLE, + details: `Failed to parse ${target.scheme} address ${path}`, + metadata: new metadata_1.Metadata() + }; + return; + } + if (target.scheme === IPV4_SCHEME && !(0, net_1.isIPv4)(hostPort.host) || target.scheme === IPV6_SCHEME && !(0, net_1.isIPv6)(hostPort.host)) { + this.error = { + code: constants_1.Status.UNAVAILABLE, + details: `Failed to parse ${target.scheme} address ${path}`, + metadata: new metadata_1.Metadata() + }; + return; + } + addresses.push({ + host: hostPort.host, + port: (_a = hostPort.port) !== null && _a !== void 0 ? _a : DEFAULT_PORT + }); + } + this.endpoints = addresses.map((address) => ({ addresses: [address] })); + trace("Parsed " + target.scheme + " address list " + addresses.map(subchannel_address_1.subchannelAddressToString)); + } + updateResolution() { + if (!this.hasReturnedResult) { + this.hasReturnedResult = true; + process.nextTick(() => { + if (this.error) { + this.listener((0, call_interface_1.statusOrFromError)(this.error), {}, null, ""); + } else { + this.listener((0, call_interface_1.statusOrFromValue)(this.endpoints), {}, null, ""); + } + }); + } + } + destroy() { + this.hasReturnedResult = false; + } + static getDefaultAuthority(target) { + return target.path.split(",")[0]; + } + }; + function setup() { + (0, resolver_1.registerResolver)(IPV4_SCHEME, IpResolver); + (0, resolver_1.registerResolver)(IPV6_SCHEME, IpResolver); + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.js +var require_load_balancer_round_robin = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.RoundRobinLoadBalancer = void 0; + exports2.setup = setup; + var load_balancer_1 = require_load_balancer(); + var connectivity_state_1 = require_connectivity_state(); + var picker_1 = require_picker(); + var logging = require_logging(); + var constants_1 = require_constants7(); + var subchannel_address_1 = require_subchannel_address(); + var load_balancer_pick_first_1 = require_load_balancer_pick_first(); + var TRACER_NAME = "round_robin"; + function trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); + } + var TYPE_NAME = "round_robin"; + var RoundRobinLoadBalancingConfig = class _RoundRobinLoadBalancingConfig { + getLoadBalancerName() { + return TYPE_NAME; + } + constructor() { + } + toJsonObject() { + return { + [TYPE_NAME]: {} + }; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static createFromJson(obj) { + return new _RoundRobinLoadBalancingConfig(); + } + }; + var RoundRobinPicker = class { + constructor(children, nextIndex = 0) { + this.children = children; + this.nextIndex = nextIndex; + } + pick(pickArgs) { + const childPicker = this.children[this.nextIndex].picker; + this.nextIndex = (this.nextIndex + 1) % this.children.length; + return childPicker.pick(pickArgs); + } + /** + * Check what the next subchannel returned would be. Used by the load + * balancer implementation to preserve this part of the picker state if + * possible when a subchannel connects or disconnects. + */ + peekNextEndpoint() { + return this.children[this.nextIndex].endpoint; + } + }; + function rotateArray(list, startIndex) { + return [...list.slice(startIndex), ...list.slice(0, startIndex)]; + } + var RoundRobinLoadBalancer = class { + constructor(channelControlHelper) { + this.channelControlHelper = channelControlHelper; + this.children = []; + this.currentState = connectivity_state_1.ConnectivityState.IDLE; + this.currentReadyPicker = null; + this.updatesPaused = false; + this.lastError = null; + this.childChannelControlHelper = (0, load_balancer_1.createChildChannelControlHelper)(channelControlHelper, { + updateState: (connectivityState, picker, errorMessage) => { + if (this.currentState === connectivity_state_1.ConnectivityState.READY && connectivityState !== connectivity_state_1.ConnectivityState.READY) { + this.channelControlHelper.requestReresolution(); + } + if (errorMessage) { + this.lastError = errorMessage; + } + this.calculateAndUpdateState(); + } + }); + } + countChildrenWithState(state) { + return this.children.filter((child) => child.getConnectivityState() === state).length; + } + calculateAndUpdateState() { + if (this.updatesPaused) { + return; + } + if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.READY) > 0) { + const readyChildren = this.children.filter((child) => child.getConnectivityState() === connectivity_state_1.ConnectivityState.READY); + let index = 0; + if (this.currentReadyPicker !== null) { + const nextPickedEndpoint = this.currentReadyPicker.peekNextEndpoint(); + index = readyChildren.findIndex((child) => (0, subchannel_address_1.endpointEqual)(child.getEndpoint(), nextPickedEndpoint)); + if (index < 0) { + index = 0; + } + } + this.updateState(connectivity_state_1.ConnectivityState.READY, new RoundRobinPicker(readyChildren.map((child) => ({ + endpoint: child.getEndpoint(), + picker: child.getPicker() + })), index), null); + } else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.CONNECTING) > 0) { + this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this), null); + } else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) > 0) { + const errorMessage = `round_robin: No connection established. Last error: ${this.lastError}`; + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ + details: errorMessage + }), errorMessage); + } else { + this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null); + } + for (const child of this.children) { + if (child.getConnectivityState() === connectivity_state_1.ConnectivityState.IDLE) { + child.exitIdle(); + } + } + } + updateState(newState, picker, errorMessage) { + trace(connectivity_state_1.ConnectivityState[this.currentState] + " -> " + connectivity_state_1.ConnectivityState[newState]); + if (newState === connectivity_state_1.ConnectivityState.READY) { + this.currentReadyPicker = picker; + } else { + this.currentReadyPicker = null; + } + this.currentState = newState; + this.channelControlHelper.updateState(newState, picker, errorMessage); + } + resetSubchannelList() { + for (const child of this.children) { + child.destroy(); + } + this.children = []; + } + updateAddressList(maybeEndpointList, lbConfig, options, resolutionNote) { + if (!(lbConfig instanceof RoundRobinLoadBalancingConfig)) { + return false; + } + if (!maybeEndpointList.ok) { + if (this.children.length === 0) { + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(maybeEndpointList.error), maybeEndpointList.error.details); + } + return true; + } + const startIndex = Math.random() * maybeEndpointList.value.length | 0; + const endpointList = rotateArray(maybeEndpointList.value, startIndex); + this.resetSubchannelList(); + if (endpointList.length === 0) { + const errorMessage = `No addresses resolved. Resolution note: ${resolutionNote}`; + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ details: errorMessage }), errorMessage); + } + trace("Connect to endpoint list " + endpointList.map(subchannel_address_1.endpointToString)); + this.updatesPaused = true; + this.children = endpointList.map((endpoint2) => new load_balancer_pick_first_1.LeafLoadBalancer(endpoint2, this.childChannelControlHelper, options, resolutionNote)); + for (const child of this.children) { + child.startConnecting(); + } + this.updatesPaused = false; + this.calculateAndUpdateState(); + return true; + } + exitIdle() { + } + resetBackoff() { + } + destroy() { + this.resetSubchannelList(); + } + getTypeName() { + return TYPE_NAME; + } + }; + exports2.RoundRobinLoadBalancer = RoundRobinLoadBalancer; + function setup() { + (0, load_balancer_1.registerLoadBalancerType)(TYPE_NAME, RoundRobinLoadBalancer, RoundRobinLoadBalancingConfig); + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.js +var require_load_balancer_outlier_detection = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.js"(exports2) { + "use strict"; + var _a; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.OutlierDetectionLoadBalancer = exports2.OutlierDetectionLoadBalancingConfig = void 0; + exports2.setup = setup; + var connectivity_state_1 = require_connectivity_state(); + var constants_1 = require_constants7(); + var duration_1 = require_duration(); + var experimental_1 = require_experimental(); + var load_balancer_1 = require_load_balancer(); + var load_balancer_child_handler_1 = require_load_balancer_child_handler(); + var picker_1 = require_picker(); + var subchannel_address_1 = require_subchannel_address(); + var subchannel_interface_1 = require_subchannel_interface(); + var logging = require_logging(); + var TRACER_NAME = "outlier_detection"; + function trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); + } + var TYPE_NAME = "outlier_detection"; + var OUTLIER_DETECTION_ENABLED = ((_a = process.env.GRPC_EXPERIMENTAL_ENABLE_OUTLIER_DETECTION) !== null && _a !== void 0 ? _a : "true") === "true"; + var defaultSuccessRateEjectionConfig = { + stdev_factor: 1900, + enforcement_percentage: 100, + minimum_hosts: 5, + request_volume: 100 + }; + var defaultFailurePercentageEjectionConfig = { + threshold: 85, + enforcement_percentage: 100, + minimum_hosts: 5, + request_volume: 50 + }; + function validateFieldType(obj, fieldName, expectedType, objectName) { + if (fieldName in obj && obj[fieldName] !== void 0 && typeof obj[fieldName] !== expectedType) { + const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName; + throw new Error(`outlier detection config ${fullFieldName} parse error: expected ${expectedType}, got ${typeof obj[fieldName]}`); + } + } + function validatePositiveDuration(obj, fieldName, objectName) { + const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName; + if (fieldName in obj && obj[fieldName] !== void 0) { + if (!(0, duration_1.isDuration)(obj[fieldName])) { + throw new Error(`outlier detection config ${fullFieldName} parse error: expected Duration, got ${typeof obj[fieldName]}`); + } + if (!(obj[fieldName].seconds >= 0 && obj[fieldName].seconds <= 315576e6 && obj[fieldName].nanos >= 0 && obj[fieldName].nanos <= 999999999)) { + throw new Error(`outlier detection config ${fullFieldName} parse error: values out of range for non-negative Duaration`); + } + } + } + function validatePercentage(obj, fieldName, objectName) { + const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName; + validateFieldType(obj, fieldName, "number", objectName); + if (fieldName in obj && obj[fieldName] !== void 0 && !(obj[fieldName] >= 0 && obj[fieldName] <= 100)) { + throw new Error(`outlier detection config ${fullFieldName} parse error: value out of range for percentage (0-100)`); + } + } + var OutlierDetectionLoadBalancingConfig = class _OutlierDetectionLoadBalancingConfig { + constructor(intervalMs, baseEjectionTimeMs, maxEjectionTimeMs, maxEjectionPercent, successRateEjection, failurePercentageEjection, childPolicy) { + this.childPolicy = childPolicy; + if (childPolicy.getLoadBalancerName() === "pick_first") { + throw new Error("outlier_detection LB policy cannot have a pick_first child policy"); + } + this.intervalMs = intervalMs !== null && intervalMs !== void 0 ? intervalMs : 1e4; + this.baseEjectionTimeMs = baseEjectionTimeMs !== null && baseEjectionTimeMs !== void 0 ? baseEjectionTimeMs : 3e4; + this.maxEjectionTimeMs = maxEjectionTimeMs !== null && maxEjectionTimeMs !== void 0 ? maxEjectionTimeMs : 3e5; + this.maxEjectionPercent = maxEjectionPercent !== null && maxEjectionPercent !== void 0 ? maxEjectionPercent : 10; + this.successRateEjection = successRateEjection ? Object.assign(Object.assign({}, defaultSuccessRateEjectionConfig), successRateEjection) : null; + this.failurePercentageEjection = failurePercentageEjection ? Object.assign(Object.assign({}, defaultFailurePercentageEjectionConfig), failurePercentageEjection) : null; + } + getLoadBalancerName() { + return TYPE_NAME; + } + toJsonObject() { + var _a2, _b; + return { + outlier_detection: { + interval: (0, duration_1.msToDuration)(this.intervalMs), + base_ejection_time: (0, duration_1.msToDuration)(this.baseEjectionTimeMs), + max_ejection_time: (0, duration_1.msToDuration)(this.maxEjectionTimeMs), + max_ejection_percent: this.maxEjectionPercent, + success_rate_ejection: (_a2 = this.successRateEjection) !== null && _a2 !== void 0 ? _a2 : void 0, + failure_percentage_ejection: (_b = this.failurePercentageEjection) !== null && _b !== void 0 ? _b : void 0, + child_policy: [this.childPolicy.toJsonObject()] + } + }; + } + getIntervalMs() { + return this.intervalMs; + } + getBaseEjectionTimeMs() { + return this.baseEjectionTimeMs; + } + getMaxEjectionTimeMs() { + return this.maxEjectionTimeMs; + } + getMaxEjectionPercent() { + return this.maxEjectionPercent; + } + getSuccessRateEjectionConfig() { + return this.successRateEjection; + } + getFailurePercentageEjectionConfig() { + return this.failurePercentageEjection; + } + getChildPolicy() { + return this.childPolicy; + } + static createFromJson(obj) { + var _a2; + validatePositiveDuration(obj, "interval"); + validatePositiveDuration(obj, "base_ejection_time"); + validatePositiveDuration(obj, "max_ejection_time"); + validatePercentage(obj, "max_ejection_percent"); + if ("success_rate_ejection" in obj && obj.success_rate_ejection !== void 0) { + if (typeof obj.success_rate_ejection !== "object") { + throw new Error("outlier detection config success_rate_ejection must be an object"); + } + validateFieldType(obj.success_rate_ejection, "stdev_factor", "number", "success_rate_ejection"); + validatePercentage(obj.success_rate_ejection, "enforcement_percentage", "success_rate_ejection"); + validateFieldType(obj.success_rate_ejection, "minimum_hosts", "number", "success_rate_ejection"); + validateFieldType(obj.success_rate_ejection, "request_volume", "number", "success_rate_ejection"); + } + if ("failure_percentage_ejection" in obj && obj.failure_percentage_ejection !== void 0) { + if (typeof obj.failure_percentage_ejection !== "object") { + throw new Error("outlier detection config failure_percentage_ejection must be an object"); + } + validatePercentage(obj.failure_percentage_ejection, "threshold", "failure_percentage_ejection"); + validatePercentage(obj.failure_percentage_ejection, "enforcement_percentage", "failure_percentage_ejection"); + validateFieldType(obj.failure_percentage_ejection, "minimum_hosts", "number", "failure_percentage_ejection"); + validateFieldType(obj.failure_percentage_ejection, "request_volume", "number", "failure_percentage_ejection"); + } + if (!("child_policy" in obj) || !Array.isArray(obj.child_policy)) { + throw new Error("outlier detection config child_policy must be an array"); + } + const childPolicy = (0, load_balancer_1.selectLbConfigFromList)(obj.child_policy); + if (!childPolicy) { + throw new Error("outlier detection config child_policy: no valid recognized policy found"); + } + return new _OutlierDetectionLoadBalancingConfig(obj.interval ? (0, duration_1.durationToMs)(obj.interval) : null, obj.base_ejection_time ? (0, duration_1.durationToMs)(obj.base_ejection_time) : null, obj.max_ejection_time ? (0, duration_1.durationToMs)(obj.max_ejection_time) : null, (_a2 = obj.max_ejection_percent) !== null && _a2 !== void 0 ? _a2 : null, obj.success_rate_ejection, obj.failure_percentage_ejection, childPolicy); + } + }; + exports2.OutlierDetectionLoadBalancingConfig = OutlierDetectionLoadBalancingConfig; + var OutlierDetectionSubchannelWrapper = class extends subchannel_interface_1.BaseSubchannelWrapper { + constructor(childSubchannel, mapEntry) { + super(childSubchannel); + this.mapEntry = mapEntry; + this.refCount = 0; + } + ref() { + this.child.ref(); + this.refCount += 1; + } + unref() { + this.child.unref(); + this.refCount -= 1; + if (this.refCount <= 0) { + if (this.mapEntry) { + const index = this.mapEntry.subchannelWrappers.indexOf(this); + if (index >= 0) { + this.mapEntry.subchannelWrappers.splice(index, 1); + } + } + } + } + eject() { + this.setHealthy(false); + } + uneject() { + this.setHealthy(true); + } + getMapEntry() { + return this.mapEntry; + } + getWrappedSubchannel() { + return this.child; + } + }; + function createEmptyBucket() { + return { + success: 0, + failure: 0 + }; + } + var CallCounter = class { + constructor() { + this.activeBucket = createEmptyBucket(); + this.inactiveBucket = createEmptyBucket(); + } + addSuccess() { + this.activeBucket.success += 1; + } + addFailure() { + this.activeBucket.failure += 1; + } + switchBuckets() { + this.inactiveBucket = this.activeBucket; + this.activeBucket = createEmptyBucket(); + } + getLastSuccesses() { + return this.inactiveBucket.success; + } + getLastFailures() { + return this.inactiveBucket.failure; + } + }; + var OutlierDetectionPicker = class { + constructor(wrappedPicker, countCalls) { + this.wrappedPicker = wrappedPicker; + this.countCalls = countCalls; + } + pick(pickArgs) { + const wrappedPick = this.wrappedPicker.pick(pickArgs); + if (wrappedPick.pickResultType === picker_1.PickResultType.COMPLETE) { + const subchannelWrapper = wrappedPick.subchannel; + const mapEntry = subchannelWrapper.getMapEntry(); + if (mapEntry) { + let onCallEnded = wrappedPick.onCallEnded; + if (this.countCalls) { + onCallEnded = (statusCode, details, metadata) => { + var _a2; + if (statusCode === constants_1.Status.OK) { + mapEntry.counter.addSuccess(); + } else { + mapEntry.counter.addFailure(); + } + (_a2 = wrappedPick.onCallEnded) === null || _a2 === void 0 ? void 0 : _a2.call(wrappedPick, statusCode, details, metadata); + }; + } + return Object.assign(Object.assign({}, wrappedPick), { subchannel: subchannelWrapper.getWrappedSubchannel(), onCallEnded }); + } else { + return Object.assign(Object.assign({}, wrappedPick), { subchannel: subchannelWrapper.getWrappedSubchannel() }); + } + } else { + return wrappedPick; + } + } + }; + var OutlierDetectionLoadBalancer = class { + constructor(channelControlHelper) { + this.entryMap = new subchannel_address_1.EndpointMap(); + this.latestConfig = null; + this.timerStartTime = null; + this.childBalancer = new load_balancer_child_handler_1.ChildLoadBalancerHandler((0, experimental_1.createChildChannelControlHelper)(channelControlHelper, { + createSubchannel: (subchannelAddress, subchannelArgs) => { + const originalSubchannel = channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs); + const mapEntry = this.entryMap.getForSubchannelAddress(subchannelAddress); + const subchannelWrapper = new OutlierDetectionSubchannelWrapper(originalSubchannel, mapEntry); + if ((mapEntry === null || mapEntry === void 0 ? void 0 : mapEntry.currentEjectionTimestamp) !== null) { + subchannelWrapper.eject(); + } + mapEntry === null || mapEntry === void 0 ? void 0 : mapEntry.subchannelWrappers.push(subchannelWrapper); + return subchannelWrapper; + }, + updateState: (connectivityState, picker, errorMessage) => { + if (connectivityState === connectivity_state_1.ConnectivityState.READY) { + channelControlHelper.updateState(connectivityState, new OutlierDetectionPicker(picker, this.isCountingEnabled()), errorMessage); + } else { + channelControlHelper.updateState(connectivityState, picker, errorMessage); + } + } + })); + this.ejectionTimer = setInterval(() => { + }, 0); + clearInterval(this.ejectionTimer); + } + isCountingEnabled() { + return this.latestConfig !== null && (this.latestConfig.getSuccessRateEjectionConfig() !== null || this.latestConfig.getFailurePercentageEjectionConfig() !== null); + } + getCurrentEjectionPercent() { + let ejectionCount = 0; + for (const mapEntry of this.entryMap.values()) { + if (mapEntry.currentEjectionTimestamp !== null) { + ejectionCount += 1; + } + } + return ejectionCount * 100 / this.entryMap.size; + } + runSuccessRateCheck(ejectionTimestamp) { + if (!this.latestConfig) { + return; + } + const successRateConfig = this.latestConfig.getSuccessRateEjectionConfig(); + if (!successRateConfig) { + return; + } + trace("Running success rate check"); + const targetRequestVolume = successRateConfig.request_volume; + let addresesWithTargetVolume = 0; + const successRates = []; + for (const [endpoint2, mapEntry] of this.entryMap.entries()) { + const successes = mapEntry.counter.getLastSuccesses(); + const failures = mapEntry.counter.getLastFailures(); + trace("Stats for " + (0, subchannel_address_1.endpointToString)(endpoint2) + ": successes=" + successes + " failures=" + failures + " targetRequestVolume=" + targetRequestVolume); + if (successes + failures >= targetRequestVolume) { + addresesWithTargetVolume += 1; + successRates.push(successes / (successes + failures)); + } + } + trace("Found " + addresesWithTargetVolume + " success rate candidates; currentEjectionPercent=" + this.getCurrentEjectionPercent() + " successRates=[" + successRates + "]"); + if (addresesWithTargetVolume < successRateConfig.minimum_hosts) { + return; + } + const successRateMean = successRates.reduce((a, b) => a + b) / successRates.length; + let successRateDeviationSum = 0; + for (const rate of successRates) { + const deviation = rate - successRateMean; + successRateDeviationSum += deviation * deviation; + } + const successRateVariance = successRateDeviationSum / successRates.length; + const successRateStdev = Math.sqrt(successRateVariance); + const ejectionThreshold = successRateMean - successRateStdev * (successRateConfig.stdev_factor / 1e3); + trace("stdev=" + successRateStdev + " ejectionThreshold=" + ejectionThreshold); + for (const [address, mapEntry] of this.entryMap.entries()) { + if (this.getCurrentEjectionPercent() >= this.latestConfig.getMaxEjectionPercent()) { + break; + } + const successes = mapEntry.counter.getLastSuccesses(); + const failures = mapEntry.counter.getLastFailures(); + if (successes + failures < targetRequestVolume) { + continue; + } + const successRate = successes / (successes + failures); + trace("Checking candidate " + address + " successRate=" + successRate); + if (successRate < ejectionThreshold) { + const randomNumber = Math.random() * 100; + trace("Candidate " + address + " randomNumber=" + randomNumber + " enforcement_percentage=" + successRateConfig.enforcement_percentage); + if (randomNumber < successRateConfig.enforcement_percentage) { + trace("Ejecting candidate " + address); + this.eject(mapEntry, ejectionTimestamp); + } + } + } + } + runFailurePercentageCheck(ejectionTimestamp) { + if (!this.latestConfig) { + return; + } + const failurePercentageConfig = this.latestConfig.getFailurePercentageEjectionConfig(); + if (!failurePercentageConfig) { + return; + } + trace("Running failure percentage check. threshold=" + failurePercentageConfig.threshold + " request volume threshold=" + failurePercentageConfig.request_volume); + let addressesWithTargetVolume = 0; + for (const mapEntry of this.entryMap.values()) { + const successes = mapEntry.counter.getLastSuccesses(); + const failures = mapEntry.counter.getLastFailures(); + if (successes + failures >= failurePercentageConfig.request_volume) { + addressesWithTargetVolume += 1; + } + } + if (addressesWithTargetVolume < failurePercentageConfig.minimum_hosts) { + return; + } + for (const [address, mapEntry] of this.entryMap.entries()) { + if (this.getCurrentEjectionPercent() >= this.latestConfig.getMaxEjectionPercent()) { + break; + } + const successes = mapEntry.counter.getLastSuccesses(); + const failures = mapEntry.counter.getLastFailures(); + trace("Candidate successes=" + successes + " failures=" + failures); + if (successes + failures < failurePercentageConfig.request_volume) { + continue; + } + const failurePercentage = failures * 100 / (failures + successes); + if (failurePercentage > failurePercentageConfig.threshold) { + const randomNumber = Math.random() * 100; + trace("Candidate " + address + " randomNumber=" + randomNumber + " enforcement_percentage=" + failurePercentageConfig.enforcement_percentage); + if (randomNumber < failurePercentageConfig.enforcement_percentage) { + trace("Ejecting candidate " + address); + this.eject(mapEntry, ejectionTimestamp); + } + } + } + } + eject(mapEntry, ejectionTimestamp) { + mapEntry.currentEjectionTimestamp = /* @__PURE__ */ new Date(); + mapEntry.ejectionTimeMultiplier += 1; + for (const subchannelWrapper of mapEntry.subchannelWrappers) { + subchannelWrapper.eject(); + } + } + uneject(mapEntry) { + mapEntry.currentEjectionTimestamp = null; + for (const subchannelWrapper of mapEntry.subchannelWrappers) { + subchannelWrapper.uneject(); + } + } + switchAllBuckets() { + for (const mapEntry of this.entryMap.values()) { + mapEntry.counter.switchBuckets(); + } + } + startTimer(delayMs) { + var _a2, _b; + this.ejectionTimer = setTimeout(() => this.runChecks(), delayMs); + (_b = (_a2 = this.ejectionTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a2); + } + runChecks() { + const ejectionTimestamp = /* @__PURE__ */ new Date(); + trace("Ejection timer running"); + this.switchAllBuckets(); + if (!this.latestConfig) { + return; + } + this.timerStartTime = ejectionTimestamp; + this.startTimer(this.latestConfig.getIntervalMs()); + this.runSuccessRateCheck(ejectionTimestamp); + this.runFailurePercentageCheck(ejectionTimestamp); + for (const [address, mapEntry] of this.entryMap.entries()) { + if (mapEntry.currentEjectionTimestamp === null) { + if (mapEntry.ejectionTimeMultiplier > 0) { + mapEntry.ejectionTimeMultiplier -= 1; + } + } else { + const baseEjectionTimeMs = this.latestConfig.getBaseEjectionTimeMs(); + const maxEjectionTimeMs = this.latestConfig.getMaxEjectionTimeMs(); + const returnTime = new Date(mapEntry.currentEjectionTimestamp.getTime()); + returnTime.setMilliseconds(returnTime.getMilliseconds() + Math.min(baseEjectionTimeMs * mapEntry.ejectionTimeMultiplier, Math.max(baseEjectionTimeMs, maxEjectionTimeMs))); + if (returnTime < /* @__PURE__ */ new Date()) { + trace("Unejecting " + address); + this.uneject(mapEntry); + } + } + } + } + updateAddressList(endpointList, lbConfig, options, resolutionNote) { + if (!(lbConfig instanceof OutlierDetectionLoadBalancingConfig)) { + return false; + } + trace("Received update with config: " + JSON.stringify(lbConfig.toJsonObject(), void 0, 2)); + if (endpointList.ok) { + for (const endpoint2 of endpointList.value) { + if (!this.entryMap.has(endpoint2)) { + trace("Adding map entry for " + (0, subchannel_address_1.endpointToString)(endpoint2)); + this.entryMap.set(endpoint2, { + counter: new CallCounter(), + currentEjectionTimestamp: null, + ejectionTimeMultiplier: 0, + subchannelWrappers: [] + }); + } + } + this.entryMap.deleteMissing(endpointList.value); + } + const childPolicy = lbConfig.getChildPolicy(); + this.childBalancer.updateAddressList(endpointList, childPolicy, options, resolutionNote); + if (lbConfig.getSuccessRateEjectionConfig() || lbConfig.getFailurePercentageEjectionConfig()) { + if (this.timerStartTime) { + trace("Previous timer existed. Replacing timer"); + clearTimeout(this.ejectionTimer); + const remainingDelay = lbConfig.getIntervalMs() - ((/* @__PURE__ */ new Date()).getTime() - this.timerStartTime.getTime()); + this.startTimer(remainingDelay); + } else { + trace("Starting new timer"); + this.timerStartTime = /* @__PURE__ */ new Date(); + this.startTimer(lbConfig.getIntervalMs()); + this.switchAllBuckets(); + } + } else { + trace("Counting disabled. Cancelling timer."); + this.timerStartTime = null; + clearTimeout(this.ejectionTimer); + for (const mapEntry of this.entryMap.values()) { + this.uneject(mapEntry); + mapEntry.ejectionTimeMultiplier = 0; + } + } + this.latestConfig = lbConfig; + return true; + } + exitIdle() { + this.childBalancer.exitIdle(); + } + resetBackoff() { + this.childBalancer.resetBackoff(); + } + destroy() { + clearTimeout(this.ejectionTimer); + this.childBalancer.destroy(); + } + getTypeName() { + return TYPE_NAME; + } + }; + exports2.OutlierDetectionLoadBalancer = OutlierDetectionLoadBalancer; + function setup() { + if (OUTLIER_DETECTION_ENABLED) { + (0, experimental_1.registerLoadBalancerType)(TYPE_NAME, OutlierDetectionLoadBalancer, OutlierDetectionLoadBalancingConfig); + } + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/priority-queue.js +var require_priority_queue = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/priority-queue.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.PriorityQueue = void 0; + var top = 0; + var parent = (i) => Math.floor(i / 2); + var left = (i) => i * 2 + 1; + var right = (i) => i * 2 + 2; + var PriorityQueue = class { + /** + * + * @param comparator Returns true if the first argument should precede the + * second in the queue. Defaults to `(a, b) => a > b` + */ + constructor(comparator = (a, b) => a > b) { + this.comparator = comparator; + this.heap = []; + } + /** + * @returns The number of items currently in the queue + */ + size() { + return this.heap.length; + } + /** + * @returns True if there are no items in the queue, false otherwise + */ + isEmpty() { + return this.size() == 0; + } + /** + * Look at the front item that would be popped, without modifying the contents + * of the queue + * @returns The front item in the queue, or undefined if the queue is empty + */ + peek() { + return this.heap[top]; + } + /** + * Add the items to the queue + * @param values The items to add + * @returns The new size of the queue after adding the items + */ + push(...values) { + values.forEach((value) => { + this.heap.push(value); + this.siftUp(); + }); + return this.size(); + } + /** + * Remove the front item in the queue and return it + * @returns The front item in the queue, or undefined if the queue is empty + */ + pop() { + const poppedValue = this.peek(); + const bottom = this.size() - 1; + if (bottom > top) { + this.swap(top, bottom); + } + this.heap.pop(); + this.siftDown(); + return poppedValue; + } + /** + * Simultaneously remove the front item in the queue and add the provided + * item. + * @param value The item to add + * @returns The front item in the queue, or undefined if the queue is empty + */ + replace(value) { + const replacedValue = this.peek(); + this.heap[top] = value; + this.siftDown(); + return replacedValue; + } + greater(i, j) { + return this.comparator(this.heap[i], this.heap[j]); + } + swap(i, j) { + [this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]]; + } + siftUp() { + let node = this.size() - 1; + while (node > top && this.greater(node, parent(node))) { + this.swap(node, parent(node)); + node = parent(node); + } + } + siftDown() { + let node = top; + while (left(node) < this.size() && this.greater(left(node), node) || right(node) < this.size() && this.greater(right(node), node)) { + let maxChild = right(node) < this.size() && this.greater(right(node), left(node)) ? right(node) : left(node); + this.swap(node, maxChild); + node = maxChild; + } + } + }; + exports2.PriorityQueue = PriorityQueue; + } +}); + +// node_modules/@grpc/grpc-js/build/src/load-balancer-weighted-round-robin.js +var require_load_balancer_weighted_round_robin = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/load-balancer-weighted-round-robin.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.WeightedRoundRobinLoadBalancingConfig = void 0; + exports2.setup = setup; + var connectivity_state_1 = require_connectivity_state(); + var constants_1 = require_constants7(); + var duration_1 = require_duration(); + var load_balancer_1 = require_load_balancer(); + var load_balancer_pick_first_1 = require_load_balancer_pick_first(); + var logging = require_logging(); + var orca_1 = require_orca(); + var picker_1 = require_picker(); + var priority_queue_1 = require_priority_queue(); + var subchannel_address_1 = require_subchannel_address(); + var TRACER_NAME = "weighted_round_robin"; + function trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); + } + var TYPE_NAME = "weighted_round_robin"; + var DEFAULT_OOB_REPORTING_PERIOD_MS = 1e4; + var DEFAULT_BLACKOUT_PERIOD_MS = 1e4; + var DEFAULT_WEIGHT_EXPIRATION_PERIOD_MS = 3 * 6e4; + var DEFAULT_WEIGHT_UPDATE_PERIOD_MS = 1e3; + var DEFAULT_ERROR_UTILIZATION_PENALTY = 1; + function validateFieldType(obj, fieldName, expectedType) { + if (fieldName in obj && obj[fieldName] !== void 0 && typeof obj[fieldName] !== expectedType) { + throw new Error(`weighted round robin config ${fieldName} parse error: expected ${expectedType}, got ${typeof obj[fieldName]}`); + } + } + function parseDurationField(obj, fieldName) { + if (fieldName in obj && obj[fieldName] !== void 0 && obj[fieldName] !== null) { + let durationObject; + if ((0, duration_1.isDuration)(obj[fieldName])) { + durationObject = obj[fieldName]; + } else if ((0, duration_1.isDurationMessage)(obj[fieldName])) { + durationObject = (0, duration_1.durationMessageToDuration)(obj[fieldName]); + } else if (typeof obj[fieldName] === "string") { + const parsedDuration = (0, duration_1.parseDuration)(obj[fieldName]); + if (!parsedDuration) { + throw new Error(`weighted round robin config ${fieldName}: failed to parse duration string ${obj[fieldName]}`); + } + durationObject = parsedDuration; + } else { + throw new Error(`weighted round robin config ${fieldName}: expected duration, got ${typeof obj[fieldName]}`); + } + return (0, duration_1.durationToMs)(durationObject); + } + return null; + } + var WeightedRoundRobinLoadBalancingConfig = class _WeightedRoundRobinLoadBalancingConfig { + constructor(enableOobLoadReport, oobLoadReportingPeriodMs, blackoutPeriodMs, weightExpirationPeriodMs, weightUpdatePeriodMs, errorUtilizationPenalty) { + this.enableOobLoadReport = enableOobLoadReport !== null && enableOobLoadReport !== void 0 ? enableOobLoadReport : false; + this.oobLoadReportingPeriodMs = oobLoadReportingPeriodMs !== null && oobLoadReportingPeriodMs !== void 0 ? oobLoadReportingPeriodMs : DEFAULT_OOB_REPORTING_PERIOD_MS; + this.blackoutPeriodMs = blackoutPeriodMs !== null && blackoutPeriodMs !== void 0 ? blackoutPeriodMs : DEFAULT_BLACKOUT_PERIOD_MS; + this.weightExpirationPeriodMs = weightExpirationPeriodMs !== null && weightExpirationPeriodMs !== void 0 ? weightExpirationPeriodMs : DEFAULT_WEIGHT_EXPIRATION_PERIOD_MS; + this.weightUpdatePeriodMs = Math.max(weightUpdatePeriodMs !== null && weightUpdatePeriodMs !== void 0 ? weightUpdatePeriodMs : DEFAULT_WEIGHT_UPDATE_PERIOD_MS, 100); + this.errorUtilizationPenalty = errorUtilizationPenalty !== null && errorUtilizationPenalty !== void 0 ? errorUtilizationPenalty : DEFAULT_ERROR_UTILIZATION_PENALTY; + } + getLoadBalancerName() { + return TYPE_NAME; + } + toJsonObject() { + return { + enable_oob_load_report: this.enableOobLoadReport, + oob_load_reporting_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.oobLoadReportingPeriodMs)), + blackout_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.blackoutPeriodMs)), + weight_expiration_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.weightExpirationPeriodMs)), + weight_update_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.weightUpdatePeriodMs)), + error_utilization_penalty: this.errorUtilizationPenalty + }; + } + static createFromJson(obj) { + validateFieldType(obj, "enable_oob_load_report", "boolean"); + validateFieldType(obj, "error_utilization_penalty", "number"); + if (obj.error_utilization_penalty < 0) { + throw new Error("weighted round robin config error_utilization_penalty < 0"); + } + return new _WeightedRoundRobinLoadBalancingConfig(obj.enable_oob_load_report, parseDurationField(obj, "oob_load_reporting_period"), parseDurationField(obj, "blackout_period"), parseDurationField(obj, "weight_expiration_period"), parseDurationField(obj, "weight_update_period"), obj.error_utilization_penalty); + } + getEnableOobLoadReport() { + return this.enableOobLoadReport; + } + getOobLoadReportingPeriodMs() { + return this.oobLoadReportingPeriodMs; + } + getBlackoutPeriodMs() { + return this.blackoutPeriodMs; + } + getWeightExpirationPeriodMs() { + return this.weightExpirationPeriodMs; + } + getWeightUpdatePeriodMs() { + return this.weightUpdatePeriodMs; + } + getErrorUtilizationPenalty() { + return this.errorUtilizationPenalty; + } + }; + exports2.WeightedRoundRobinLoadBalancingConfig = WeightedRoundRobinLoadBalancingConfig; + var WeightedRoundRobinPicker = class { + constructor(children, metricsHandler) { + this.metricsHandler = metricsHandler; + this.queue = new priority_queue_1.PriorityQueue((a, b) => a.deadline < b.deadline); + const positiveWeight = children.filter((picker) => picker.weight > 0); + let averageWeight; + if (positiveWeight.length < 2) { + averageWeight = 1; + } else { + let weightSum = 0; + for (const { weight } of positiveWeight) { + weightSum += weight; + } + averageWeight = weightSum / positiveWeight.length; + } + for (const child of children) { + const period = child.weight > 0 ? 1 / child.weight : averageWeight; + this.queue.push({ + endpointName: child.endpointName, + picker: child.picker, + period, + deadline: Math.random() * period + }); + } + } + pick(pickArgs) { + const entry = this.queue.pop(); + this.queue.push(Object.assign(Object.assign({}, entry), { deadline: entry.deadline + entry.period })); + const childPick = entry.picker.pick(pickArgs); + if (childPick.pickResultType === picker_1.PickResultType.COMPLETE) { + if (this.metricsHandler) { + return Object.assign(Object.assign({}, childPick), { onCallEnded: (0, orca_1.createMetricsReader)((loadReport) => this.metricsHandler(loadReport, entry.endpointName), childPick.onCallEnded) }); + } else { + const subchannelWrapper = childPick.subchannel; + return Object.assign(Object.assign({}, childPick), { subchannel: subchannelWrapper.getWrappedSubchannel() }); + } + } else { + return childPick; + } + } + }; + var WeightedRoundRobinLoadBalancer = class { + constructor(channelControlHelper) { + this.channelControlHelper = channelControlHelper; + this.latestConfig = null; + this.children = /* @__PURE__ */ new Map(); + this.currentState = connectivity_state_1.ConnectivityState.IDLE; + this.updatesPaused = false; + this.lastError = null; + this.weightUpdateTimer = null; + } + countChildrenWithState(state) { + let count = 0; + for (const entry of this.children.values()) { + if (entry.child.getConnectivityState() === state) { + count += 1; + } + } + return count; + } + updateWeight(entry, loadReport) { + var _a, _b; + const qps = loadReport.rps_fractional; + let utilization = loadReport.application_utilization; + if (utilization > 0 && qps > 0) { + utilization += loadReport.eps / qps * ((_b = (_a = this.latestConfig) === null || _a === void 0 ? void 0 : _a.getErrorUtilizationPenalty()) !== null && _b !== void 0 ? _b : 0); + } + const newWeight = utilization === 0 ? 0 : qps / utilization; + if (newWeight === 0) { + return; + } + const now = /* @__PURE__ */ new Date(); + if (entry.nonEmptySince === null) { + entry.nonEmptySince = now; + } + entry.lastUpdated = now; + entry.weight = newWeight; + } + getWeight(entry) { + if (!this.latestConfig) { + return 0; + } + const now = (/* @__PURE__ */ new Date()).getTime(); + if (now - entry.lastUpdated.getTime() >= this.latestConfig.getWeightExpirationPeriodMs()) { + entry.nonEmptySince = null; + return 0; + } + const blackoutPeriod = this.latestConfig.getBlackoutPeriodMs(); + if (blackoutPeriod > 0 && (entry.nonEmptySince === null || now - entry.nonEmptySince.getTime() < blackoutPeriod)) { + return 0; + } + return entry.weight; + } + calculateAndUpdateState() { + if (this.updatesPaused || !this.latestConfig) { + return; + } + if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.READY) > 0) { + const weightedPickers = []; + for (const [endpoint2, entry] of this.children) { + if (entry.child.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) { + continue; + } + weightedPickers.push({ + endpointName: endpoint2, + picker: entry.child.getPicker(), + weight: this.getWeight(entry) + }); + } + trace("Created picker with weights: " + weightedPickers.map((entry) => entry.endpointName + ":" + entry.weight).join(",")); + let metricsHandler; + if (!this.latestConfig.getEnableOobLoadReport()) { + metricsHandler = (loadReport, endpointName) => { + const childEntry = this.children.get(endpointName); + if (childEntry) { + this.updateWeight(childEntry, loadReport); + } + }; + } else { + metricsHandler = null; + } + this.updateState(connectivity_state_1.ConnectivityState.READY, new WeightedRoundRobinPicker(weightedPickers, metricsHandler), null); + } else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.CONNECTING) > 0) { + this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this), null); + } else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) > 0) { + const errorMessage = `weighted_round_robin: No connection established. Last error: ${this.lastError}`; + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ + details: errorMessage + }), errorMessage); + } else { + this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null); + } + for (const { child } of this.children.values()) { + if (child.getConnectivityState() === connectivity_state_1.ConnectivityState.IDLE) { + child.exitIdle(); + } + } + } + updateState(newState, picker, errorMessage) { + trace(connectivity_state_1.ConnectivityState[this.currentState] + " -> " + connectivity_state_1.ConnectivityState[newState]); + this.currentState = newState; + this.channelControlHelper.updateState(newState, picker, errorMessage); + } + updateAddressList(maybeEndpointList, lbConfig, options, resolutionNote) { + var _a, _b; + if (!(lbConfig instanceof WeightedRoundRobinLoadBalancingConfig)) { + return false; + } + if (!maybeEndpointList.ok) { + if (this.children.size === 0) { + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(maybeEndpointList.error), maybeEndpointList.error.details); + } + return true; + } + if (maybeEndpointList.value.length === 0) { + const errorMessage = `No addresses resolved. Resolution note: ${resolutionNote}`; + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ details: errorMessage }), errorMessage); + return false; + } + trace("Connect to endpoint list " + maybeEndpointList.value.map(subchannel_address_1.endpointToString)); + const now = /* @__PURE__ */ new Date(); + const seenEndpointNames = /* @__PURE__ */ new Set(); + this.updatesPaused = true; + this.latestConfig = lbConfig; + for (const endpoint2 of maybeEndpointList.value) { + const name = (0, subchannel_address_1.endpointToString)(endpoint2); + seenEndpointNames.add(name); + let entry = this.children.get(name); + if (!entry) { + entry = { + child: new load_balancer_pick_first_1.LeafLoadBalancer(endpoint2, (0, load_balancer_1.createChildChannelControlHelper)(this.channelControlHelper, { + updateState: (connectivityState, picker, errorMessage) => { + if (this.currentState === connectivity_state_1.ConnectivityState.READY && connectivityState !== connectivity_state_1.ConnectivityState.READY) { + this.channelControlHelper.requestReresolution(); + } + if (connectivityState === connectivity_state_1.ConnectivityState.READY) { + entry.nonEmptySince = null; + } + if (errorMessage) { + this.lastError = errorMessage; + } + this.calculateAndUpdateState(); + }, + createSubchannel: (subchannelAddress, subchannelArgs) => { + const subchannel = this.channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs); + if (entry === null || entry === void 0 ? void 0 : entry.oobMetricsListener) { + return new orca_1.OrcaOobMetricsSubchannelWrapper(subchannel, entry.oobMetricsListener, this.latestConfig.getOobLoadReportingPeriodMs()); + } else { + return subchannel; + } + } + }), options, resolutionNote), + lastUpdated: now, + nonEmptySince: null, + weight: 0, + oobMetricsListener: null + }; + this.children.set(name, entry); + } + if (lbConfig.getEnableOobLoadReport()) { + entry.oobMetricsListener = (loadReport) => { + this.updateWeight(entry, loadReport); + }; + } else { + entry.oobMetricsListener = null; + } + } + for (const [endpointName, entry] of this.children) { + if (seenEndpointNames.has(endpointName)) { + entry.child.startConnecting(); + } else { + entry.child.destroy(); + this.children.delete(endpointName); + } + } + this.updatesPaused = false; + this.calculateAndUpdateState(); + if (this.weightUpdateTimer) { + clearInterval(this.weightUpdateTimer); + } + this.weightUpdateTimer = (_b = (_a = setInterval(() => { + if (this.currentState === connectivity_state_1.ConnectivityState.READY) { + this.calculateAndUpdateState(); + } + }, lbConfig.getWeightUpdatePeriodMs())).unref) === null || _b === void 0 ? void 0 : _b.call(_a); + return true; + } + exitIdle() { + } + resetBackoff() { + } + destroy() { + for (const entry of this.children.values()) { + entry.child.destroy(); + } + this.children.clear(); + if (this.weightUpdateTimer) { + clearInterval(this.weightUpdateTimer); + } + } + getTypeName() { + return TYPE_NAME; + } + }; + function setup() { + (0, load_balancer_1.registerLoadBalancerType)(TYPE_NAME, WeightedRoundRobinLoadBalancer, WeightedRoundRobinLoadBalancingConfig); + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/index.js +var require_src4 = __commonJS({ + "node_modules/@grpc/grpc-js/build/src/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.experimental = exports2.ServerMetricRecorder = exports2.ServerInterceptingCall = exports2.ResponderBuilder = exports2.ServerListenerBuilder = exports2.addAdminServicesToServer = exports2.getChannelzHandlers = exports2.getChannelzServiceDefinition = exports2.InterceptorConfigurationError = exports2.InterceptingCall = exports2.RequesterBuilder = exports2.ListenerBuilder = exports2.StatusBuilder = exports2.getClientChannel = exports2.ServerCredentials = exports2.Server = exports2.setLogVerbosity = exports2.setLogger = exports2.load = exports2.loadObject = exports2.CallCredentials = exports2.ChannelCredentials = exports2.waitForClientReady = exports2.closeClient = exports2.Channel = exports2.makeGenericClientConstructor = exports2.makeClientConstructor = exports2.loadPackageDefinition = exports2.Client = exports2.compressionAlgorithms = exports2.propagate = exports2.connectivityState = exports2.status = exports2.logVerbosity = exports2.Metadata = exports2.credentials = void 0; + var call_credentials_1 = require_call_credentials(); + Object.defineProperty(exports2, "CallCredentials", { enumerable: true, get: function() { + return call_credentials_1.CallCredentials; + } }); + var channel_1 = require_channel(); + Object.defineProperty(exports2, "Channel", { enumerable: true, get: function() { + return channel_1.ChannelImplementation; + } }); + var compression_algorithms_1 = require_compression_algorithms(); + Object.defineProperty(exports2, "compressionAlgorithms", { enumerable: true, get: function() { + return compression_algorithms_1.CompressionAlgorithms; + } }); + var connectivity_state_1 = require_connectivity_state(); + Object.defineProperty(exports2, "connectivityState", { enumerable: true, get: function() { + return connectivity_state_1.ConnectivityState; + } }); + var channel_credentials_1 = require_channel_credentials(); + Object.defineProperty(exports2, "ChannelCredentials", { enumerable: true, get: function() { + return channel_credentials_1.ChannelCredentials; + } }); + var client_1 = require_client3(); + Object.defineProperty(exports2, "Client", { enumerable: true, get: function() { + return client_1.Client; + } }); + var constants_1 = require_constants7(); + Object.defineProperty(exports2, "logVerbosity", { enumerable: true, get: function() { + return constants_1.LogVerbosity; + } }); + Object.defineProperty(exports2, "status", { enumerable: true, get: function() { + return constants_1.Status; + } }); + Object.defineProperty(exports2, "propagate", { enumerable: true, get: function() { + return constants_1.Propagate; + } }); + var logging = require_logging(); + var make_client_1 = require_make_client(); + Object.defineProperty(exports2, "loadPackageDefinition", { enumerable: true, get: function() { + return make_client_1.loadPackageDefinition; + } }); + Object.defineProperty(exports2, "makeClientConstructor", { enumerable: true, get: function() { + return make_client_1.makeClientConstructor; + } }); + Object.defineProperty(exports2, "makeGenericClientConstructor", { enumerable: true, get: function() { + return make_client_1.makeClientConstructor; + } }); + var metadata_1 = require_metadata(); + Object.defineProperty(exports2, "Metadata", { enumerable: true, get: function() { + return metadata_1.Metadata; + } }); + var server_1 = require_server2(); + Object.defineProperty(exports2, "Server", { enumerable: true, get: function() { + return server_1.Server; + } }); + var server_credentials_1 = require_server_credentials(); + Object.defineProperty(exports2, "ServerCredentials", { enumerable: true, get: function() { + return server_credentials_1.ServerCredentials; + } }); + var status_builder_1 = require_status_builder(); + Object.defineProperty(exports2, "StatusBuilder", { enumerable: true, get: function() { + return status_builder_1.StatusBuilder; + } }); + exports2.credentials = { + /** + * Combine a ChannelCredentials with any number of CallCredentials into a + * single ChannelCredentials object. + * @param channelCredentials The ChannelCredentials object. + * @param callCredentials Any number of CallCredentials objects. + * @return The resulting ChannelCredentials object. + */ + combineChannelCredentials: (channelCredentials, ...callCredentials) => { + return callCredentials.reduce((acc, other) => acc.compose(other), channelCredentials); + }, + /** + * Combine any number of CallCredentials into a single CallCredentials + * object. + * @param first The first CallCredentials object. + * @param additional Any number of additional CallCredentials objects. + * @return The resulting CallCredentials object. + */ + combineCallCredentials: (first, ...additional) => { + return additional.reduce((acc, other) => acc.compose(other), first); + }, + // from channel-credentials.ts + createInsecure: channel_credentials_1.ChannelCredentials.createInsecure, + createSsl: channel_credentials_1.ChannelCredentials.createSsl, + createFromSecureContext: channel_credentials_1.ChannelCredentials.createFromSecureContext, + // from call-credentials.ts + createFromMetadataGenerator: call_credentials_1.CallCredentials.createFromMetadataGenerator, + createFromGoogleCredential: call_credentials_1.CallCredentials.createFromGoogleCredential, + createEmpty: call_credentials_1.CallCredentials.createEmpty + }; + var closeClient = (client) => client.close(); + exports2.closeClient = closeClient; + var waitForClientReady = (client, deadline, callback) => client.waitForReady(deadline, callback); + exports2.waitForClientReady = waitForClientReady; + var loadObject = (value, options) => { + throw new Error("Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead"); + }; + exports2.loadObject = loadObject; + var load = (filename, format, options) => { + throw new Error("Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead"); + }; + exports2.load = load; + var setLogger = (logger) => { + logging.setLogger(logger); + }; + exports2.setLogger = setLogger; + var setLogVerbosity = (verbosity) => { + logging.setLoggerVerbosity(verbosity); + }; + exports2.setLogVerbosity = setLogVerbosity; + var getClientChannel = (client) => { + return client_1.Client.prototype.getChannel.call(client); + }; + exports2.getClientChannel = getClientChannel; + var client_interceptors_1 = require_client_interceptors(); + Object.defineProperty(exports2, "ListenerBuilder", { enumerable: true, get: function() { + return client_interceptors_1.ListenerBuilder; + } }); + Object.defineProperty(exports2, "RequesterBuilder", { enumerable: true, get: function() { + return client_interceptors_1.RequesterBuilder; + } }); + Object.defineProperty(exports2, "InterceptingCall", { enumerable: true, get: function() { + return client_interceptors_1.InterceptingCall; + } }); + Object.defineProperty(exports2, "InterceptorConfigurationError", { enumerable: true, get: function() { + return client_interceptors_1.InterceptorConfigurationError; + } }); + var channelz_1 = require_channelz(); + Object.defineProperty(exports2, "getChannelzServiceDefinition", { enumerable: true, get: function() { + return channelz_1.getChannelzServiceDefinition; + } }); + Object.defineProperty(exports2, "getChannelzHandlers", { enumerable: true, get: function() { + return channelz_1.getChannelzHandlers; + } }); + var admin_1 = require_admin(); + Object.defineProperty(exports2, "addAdminServicesToServer", { enumerable: true, get: function() { + return admin_1.addAdminServicesToServer; + } }); + var server_interceptors_1 = require_server_interceptors(); + Object.defineProperty(exports2, "ServerListenerBuilder", { enumerable: true, get: function() { + return server_interceptors_1.ServerListenerBuilder; + } }); + Object.defineProperty(exports2, "ResponderBuilder", { enumerable: true, get: function() { + return server_interceptors_1.ResponderBuilder; + } }); + Object.defineProperty(exports2, "ServerInterceptingCall", { enumerable: true, get: function() { + return server_interceptors_1.ServerInterceptingCall; + } }); + var orca_1 = require_orca(); + Object.defineProperty(exports2, "ServerMetricRecorder", { enumerable: true, get: function() { + return orca_1.ServerMetricRecorder; + } }); + var experimental = require_experimental(); + exports2.experimental = experimental; + var resolver_dns = require_resolver_dns(); + var resolver_uds = require_resolver_uds(); + var resolver_ip = require_resolver_ip(); + var load_balancer_pick_first = require_load_balancer_pick_first(); + var load_balancer_round_robin = require_load_balancer_round_robin(); + var load_balancer_outlier_detection = require_load_balancer_outlier_detection(); + var load_balancer_weighted_round_robin = require_load_balancer_weighted_round_robin(); + var channelz = require_channelz(); + (() => { + resolver_dns.setup(); + resolver_uds.setup(); + resolver_ip.setup(); + load_balancer_pick_first.setup(); + load_balancer_round_robin.setup(); + load_balancer_outlier_detection.setup(); + load_balancer_weighted_round_robin.setup(); + channelz.setup(); + })(); + } +}); + +// node_modules/@grpc/proto-loader/build/src/util.js +var require_util12 = __commonJS({ + "node_modules/@grpc/proto-loader/build/src/util.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.addCommonProtos = exports2.loadProtosWithOptionsSync = exports2.loadProtosWithOptions = void 0; + var fs4 = require("fs"); + var path = require("path"); + var Protobuf = require_protobufjs(); + function addIncludePathResolver(root, includePaths) { + const originalResolvePath = root.resolvePath; + root.resolvePath = (origin, target) => { + if (path.isAbsolute(target)) { + return target; + } + for (const directory of includePaths) { + const fullPath = path.join(directory, target); + try { + fs4.accessSync(fullPath, fs4.constants.R_OK); + return fullPath; + } catch (err) { + continue; + } + } + process.emitWarning(`${target} not found in any of the include paths ${includePaths}`); + return originalResolvePath(origin, target); + }; + } + async function loadProtosWithOptions(filename, options) { + const root = new Protobuf.Root(); + options = options || {}; + if (!!options.includeDirs) { + if (!Array.isArray(options.includeDirs)) { + return Promise.reject(new Error("The includeDirs option must be an array")); + } + addIncludePathResolver(root, options.includeDirs); + } + const loadedRoot = await root.load(filename, options); + loadedRoot.resolveAll(); + return loadedRoot; + } + exports2.loadProtosWithOptions = loadProtosWithOptions; + function loadProtosWithOptionsSync(filename, options) { + const root = new Protobuf.Root(); + options = options || {}; + if (!!options.includeDirs) { + if (!Array.isArray(options.includeDirs)) { + throw new Error("The includeDirs option must be an array"); + } + addIncludePathResolver(root, options.includeDirs); + } + const loadedRoot = root.loadSync(filename, options); + loadedRoot.resolveAll(); + return loadedRoot; + } + exports2.loadProtosWithOptionsSync = loadProtosWithOptionsSync; + function addCommonProtos() { + const apiDescriptor = require_api2(); + const descriptorDescriptor = require_descriptor(); + const sourceContextDescriptor = require_source_context(); + const typeDescriptor = require_type2(); + Protobuf.common("api", apiDescriptor.nested.google.nested.protobuf.nested); + Protobuf.common("descriptor", descriptorDescriptor.nested.google.nested.protobuf.nested); + Protobuf.common("source_context", sourceContextDescriptor.nested.google.nested.protobuf.nested); + Protobuf.common("type", typeDescriptor.nested.google.nested.protobuf.nested); + } + exports2.addCommonProtos = addCommonProtos; + } +}); + +// node_modules/@grpc/proto-loader/build/src/index.js +var require_src5 = __commonJS({ + "node_modules/@grpc/proto-loader/build/src/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.loadFileDescriptorSetFromObject = exports2.loadFileDescriptorSetFromBuffer = exports2.fromJSON = exports2.loadSync = exports2.load = exports2.IdempotencyLevel = exports2.isAnyExtension = exports2.Long = void 0; + var camelCase = require_lodash(); + var Protobuf = require_protobufjs(); + var descriptor = require_descriptor2(); + var util_1 = require_util12(); + var Long = require_umd(); + exports2.Long = Long; + function isAnyExtension(obj) { + return "@type" in obj && typeof obj["@type"] === "string"; + } + exports2.isAnyExtension = isAnyExtension; + var IdempotencyLevel; + (function(IdempotencyLevel2) { + IdempotencyLevel2["IDEMPOTENCY_UNKNOWN"] = "IDEMPOTENCY_UNKNOWN"; + IdempotencyLevel2["NO_SIDE_EFFECTS"] = "NO_SIDE_EFFECTS"; + IdempotencyLevel2["IDEMPOTENT"] = "IDEMPOTENT"; + })(IdempotencyLevel = exports2.IdempotencyLevel || (exports2.IdempotencyLevel = {})); + var descriptorOptions = { + longs: String, + enums: String, + bytes: String, + defaults: true, + oneofs: true, + json: true + }; + function joinName(baseName, name) { + if (baseName === "") { + return name; + } else { + return baseName + "." + name; + } + } + function isHandledReflectionObject(obj) { + return obj instanceof Protobuf.Service || obj instanceof Protobuf.Type || obj instanceof Protobuf.Enum; + } + function isNamespaceBase(obj) { + return obj instanceof Protobuf.Namespace || obj instanceof Protobuf.Root; + } + function getAllHandledReflectionObjects(obj, parentName) { + const objName = joinName(parentName, obj.name); + if (isHandledReflectionObject(obj)) { + return [[objName, obj]]; + } else { + if (isNamespaceBase(obj) && typeof obj.nested !== "undefined") { + return Object.keys(obj.nested).map((name) => { + return getAllHandledReflectionObjects(obj.nested[name], objName); + }).reduce((accumulator, currentValue) => accumulator.concat(currentValue), []); + } + } + return []; + } + function createDeserializer(cls, options) { + return function deserialize(argBuf) { + return cls.toObject(cls.decode(argBuf), options); + }; + } + function createSerializer(cls) { + return function serialize(arg) { + if (Array.isArray(arg)) { + throw new Error(`Failed to serialize message: expected object with ${cls.name} structure, got array instead`); + } + const message = cls.fromObject(arg); + return cls.encode(message).finish(); + }; + } + function mapMethodOptions(options) { + return (options || []).reduce((obj, item) => { + for (const [key, value] of Object.entries(item)) { + switch (key) { + case "uninterpreted_option": + obj.uninterpreted_option.push(item.uninterpreted_option); + break; + default: + obj[key] = value; + } + } + return obj; + }, { + deprecated: false, + idempotency_level: IdempotencyLevel.IDEMPOTENCY_UNKNOWN, + uninterpreted_option: [] + }); + } + function createMethodDefinition(method, serviceName, options, fileDescriptors) { + const requestType = method.resolvedRequestType; + const responseType = method.resolvedResponseType; + return { + path: "/" + serviceName + "/" + method.name, + requestStream: !!method.requestStream, + responseStream: !!method.responseStream, + requestSerialize: createSerializer(requestType), + requestDeserialize: createDeserializer(requestType, options), + responseSerialize: createSerializer(responseType), + responseDeserialize: createDeserializer(responseType, options), + // TODO(murgatroid99): Find a better way to handle this + originalName: camelCase(method.name), + requestType: createMessageDefinition(requestType, fileDescriptors), + responseType: createMessageDefinition(responseType, fileDescriptors), + options: mapMethodOptions(method.parsedOptions) + }; + } + function createServiceDefinition(service, name, options, fileDescriptors) { + const def = {}; + for (const method of service.methodsArray) { + def[method.name] = createMethodDefinition(method, name, options, fileDescriptors); + } + return def; + } + function createMessageDefinition(message, fileDescriptors) { + const messageDescriptor = message.toDescriptor("proto3"); + return { + format: "Protocol Buffer 3 DescriptorProto", + type: messageDescriptor.$type.toObject(messageDescriptor, descriptorOptions), + fileDescriptorProtos: fileDescriptors + }; + } + function createEnumDefinition(enumType, fileDescriptors) { + const enumDescriptor = enumType.toDescriptor("proto3"); + return { + format: "Protocol Buffer 3 EnumDescriptorProto", + type: enumDescriptor.$type.toObject(enumDescriptor, descriptorOptions), + fileDescriptorProtos: fileDescriptors + }; + } + function createDefinition(obj, name, options, fileDescriptors) { + if (obj instanceof Protobuf.Service) { + return createServiceDefinition(obj, name, options, fileDescriptors); + } else if (obj instanceof Protobuf.Type) { + return createMessageDefinition(obj, fileDescriptors); + } else if (obj instanceof Protobuf.Enum) { + return createEnumDefinition(obj, fileDescriptors); + } else { + throw new Error("Type mismatch in reflection object handling"); + } + } + function createPackageDefinition(root, options) { + const def = {}; + root.resolveAll(); + const descriptorList = root.toDescriptor("proto3").file; + const bufferList = descriptorList.map((value) => Buffer.from(descriptor.FileDescriptorProto.encode(value).finish())); + for (const [name, obj] of getAllHandledReflectionObjects(root, "")) { + def[name] = createDefinition(obj, name, options, bufferList); + } + return def; + } + function createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options) { + options = options || {}; + const root = Protobuf.Root.fromDescriptor(decodedDescriptorSet); + root.resolveAll(); + return createPackageDefinition(root, options); + } + function load(filename, options) { + return (0, util_1.loadProtosWithOptions)(filename, options).then((loadedRoot) => { + return createPackageDefinition(loadedRoot, options); + }); + } + exports2.load = load; + function loadSync(filename, options) { + const loadedRoot = (0, util_1.loadProtosWithOptionsSync)(filename, options); + return createPackageDefinition(loadedRoot, options); + } + exports2.loadSync = loadSync; + function fromJSON(json, options) { + options = options || {}; + const loadedRoot = Protobuf.Root.fromJSON(json); + loadedRoot.resolveAll(); + return createPackageDefinition(loadedRoot, options); + } + exports2.fromJSON = fromJSON; + function loadFileDescriptorSetFromBuffer(descriptorSet, options) { + const decodedDescriptorSet = descriptor.FileDescriptorSet.decode(descriptorSet); + return createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options); + } + exports2.loadFileDescriptorSetFromBuffer = loadFileDescriptorSetFromBuffer; + function loadFileDescriptorSetFromObject(descriptorSet, options) { + const decodedDescriptorSet = descriptor.FileDescriptorSet.fromObject(descriptorSet); + return createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options); + } + exports2.loadFileDescriptorSetFromObject = loadFileDescriptorSetFromObject; + (0, util_1.addCommonProtos)(); + } +}); + +// node_modules/dockerode/lib/session.js +var require_session = __commonJS({ + "node_modules/dockerode/lib/session.js"(exports2, module2) { + var grpc = require_src4(); + var protoLoader = require_src5(); + var path = require("path"); + var crypto = require("crypto"); + function withSession(docker, auth2, handler2) { + const sessionId = crypto.randomUUID(); + const opts = { + method: "POST", + path: "/session", + hijack: true, + headers: { + Upgrade: "h2c", + "X-Docker-Expose-Session-Uuid": sessionId, + "X-Docker-Expose-Session-Name": "testcontainers" + }, + statusCodes: { + 200: true, + 500: "server error" + } + }; + docker.modem.dial(opts, function(err, socket) { + if (err) { + return handler2(err, null, () => void 0); + } + const server = new grpc.Server(); + const creds = grpc.ServerCredentials.createInsecure(); + const injector = server.createConnectionInjector(creds); + injector.injectConnection(socket); + const pkg = protoLoader.loadSync( + path.resolve(__dirname, "proto", "auth.proto") + ); + const service = grpc.loadPackageDefinition(pkg); + server.addService(service.moby.filesync.v1.Auth.service, { + Credentials({ request: request2 }, callback) { + if (auth2) { + callback(null, { + Username: auth2.username, + Secret: auth2.password + }); + } else { + callback(null, {}); + } + } + }); + function done() { + server.forceShutdown(); + socket.end(); + } + handler2(null, sessionId, done); + }); + } + module2.exports = withSession; + } +}); + +// node_modules/dockerode/lib/buildkit.js +var require_buildkit = __commonJS({ + "node_modules/dockerode/lib/buildkit.js"(exports2, module2) { + var protobuf = require_protobufjs(); + var path = require("path"); + var BUILDKIT_TRACE_ID = "moby.buildkit.trace"; + var BUILDKIT_IMAGE_ID = "moby.image.id"; + var PROTO_TYPE = "moby.buildkit.v1.StatusResponse"; + var ENCODING_UTF8 = "utf8"; + var ENCODING_BASE64 = "base64"; + var StatusResponse; + function loadProto() { + if (StatusResponse) return StatusResponse; + var root = protobuf.loadSync( + path.resolve(__dirname, "proto", "buildkit_status.proto") + ); + StatusResponse = root.lookupType(PROTO_TYPE); + return StatusResponse; + } + function decodeBuildKitStatus(base64Data) { + var StatusResponse2 = loadProto(); + if (!base64Data || base64Data.length === 0) { + return { + vertexes: [], + statuses: [], + logs: [], + warnings: [] + }; + } + var buffer = Buffer.from(base64Data, ENCODING_BASE64); + var message = StatusResponse2.decode(buffer); + return StatusResponse2.toObject(message, { + longs: String, + enums: String, + bytes: String, + defaults: true + }); + } + function formatBuildKitStatus(status) { + var lines = []; + if (status.vertexes && status.vertexes.length > 0) { + status.vertexes.forEach(function(vertex) { + if (vertex.name && vertex.started && !vertex.completed) { + lines.push("[" + vertex.digest.substring(0, 12) + "] " + vertex.name); + } + if (vertex.error) { + lines.push("ERROR: " + vertex.error); + } + if (vertex.completed && vertex.cached) { + lines.push("CACHED: " + vertex.name); + } + }); + } + if (status.logs && status.logs.length > 0) { + status.logs.forEach(function(log) { + var msg = Buffer.from(log.msg).toString(ENCODING_UTF8); + if (msg.trim()) { + lines.push(msg.trimEnd()); + } + }); + } + if (status.statuses && status.statuses.length > 0) { + status.statuses.forEach(function(s) { + if (s.name && s.total > 0) { + var percent = Math.floor(s.current / s.total * 100); + lines.push(s.name + ": " + percent + "% (" + s.current + "/" + s.total + ")"); + } + }); + } + if (status.warnings && status.warnings.length > 0) { + status.warnings.forEach(function(warning2) { + var msg = Buffer.from(warning2.short).toString(ENCODING_UTF8); + lines.push("WARNING: " + msg); + }); + } + return lines; + } + function parseBuildKitLine(line) { + try { + var json = JSON.parse(line); + if (json.id === BUILDKIT_TRACE_ID && json.aux !== void 0) { + var status = decodeBuildKitStatus(json.aux); + var logs = formatBuildKitStatus(status); + return { + isBuildKit: true, + logs, + raw: status + }; + } + if (json.id === BUILDKIT_IMAGE_ID && json.aux && json.aux.ID) { + return { + isBuildKit: true, + logs: ["Built image: " + json.aux.ID], + raw: json.aux + }; + } + return { + isBuildKit: false, + logs: [], + raw: json + }; + } catch (e) { + return { + isBuildKit: false, + logs: [], + raw: null, + error: e.message + }; + } + } + function followProgress(stream2, onFinished, onProgress) { + var buffer = ""; + var output = []; + var finished = false; + stream2.on("data", onStreamEvent); + stream2.on("error", onStreamError); + stream2.on("end", onStreamEnd); + stream2.on("close", onStreamEnd); + function onStreamEvent(data) { + buffer += data.toString(); + var lines = buffer.split("\n"); + buffer = lines.pop(); + lines.forEach(function(line) { + if (!line.trim()) return; + processLine(line); + }); + } + function processLine(line) { + try { + var result = parseBuildKitLine(line); + if (result.isBuildKit) { + result.logs.forEach(function(log) { + var event = { stream: log + "\n" }; + output.push(event); + if (onProgress) onProgress(event); + }); + } else if (result.raw) { + output.push(result.raw); + if (onProgress) onProgress(result.raw); + } + } catch (e) { + try { + var json = JSON.parse(line); + output.push(json); + if (onProgress) onProgress(json); + } catch (e2) { + } + } + } + function onStreamError(err) { + finished = true; + stream2.removeListener("data", onStreamEvent); + stream2.removeListener("error", onStreamError); + stream2.removeListener("end", onStreamEnd); + stream2.removeListener("close", onStreamEnd); + if (onFinished) onFinished(err, output); + } + function onStreamEnd() { + if (finished) return; + finished = true; + if (buffer.trim()) { + processLine(buffer); + } + stream2.removeListener("data", onStreamEvent); + stream2.removeListener("error", onStreamError); + stream2.removeListener("end", onStreamEnd); + stream2.removeListener("close", onStreamEnd); + if (onFinished) onFinished(null, output); + } + } + module2.exports = { + followProgress + }; + } +}); + +// node_modules/dockerode/lib/docker.js +var require_docker = __commonJS({ + "node_modules/dockerode/lib/docker.js"(exports2, module2) { + var EventEmitter = require("events").EventEmitter; + var Modem = require_modem(); + var Container2 = require_container(); + var Image = require_image(); + var Volume = require_volume(); + var Network = require_network(); + var Service = require_service(); + var Plugin = require_plugin(); + var Secret = require_secret(); + var Config = require_config(); + var Task = require_task(); + var Node = require_node3(); + var Exec = require_exec(); + var util = require_util9(); + var withSession = require_session(); + var extend = util.extend; + var Docker3 = function(opts) { + if (!(this instanceof Docker3)) return new Docker3(opts); + var plibrary = global.Promise; + if (opts && opts.Promise) { + plibrary = opts.Promise; + if (Object.keys(opts).length === 1) { + opts = void 0; + } + } + if (opts && opts.modem) { + this.modem = opts.modem; + } else { + this.modem = new Modem(opts); + } + this.modem.Promise = plibrary; + }; + Docker3.prototype.createContainer = function(opts, callback) { + var self2 = this; + var optsf = { + path: "/containers/create?", + method: "POST", + options: opts, + authconfig: opts.authconfig, + abortSignal: opts.abortSignal, + statusCodes: { + 200: true, + // unofficial, but proxies may return it + 201: true, + 400: "bad parameter", + 404: "no such container", + 406: "impossible to attach", + 500: "server error" + } + }; + delete opts.authconfig; + if (callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(self2.getContainer(data.Id)); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return callback(err, data); + callback(err, self2.getContainer(data.Id)); + }); + } + }; + Docker3.prototype.createImage = function(auth2, opts, callback) { + var self2 = this; + if (!callback && typeof opts === "function") { + callback = opts; + opts = auth2; + auth2 = opts.authconfig || void 0; + } else if (!callback && !opts) { + opts = auth2; + auth2 = opts.authconfig; + } + var optsf = { + path: "/images/create?", + method: "POST", + options: opts, + authconfig: auth2, + abortSignal: opts.abortSignal, + isStream: true, + statusCodes: { + 200: true, + 500: "server error" + } + }; + if (callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } + }; + Docker3.prototype.loadImage = function(file, opts, callback) { + var self2 = this; + if (!callback && typeof opts === "function") { + callback = opts; + opts = null; + } + var optsf = { + path: "/images/load?", + method: "POST", + options: opts, + file, + abortSignal: opts && opts.abortSignal, + isStream: true, + statusCodes: { + 200: true, + 500: "server error" + } + }; + if (callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } + }; + Docker3.prototype.importImage = function(file, opts, callback) { + var self2 = this; + if (!callback && typeof opts === "function") { + callback = opts; + opts = void 0; + } + if (!opts) + opts = {}; + opts.fromSrc = "-"; + var optsf = { + path: "/images/create?", + method: "POST", + options: opts, + file, + abortSignal: opts.abortSignal, + isStream: true, + statusCodes: { + 200: true, + 500: "server error" + } + }; + if (callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } + }; + Docker3.prototype.checkAuth = function(opts, callback) { + var self2 = this; + var optsf = { + path: "/auth", + method: "POST", + options: opts, + abortSignal: opts.abortSignal, + statusCodes: { + 200: true, + 204: true, + 500: "server error" + } + }; + if (callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } + }; + Docker3.prototype.buildImage = function(file, opts, callback) { + var self2 = this; + if (!callback && typeof opts === "function") { + callback = opts; + opts = null; + } + var optsf = { + path: "/build?", + method: "POST", + file: void 0, + options: opts, + abortSignal: opts && opts.abortSignal, + isStream: true, + statusCodes: { + 200: true, + 500: "server error" + } + }; + if (opts) { + if (opts.registryconfig) { + optsf.registryconfig = optsf.options.registryconfig; + delete optsf.options.registryconfig; + } + if (opts.authconfig) { + optsf.authconfig = optsf.options.authconfig; + delete optsf.options.authconfig; + } + if (opts.cachefrom && Array.isArray(opts.cachefrom)) { + optsf.options.cachefrom = JSON.stringify(opts.cachefrom); + } + } + function dial(callback2) { + util.prepareBuildContext(file, (ctx) => { + optsf.file = ctx; + self2.modem.dial(optsf, callback2); + }); + } + function dialWithSession(callback2) { + if (opts?.version === "2") { + withSession(self2, optsf.authconfig, (err, sessionId, done) => { + if (err) { + return callback2(err); + } + optsf.options.session = sessionId; + dial((err2, data) => { + callback2(err2, data); + if (data) { + data.on("end", done); + } + }); + }); + } else { + dial(callback2); + } + } + if (callback === void 0) { + return new self2.modem.Promise(function(resolve, reject) { + dialWithSession(function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + dialWithSession(callback); + } + }; + Docker3.prototype.followProgress = function(stream2, onFinished, onProgress) { + var buildkit = require_buildkit(); + return buildkit.followProgress(stream2, onFinished, onProgress); + }; + Docker3.prototype.getContainer = function(id) { + return new Container2(this.modem, id); + }; + Docker3.prototype.getImage = function(name) { + return new Image(this.modem, name); + }; + Docker3.prototype.getVolume = function(name) { + return new Volume(this.modem, name); + }; + Docker3.prototype.getPlugin = function(name, remote) { + return new Plugin(this.modem, name, remote); + }; + Docker3.prototype.getService = function(id) { + return new Service(this.modem, id); + }; + Docker3.prototype.getTask = function(id) { + return new Task(this.modem, id); + }; + Docker3.prototype.getNode = function(id) { + return new Node(this.modem, id); + }; + Docker3.prototype.getNetwork = function(id) { + return new Network(this.modem, id); + }; + Docker3.prototype.getSecret = function(id) { + return new Secret(this.modem, id); + }; + Docker3.prototype.getConfig = function(id) { + return new Config(this.modem, id); + }; + Docker3.prototype.getExec = function(id) { + return new Exec(this.modem, id); + }; + Docker3.prototype.listContainers = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/containers/json?", + method: "GET", + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: "bad parameter", + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Docker3.prototype.listImages = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/images/json?", + method: "GET", + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: "bad parameter", + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Docker3.prototype.getImages = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/images/get?", + method: "GET", + options: args.opts, + abortSignal: args.opts.abortSignal, + isStream: true, + statusCodes: { + 200: true, + 400: "bad parameter", + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Docker3.prototype.listServices = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/services?", + method: "GET", + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Docker3.prototype.listNodes = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/nodes?", + method: "GET", + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: "bad parameter", + 404: "no such node", + 500: "server error", + 503: "node is not part of a swarm" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Docker3.prototype.listTasks = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/tasks?", + method: "GET", + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Docker3.prototype.createSecret = function(opts, callback) { + var args = util.processArgs(opts, callback); + var self2 = this; + var optsf = { + path: "/secrets/create?", + method: "POST", + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + // unofficial, but proxies may return it + 201: true, + 406: "server error or node is not part of a swarm", + 409: "name conflicts with an existing object", + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(self2.getSecret(data.ID)); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, self2.getSecret(data.ID)); + }); + } + }; + Docker3.prototype.createConfig = function(opts, callback) { + var args = util.processArgs(opts, callback); + var self2 = this; + var optsf = { + path: "/configs/create?", + method: "POST", + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + // unofficial, but proxies may return it + 201: true, + 406: "server error or node is not part of a swarm", + 409: "name conflicts with an existing object", + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(self2.getConfig(data.ID)); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, self2.getConfig(data.ID)); + }); + } + }; + Docker3.prototype.listSecrets = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/secrets?", + method: "GET", + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Docker3.prototype.listConfigs = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/configs?", + method: "GET", + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Docker3.prototype.createPlugin = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/plugins/create?", + method: "POST", + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + // unofficial, but proxies may return it + 204: true, + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(self2.getPlugin(args.opts.name)); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, self2.getPlugin(args.opts.name)); + }); + } + }; + Docker3.prototype.listPlugins = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/plugins?", + method: "GET", + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Docker3.prototype.pruneImages = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/images/prune?", + method: "POST", + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Docker3.prototype.pruneBuilder = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/build/prune", + method: "POST", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Docker3.prototype.pruneContainers = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/containers/prune?", + method: "POST", + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Docker3.prototype.pruneVolumes = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/volumes/prune?", + method: "POST", + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Docker3.prototype.pruneNetworks = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/networks/prune?", + method: "POST", + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Docker3.prototype.createVolume = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/volumes/create?", + method: "POST", + allowEmpty: true, + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + // unofficial, but proxies may return it + 201: true, + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(self2.getVolume(data.Name)); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, self2.getVolume(data.Name)); + }); + } + }; + Docker3.prototype.createService = function(auth2, opts, callback) { + if (!callback && typeof opts === "function") { + callback = opts; + opts = auth2; + auth2 = opts.authconfig || void 0; + } else if (!opts && !callback) { + opts = auth2; + } + var self2 = this; + var optsf = { + path: "/services/create", + method: "POST", + options: opts, + authconfig: auth2, + abortSignal: opts && opts.abortSignal, + statusCodes: { + 200: true, + 201: true, + 500: "server error" + } + }; + if (callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(self2.getService(data.ID || data.Id)); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return callback(err, data); + callback(err, self2.getService(data.ID || data.Id)); + }); + } + }; + Docker3.prototype.listVolumes = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/volumes?", + method: "GET", + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: "bad parameter", + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Docker3.prototype.createNetwork = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/networks/create?", + method: "POST", + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + // unofficial, but proxies may return it + 201: true, + 404: "driver not found", + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(self2.getNetwork(data.Id)); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + if (err) return args.callback(err, data); + args.callback(err, self2.getNetwork(data.Id)); + }); + } + }; + Docker3.prototype.listNetworks = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/networks?", + method: "GET", + options: args.opts, + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: "bad parameter", + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Docker3.prototype.searchImages = function(opts, callback) { + var self2 = this; + var optsf = { + path: "/images/search?", + method: "GET", + options: opts, + authconfig: opts.authconfig, + abortSignal: opts.abortSignal, + statusCodes: { + 200: true, + 500: "server error" + } + }; + if (callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + callback(err, data); + }); + } + }; + Docker3.prototype.info = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var opts = { + path: "/info", + method: "GET", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(opts, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(opts, function(err, data) { + args.callback(err, data); + }); + } + }; + Docker3.prototype.version = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var opts = { + path: "/version", + method: "GET", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(opts, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(opts, function(err, data) { + args.callback(err, data); + }); + } + }; + Docker3.prototype.ping = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/_ping", + method: "GET", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Docker3.prototype.df = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/system/df", + method: "GET", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Docker3.prototype.getEvents = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/events?", + method: "GET", + options: args.opts, + abortSignal: args.opts.abortSignal, + isStream: true, + statusCodes: { + 200: true, + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Docker3.prototype.pull = function(repoTag, opts, callback, auth2) { + var args = util.processArgs(opts, callback); + var imageSrc = util.parseRepositoryTag(repoTag); + args.opts.fromImage = imageSrc.repository; + args.opts.tag = imageSrc.tag || "latest"; + var argsf = [args.opts, args.callback]; + if (auth2) { + argsf = [auth2, args.opts, args.callback]; + } + return this.createImage.apply(this, argsf); + }; + Docker3.prototype.pullAll = function(repoTag, opts, callback, auth2) { + var args = util.processArgs(opts, callback); + var imageSrc = util.parseRepositoryTag(repoTag); + args.opts.fromImage = imageSrc.repository; + var argsf = [args.opts, args.callback]; + if (auth2) { + argsf = [auth2, args.opts, args.callback]; + } + return this.createImage.apply(this, argsf); + }; + Docker3.prototype.run = function(image, cmd, streamo, createOptions, startOptions, callback) { + if (typeof arguments[arguments.length - 1] === "function") { + return this.runCallback(image, cmd, streamo, createOptions, startOptions, callback); + } else { + return this.runPromise(image, cmd, streamo, createOptions, startOptions); + } + }; + Docker3.prototype.runCallback = function(image, cmd, streamo, createOptions, startOptions, callback) { + if (!callback && typeof createOptions === "function") { + callback = createOptions; + createOptions = {}; + startOptions = {}; + } else if (!callback && typeof startOptions === "function") { + callback = startOptions; + startOptions = {}; + } + var hub = new EventEmitter(); + function handler2(err, container) { + if (err) return callback(err, null, container); + hub.emit("container", container); + container.attach({ + stream: true, + stdout: true, + stderr: true + }, function handler3(err2, stream2) { + if (err2) return callback(err2, null, container); + hub.emit("stream", stream2); + if (streamo) { + if (streamo instanceof Array) { + stream2.on("end", function() { + try { + streamo[0].end(); + } catch (e) { + } + try { + streamo[1].end(); + } catch (e) { + } + }); + container.modem.demuxStream(stream2, streamo[0], streamo[1]); + } else { + stream2.setEncoding("utf8"); + stream2.pipe(streamo, { + end: true + }); + } + } + container.start(startOptions, function(err3, data) { + if (err3) return callback(err3, data, container); + hub.emit("start", container); + container.wait(function(err4, data2) { + hub.emit("data", data2); + callback(err4, data2, container); + }); + }); + }); + } + var optsc = { + "Hostname": "", + "User": "", + "AttachStdin": false, + "AttachStdout": true, + "AttachStderr": true, + "Tty": true, + "OpenStdin": false, + "StdinOnce": false, + "Env": null, + "Cmd": cmd, + "Image": image, + "Volumes": {}, + "VolumesFrom": [] + }; + extend(optsc, createOptions); + this.createContainer(optsc, handler2); + return hub; + }; + Docker3.prototype.runPromise = function(image, cmd, streamo, createOptions, startOptions) { + var self2 = this; + createOptions = createOptions || {}; + startOptions = startOptions || {}; + var optsc = { + "Hostname": "", + "User": "", + "AttachStdin": false, + "AttachStdout": true, + "AttachStderr": true, + "Tty": true, + "OpenStdin": false, + "StdinOnce": false, + "Env": null, + "Cmd": cmd, + "Image": image, + "Volumes": {}, + "VolumesFrom": [] + }; + extend(optsc, createOptions); + var containero; + return new this.modem.Promise(function(resolve, reject) { + self2.createContainer(optsc).then(function(container) { + containero = container; + return container.attach({ + stream: true, + stdout: true, + stderr: true + }); + }).then(function(stream2) { + if (streamo) { + if (streamo instanceof Array) { + stream2.on("end", function() { + try { + streamo[0].end(); + } catch (e) { + } + try { + streamo[1].end(); + } catch (e) { + } + }); + containero.modem.demuxStream(stream2, streamo[0], streamo[1]); + } else { + stream2.setEncoding("utf8"); + stream2.pipe(streamo, { + end: true + }); + } + } + return containero.start(startOptions); + }).then(function(data) { + return containero.wait(); + }).then(function(data) { + resolve([data, containero]); + }).catch(function(err) { + reject(err); + }); + }); + }; + Docker3.prototype.swarmInit = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/swarm/init", + method: "POST", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: "bad parameter", + 406: "node is already part of a Swarm" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Docker3.prototype.swarmJoin = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/swarm/join", + method: "POST", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: "bad parameter", + 406: "node is already part of a Swarm" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Docker3.prototype.swarmLeave = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/swarm/leave?", + method: "POST", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 406: "node is not part of a Swarm" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Docker3.prototype.swarmUpdate = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/swarm/update?", + method: "POST", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 400: "bad parameter", + 406: "node is already part of a Swarm" + }, + options: args.opts + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Docker3.prototype.swarmInspect = function(opts, callback) { + var self2 = this; + var args = util.processArgs(opts, callback); + var optsf = { + path: "/swarm", + method: "GET", + abortSignal: args.opts.abortSignal, + statusCodes: { + 200: true, + 406: "This node is not a swarm manager", + 500: "server error" + } + }; + if (args.callback === void 0) { + return new this.modem.Promise(function(resolve, reject) { + self2.modem.dial(optsf, function(err, data) { + if (err) { + return reject(err); + } + resolve(data); + }); + }); + } else { + this.modem.dial(optsf, function(err, data) { + args.callback(err, data); + }); + } + }; + Docker3.Container = Container2; + Docker3.Image = Image; + Docker3.Volume = Volume; + Docker3.Network = Network; + Docker3.Service = Service; + Docker3.Plugin = Plugin; + Docker3.Secret = Secret; + Docker3.Task = Task; + Docker3.Node = Node; + Docker3.Exec = Exec; + module2.exports = Docker3; + } +}); + +// node_modules/events-universal/default.js +var require_default = __commonJS({ + "node_modules/events-universal/default.js"(exports2, module2) { + module2.exports = require("events"); + } +}); + +// node_modules/fast-fifo/fixed-size.js +var require_fixed_size = __commonJS({ + "node_modules/fast-fifo/fixed-size.js"(exports2, module2) { + module2.exports = class FixedFIFO { + constructor(hwm) { + if (!(hwm > 0) || (hwm - 1 & hwm) !== 0) throw new Error("Max size for a FixedFIFO should be a power of two"); + this.buffer = new Array(hwm); + this.mask = hwm - 1; + this.top = 0; + this.btm = 0; + this.next = null; + } + clear() { + this.top = this.btm = 0; + this.next = null; + this.buffer.fill(void 0); + } + push(data) { + if (this.buffer[this.top] !== void 0) return false; + this.buffer[this.top] = data; + this.top = this.top + 1 & this.mask; + return true; + } + shift() { + const last = this.buffer[this.btm]; + if (last === void 0) return void 0; + this.buffer[this.btm] = void 0; + this.btm = this.btm + 1 & this.mask; + return last; + } + peek() { + return this.buffer[this.btm]; + } + isEmpty() { + return this.buffer[this.btm] === void 0; + } + }; + } +}); + +// node_modules/fast-fifo/index.js +var require_fast_fifo = __commonJS({ + "node_modules/fast-fifo/index.js"(exports2, module2) { + var FixedFIFO = require_fixed_size(); + module2.exports = class FastFIFO { + constructor(hwm) { + this.hwm = hwm || 16; + this.head = new FixedFIFO(this.hwm); + this.tail = this.head; + this.length = 0; + } + clear() { + this.head = this.tail; + this.head.clear(); + this.length = 0; + } + push(val) { + this.length++; + if (!this.head.push(val)) { + const prev = this.head; + this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length); + this.head.push(val); + } + } + shift() { + if (this.length !== 0) this.length--; + const val = this.tail.shift(); + if (val === void 0 && this.tail.next) { + const next = this.tail.next; + this.tail.next = null; + this.tail = next; + return this.tail.shift(); + } + return val; + } + peek() { + const val = this.tail.peek(); + if (val === void 0 && this.tail.next) return this.tail.next.peek(); + return val; + } + isEmpty() { + return this.length === 0; + } + }; + } +}); + +// node_modules/b4a/index.js +var require_b4a = __commonJS({ + "node_modules/b4a/index.js"(exports2, module2) { + function isBuffer(value) { + return Buffer.isBuffer(value) || value instanceof Uint8Array; + } + function isEncoding(encoding) { + return Buffer.isEncoding(encoding); + } + function alloc(size, fill2, encoding) { + return Buffer.alloc(size, fill2, encoding); + } + function allocUnsafe(size) { + return Buffer.allocUnsafe(size); + } + function allocUnsafeSlow(size) { + return Buffer.allocUnsafeSlow(size); + } + function byteLength(string, encoding) { + return Buffer.byteLength(string, encoding); + } + function compare(a, b) { + return Buffer.compare(a, b); + } + function concat(buffers, totalLength) { + return Buffer.concat(buffers, totalLength); + } + function copy(source, target, targetStart, start, end) { + return toBuffer(source).copy(target, targetStart, start, end); + } + function equals(a, b) { + return toBuffer(a).equals(b); + } + function fill(buffer, value, offset, end, encoding) { + return toBuffer(buffer).fill(value, offset, end, encoding); + } + function from(value, encodingOrOffset, length) { + return Buffer.from(value, encodingOrOffset, length); + } + function includes(buffer, value, byteOffset, encoding) { + return toBuffer(buffer).includes(value, byteOffset, encoding); + } + function indexOf(buffer, value, byfeOffset, encoding) { + return toBuffer(buffer).indexOf(value, byfeOffset, encoding); + } + function lastIndexOf(buffer, value, byteOffset, encoding) { + return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding); + } + function swap16(buffer) { + return toBuffer(buffer).swap16(); + } + function swap32(buffer) { + return toBuffer(buffer).swap32(); + } + function swap64(buffer) { + return toBuffer(buffer).swap64(); + } + function toBuffer(buffer) { + if (Buffer.isBuffer(buffer)) return buffer; + return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength); + } + function toString(buffer, encoding, start, end) { + return toBuffer(buffer).toString(encoding, start, end); + } + function write(buffer, string, offset, length, encoding) { + return toBuffer(buffer).write(string, offset, length, encoding); + } + function writeDoubleLE(buffer, value, offset) { + return toBuffer(buffer).writeDoubleLE(value, offset); + } + function writeFloatLE(buffer, value, offset) { + return toBuffer(buffer).writeFloatLE(value, offset); + } + function writeUInt32LE(buffer, value, offset) { + return toBuffer(buffer).writeUInt32LE(value, offset); + } + function writeInt32LE(buffer, value, offset) { + return toBuffer(buffer).writeInt32LE(value, offset); + } + function readDoubleLE(buffer, offset) { + return toBuffer(buffer).readDoubleLE(offset); + } + function readFloatLE(buffer, offset) { + return toBuffer(buffer).readFloatLE(offset); + } + function readUInt32LE(buffer, offset) { + return toBuffer(buffer).readUInt32LE(offset); + } + function readInt32LE(buffer, offset) { + return toBuffer(buffer).readInt32LE(offset); + } + module2.exports = { + isBuffer, + isEncoding, + alloc, + allocUnsafe, + allocUnsafeSlow, + byteLength, + compare, + concat, + copy, + equals, + fill, + from, + includes, + indexOf, + lastIndexOf, + swap16, + swap32, + swap64, + toBuffer, + toString, + write, + writeDoubleLE, + writeFloatLE, + writeUInt32LE, + writeInt32LE, + readDoubleLE, + readFloatLE, + readUInt32LE, + readInt32LE + }; + } +}); + +// node_modules/text-decoder/lib/pass-through-decoder.js +var require_pass_through_decoder = __commonJS({ + "node_modules/text-decoder/lib/pass-through-decoder.js"(exports2, module2) { + var b4a = require_b4a(); + module2.exports = class PassThroughDecoder { + constructor(encoding) { + this.encoding = encoding; + } + get remaining() { + return 0; + } + decode(data) { + return b4a.toString(data, this.encoding); + } + flush() { + return ""; + } + }; + } +}); + +// node_modules/text-decoder/lib/utf8-decoder.js +var require_utf8_decoder = __commonJS({ + "node_modules/text-decoder/lib/utf8-decoder.js"(exports2, module2) { + var b4a = require_b4a(); + module2.exports = class UTF8Decoder { + constructor() { + this._reset(); + } + get remaining() { + return this.bytesSeen; + } + decode(data) { + if (data.byteLength === 0) return ""; + if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) { + this.bytesSeen = trailingBytesSeen(data); + return b4a.toString(data, "utf8"); + } + let result = ""; + let start = 0; + if (this.bytesNeeded > 0) { + while (start < data.byteLength) { + const byte = data[start]; + if (byte < this.lowerBoundary || byte > this.upperBoundary) { + result += "\uFFFD"; + this._reset(); + break; + } + this.lowerBoundary = 128; + this.upperBoundary = 191; + this.codePoint = this.codePoint << 6 | byte & 63; + this.bytesSeen++; + start++; + if (this.bytesSeen === this.bytesNeeded) { + result += String.fromCodePoint(this.codePoint); + this._reset(); + break; + } + } + if (this.bytesNeeded > 0) return result; + } + const trailing = trailingIncomplete(data, start); + const end = data.byteLength - trailing; + if (end > start) result += b4a.toString(data, "utf8", start, end); + for (let i = end; i < data.byteLength; i++) { + const byte = data[i]; + if (this.bytesNeeded === 0) { + if (byte <= 127) { + this.bytesSeen = 0; + result += String.fromCharCode(byte); + } else if (byte >= 194 && byte <= 223) { + this.bytesNeeded = 2; + this.bytesSeen = 1; + this.codePoint = byte & 31; + } else if (byte >= 224 && byte <= 239) { + if (byte === 224) this.lowerBoundary = 160; + else if (byte === 237) this.upperBoundary = 159; + this.bytesNeeded = 3; + this.bytesSeen = 1; + this.codePoint = byte & 15; + } else if (byte >= 240 && byte <= 244) { + if (byte === 240) this.lowerBoundary = 144; + else if (byte === 244) this.upperBoundary = 143; + this.bytesNeeded = 4; + this.bytesSeen = 1; + this.codePoint = byte & 7; + } else { + this.bytesSeen = 1; + result += "\uFFFD"; + } + continue; + } + if (byte < this.lowerBoundary || byte > this.upperBoundary) { + result += "\uFFFD"; + i--; + this._reset(); + continue; + } + this.lowerBoundary = 128; + this.upperBoundary = 191; + this.codePoint = this.codePoint << 6 | byte & 63; + this.bytesSeen++; + if (this.bytesSeen === this.bytesNeeded) { + result += String.fromCodePoint(this.codePoint); + this._reset(); + } + } + return result; + } + flush() { + const result = this.bytesNeeded > 0 ? "\uFFFD" : ""; + this._reset(); + return result; + } + _reset() { + this.codePoint = 0; + this.bytesNeeded = 0; + this.bytesSeen = 0; + this.lowerBoundary = 128; + this.upperBoundary = 191; + } + }; + function trailingIncomplete(data, start) { + const len = data.byteLength; + if (len <= start) return 0; + const limit = Math.max(start, len - 4); + let i = len - 1; + while (i > limit && (data[i] & 192) === 128) i--; + if (i < start) return 0; + const byte = data[i]; + let needed; + if (byte <= 127) return 0; + if (byte >= 194 && byte <= 223) needed = 2; + else if (byte >= 224 && byte <= 239) needed = 3; + else if (byte >= 240 && byte <= 244) needed = 4; + else return 0; + const available = len - i; + return available < needed ? available : 0; + } + function trailingBytesSeen(data) { + const len = data.byteLength; + if (len === 0) return 0; + const last = data[len - 1]; + if (last <= 127) return 0; + if ((last & 192) !== 128) return 1; + const limit = Math.max(0, len - 4); + let i = len - 2; + while (i >= limit && (data[i] & 192) === 128) i--; + if (i < 0) return 1; + const first = data[i]; + let needed; + if (first >= 194 && first <= 223) needed = 2; + else if (first >= 224 && first <= 239) needed = 3; + else if (first >= 240 && first <= 244) needed = 4; + else return 1; + if (len - i !== needed) return 1; + if (needed >= 3) { + const second = data[i + 1]; + if (first === 224 && second < 160) return 1; + if (first === 237 && second > 159) return 1; + if (first === 240 && second < 144) return 1; + if (first === 244 && second > 143) return 1; + } + return 0; + } + } +}); + +// node_modules/text-decoder/index.js +var require_text_decoder = __commonJS({ + "node_modules/text-decoder/index.js"(exports2, module2) { + var PassThroughDecoder = require_pass_through_decoder(); + var UTF8Decoder = require_utf8_decoder(); + module2.exports = class TextDecoder { + constructor(encoding = "utf8") { + this.encoding = normalizeEncoding(encoding); + switch (this.encoding) { + case "utf8": + this.decoder = new UTF8Decoder(); + break; + case "utf16le": + case "base64": + throw new Error("Unsupported encoding: " + this.encoding); + default: + this.decoder = new PassThroughDecoder(this.encoding); + } + } + get remaining() { + return this.decoder.remaining; + } + push(data) { + if (typeof data === "string") return data; + return this.decoder.decode(data); + } + // For Node.js compatibility + write(data) { + return this.push(data); + } + end(data) { + let result = ""; + if (data) result = this.push(data); + result += this.decoder.flush(); + return result; + } + }; + function normalizeEncoding(encoding) { + encoding = encoding.toLowerCase(); + switch (encoding) { + 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 encoding; + default: + throw new Error("Unknown encoding: " + encoding); + } + } + } +}); + +// node_modules/streamx/index.js +var require_streamx = __commonJS({ + "node_modules/streamx/index.js"(exports2, module2) { + var { EventEmitter } = require_default(); + var STREAM_DESTROYED = new Error("Stream was destroyed"); + var PREMATURE_CLOSE = new Error("Premature close"); + var FIFO = require_fast_fifo(); + var TextDecoder2 = require_text_decoder(); + var qmt = typeof queueMicrotask === "undefined" ? (fn) => global.process.nextTick(fn) : queueMicrotask; + var MAX = (1 << 29) - 1; + var OPENING = 1; + var PREDESTROYING = 2; + var DESTROYING = 4; + var DESTROYED = 8; + var NOT_OPENING = MAX ^ OPENING; + var NOT_PREDESTROYING = MAX ^ PREDESTROYING; + var READ_ACTIVE = 1 << 4; + var READ_UPDATING = 2 << 4; + var READ_PRIMARY = 4 << 4; + var READ_QUEUED = 8 << 4; + var READ_RESUMED = 16 << 4; + var READ_PIPE_DRAINED = 32 << 4; + var READ_ENDING = 64 << 4; + var READ_EMIT_DATA = 128 << 4; + var READ_EMIT_READABLE = 256 << 4; + var READ_EMITTED_READABLE = 512 << 4; + var READ_DONE = 1024 << 4; + var READ_NEXT_TICK = 2048 << 4; + var READ_NEEDS_PUSH = 4096 << 4; + var READ_READ_AHEAD = 8192 << 4; + var READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED; + var READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH; + var READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE; + var READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED; + var READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD; + var READ_NOT_ACTIVE = MAX ^ READ_ACTIVE; + var READ_NON_PRIMARY = MAX ^ READ_PRIMARY; + var READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH); + var READ_PUSHED = MAX ^ READ_NEEDS_PUSH; + var READ_PAUSED = MAX ^ READ_RESUMED; + var READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE); + var READ_NOT_ENDING = MAX ^ READ_ENDING; + var READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING; + var READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK; + var READ_NOT_UPDATING = MAX ^ READ_UPDATING; + var READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD; + var READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD; + var WRITE_ACTIVE = 1 << 18; + var WRITE_UPDATING = 2 << 18; + var WRITE_PRIMARY = 4 << 18; + var WRITE_QUEUED = 8 << 18; + var WRITE_UNDRAINED = 16 << 18; + var WRITE_DONE = 32 << 18; + var WRITE_EMIT_DRAIN = 64 << 18; + var WRITE_NEXT_TICK = 128 << 18; + var WRITE_WRITING = 256 << 18; + var WRITE_FINISHING = 512 << 18; + var WRITE_CORKED = 1024 << 18; + var WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING); + var WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY; + var WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING); + var WRITE_DRAINED = MAX ^ WRITE_UNDRAINED; + var WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED; + var WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK; + var WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING; + var WRITE_NOT_CORKED = MAX ^ WRITE_CORKED; + var ACTIVE = READ_ACTIVE | WRITE_ACTIVE; + var NOT_ACTIVE = MAX ^ ACTIVE; + var DONE = READ_DONE | WRITE_DONE; + var DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING; + var OPEN_STATUS = DESTROY_STATUS | OPENING; + var AUTO_DESTROY = DESTROY_STATUS | DONE; + var NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY; + var ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK; + var TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE; + var IS_OPENING = OPEN_STATUS | TICKING; + var READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE; + var READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED; + var READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED; + var READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE; + var SHOULD_NOT_READ = OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD; + var READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE; + var READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY; + var READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING; + var WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE; + var WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED; + var WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE; + var WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE; + var WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED; + var WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE; + var WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING; + var WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE; + var WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE; + var WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY; + var WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS; + var asyncIterator = Symbol.asyncIterator || /* @__PURE__ */ Symbol("asyncIterator"); + var WritableState = class { + constructor(stream2, { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}) { + this.stream = stream2; + this.queue = new FIFO(); + this.highWaterMark = highWaterMark; + this.buffered = 0; + this.error = null; + this.pipeline = null; + this.drains = null; + this.byteLength = byteLengthWritable || byteLength || defaultByteLength; + this.map = mapWritable || map; + this.afterWrite = afterWrite.bind(this); + this.afterUpdateNextTick = updateWriteNT.bind(this); + } + get ended() { + return (this.stream._duplexState & WRITE_DONE) !== 0; + } + push(data) { + if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false; + if (this.map !== null) data = this.map(data); + this.buffered += this.byteLength(data); + this.queue.push(data); + if (this.buffered < this.highWaterMark) { + this.stream._duplexState |= WRITE_QUEUED; + return true; + } + this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED; + return false; + } + shift() { + const data = this.queue.shift(); + this.buffered -= this.byteLength(data); + if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED; + return data; + } + end(data) { + if (typeof data === "function") this.stream.once("finish", data); + else if (data !== void 0 && data !== null) this.push(data); + this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY; + } + autoBatch(data, cb) { + const buffer = []; + const stream2 = this.stream; + buffer.push(data); + while ((stream2._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) { + buffer.push(stream2._writableState.shift()); + } + if ((stream2._duplexState & OPEN_STATUS) !== 0) return cb(null); + stream2._writev(buffer, cb); + } + update() { + const stream2 = this.stream; + stream2._duplexState |= WRITE_UPDATING; + do { + while ((stream2._duplexState & WRITE_STATUS) === WRITE_QUEUED) { + const data = this.shift(); + stream2._duplexState |= WRITE_ACTIVE_AND_WRITING; + stream2._write(data, this.afterWrite); + } + if ((stream2._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary(); + } while (this.continueUpdate() === true); + stream2._duplexState &= WRITE_NOT_UPDATING; + } + updateNonPrimary() { + const stream2 = this.stream; + if ((stream2._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) { + stream2._duplexState = stream2._duplexState | WRITE_ACTIVE; + stream2._final(afterFinal.bind(this)); + return; + } + if ((stream2._duplexState & DESTROY_STATUS) === DESTROYING) { + if ((stream2._duplexState & ACTIVE_OR_TICKING) === 0) { + stream2._duplexState |= ACTIVE; + stream2._destroy(afterDestroy.bind(this)); + } + return; + } + if ((stream2._duplexState & IS_OPENING) === OPENING) { + stream2._duplexState = (stream2._duplexState | ACTIVE) & NOT_OPENING; + stream2._open(afterOpen.bind(this)); + } + } + continueUpdate() { + if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false; + this.stream._duplexState &= WRITE_NOT_NEXT_TICK; + return true; + } + updateCallback() { + if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) this.update(); + else this.updateNextTick(); + } + updateNextTick() { + if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return; + this.stream._duplexState |= WRITE_NEXT_TICK; + if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick); + } + }; + var ReadableState = class { + constructor(stream2, { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}) { + this.stream = stream2; + this.queue = new FIFO(); + this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark; + this.buffered = 0; + this.readAhead = highWaterMark > 0; + this.error = null; + this.pipeline = null; + this.byteLength = byteLengthReadable || byteLength || defaultByteLength; + this.map = mapReadable || map; + this.pipeTo = null; + this.afterRead = afterRead.bind(this); + this.afterUpdateNextTick = updateReadNT.bind(this); + } + get ended() { + return (this.stream._duplexState & READ_DONE) !== 0; + } + pipe(pipeTo, cb) { + if (this.pipeTo !== null) throw new Error("Can only pipe to one destination"); + if (typeof cb !== "function") cb = null; + this.stream._duplexState |= READ_PIPE_DRAINED; + this.pipeTo = pipeTo; + this.pipeline = new Pipeline(this.stream, pipeTo, cb); + if (cb) this.stream.on("error", noop3); + if (isStreamx(pipeTo)) { + pipeTo._writableState.pipeline = this.pipeline; + if (cb) pipeTo.on("error", noop3); + pipeTo.on("finish", this.pipeline.finished.bind(this.pipeline)); + } else { + const onerror = this.pipeline.done.bind(this.pipeline, pipeTo); + const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null); + pipeTo.on("error", onerror); + pipeTo.on("close", onclose); + pipeTo.on("finish", this.pipeline.finished.bind(this.pipeline)); + } + pipeTo.on("drain", afterDrain.bind(this)); + this.stream.emit("piping", pipeTo); + pipeTo.emit("pipe", this.stream); + } + push(data) { + const stream2 = this.stream; + if (data === null) { + this.highWaterMark = 0; + stream2._duplexState = (stream2._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED; + return false; + } + if (this.map !== null) { + data = this.map(data); + if (data === null) { + stream2._duplexState &= READ_PUSHED; + return this.buffered < this.highWaterMark; + } + } + this.buffered += this.byteLength(data); + this.queue.push(data); + stream2._duplexState = (stream2._duplexState | READ_QUEUED) & READ_PUSHED; + return this.buffered < this.highWaterMark; + } + shift() { + const data = this.queue.shift(); + this.buffered -= this.byteLength(data); + if (this.buffered === 0) this.stream._duplexState &= READ_NOT_QUEUED; + return data; + } + unshift(data) { + const pending = [this.map !== null ? this.map(data) : data]; + while (this.buffered > 0) pending.push(this.shift()); + for (let i = 0; i < pending.length - 1; i++) { + const data2 = pending[i]; + this.buffered += this.byteLength(data2); + this.queue.push(data2); + } + this.push(pending[pending.length - 1]); + } + read() { + const stream2 = this.stream; + if ((stream2._duplexState & READ_STATUS) === READ_QUEUED) { + const data = this.shift(); + if (this.pipeTo !== null && this.pipeTo.write(data) === false) stream2._duplexState &= READ_PIPE_NOT_DRAINED; + if ((stream2._duplexState & READ_EMIT_DATA) !== 0) stream2.emit("data", data); + return data; + } + if (this.readAhead === false) { + stream2._duplexState |= READ_READ_AHEAD; + this.updateNextTick(); + } + return null; + } + drain() { + const stream2 = this.stream; + while ((stream2._duplexState & READ_STATUS) === READ_QUEUED && (stream2._duplexState & READ_FLOWING) !== 0) { + const data = this.shift(); + if (this.pipeTo !== null && this.pipeTo.write(data) === false) stream2._duplexState &= READ_PIPE_NOT_DRAINED; + if ((stream2._duplexState & READ_EMIT_DATA) !== 0) stream2.emit("data", data); + } + } + update() { + const stream2 = this.stream; + stream2._duplexState |= READ_UPDATING; + do { + this.drain(); + while (this.buffered < this.highWaterMark && (stream2._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD) { + stream2._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH; + stream2._read(this.afterRead); + this.drain(); + } + if ((stream2._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) { + stream2._duplexState |= READ_EMITTED_READABLE; + stream2.emit("readable"); + } + if ((stream2._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary(); + } while (this.continueUpdate() === true); + stream2._duplexState &= READ_NOT_UPDATING; + } + updateNonPrimary() { + const stream2 = this.stream; + if ((stream2._duplexState & READ_ENDING_STATUS) === READ_ENDING) { + stream2._duplexState = (stream2._duplexState | READ_DONE) & READ_NOT_ENDING; + stream2.emit("end"); + if ((stream2._duplexState & AUTO_DESTROY) === DONE) stream2._duplexState |= DESTROYING; + if (this.pipeTo !== null) this.pipeTo.end(); + } + if ((stream2._duplexState & DESTROY_STATUS) === DESTROYING) { + if ((stream2._duplexState & ACTIVE_OR_TICKING) === 0) { + stream2._duplexState |= ACTIVE; + stream2._destroy(afterDestroy.bind(this)); + } + return; + } + if ((stream2._duplexState & IS_OPENING) === OPENING) { + stream2._duplexState = (stream2._duplexState | ACTIVE) & NOT_OPENING; + stream2._open(afterOpen.bind(this)); + } + } + continueUpdate() { + if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false; + this.stream._duplexState &= READ_NOT_NEXT_TICK; + return true; + } + updateCallback() { + if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) this.update(); + else this.updateNextTick(); + } + updateNextTickIfOpen() { + if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return; + this.stream._duplexState |= READ_NEXT_TICK; + if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick); + } + updateNextTick() { + if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return; + this.stream._duplexState |= READ_NEXT_TICK; + if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick); + } + }; + var TransformState = class { + constructor(stream2) { + this.data = null; + this.afterTransform = afterTransform.bind(stream2); + this.afterFinal = null; + } + }; + var Pipeline = class { + constructor(src, dst, cb) { + this.from = src; + this.to = dst; + this.afterPipe = cb; + this.error = null; + this.pipeToFinished = false; + } + finished() { + this.pipeToFinished = true; + } + done(stream2, err) { + if (err) this.error = err; + if (stream2 === this.to) { + this.to = null; + if (this.from !== null) { + if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) { + this.from.destroy(this.error || new Error("Writable stream closed prematurely")); + } + return; + } + } + if (stream2 === this.from) { + this.from = null; + if (this.to !== null) { + if ((stream2._duplexState & READ_DONE) === 0) { + this.to.destroy(this.error || new Error("Readable stream closed before ending")); + } + return; + } + } + if (this.afterPipe !== null) this.afterPipe(this.error); + this.to = this.from = this.afterPipe = null; + } + }; + function afterDrain() { + this.stream._duplexState |= READ_PIPE_DRAINED; + this.updateCallback(); + } + function afterFinal(err) { + const stream2 = this.stream; + if (err) stream2.destroy(err); + if ((stream2._duplexState & DESTROY_STATUS) === 0) { + stream2._duplexState |= WRITE_DONE; + stream2.emit("finish"); + } + if ((stream2._duplexState & AUTO_DESTROY) === DONE) { + stream2._duplexState |= DESTROYING; + } + stream2._duplexState &= WRITE_NOT_FINISHING; + if ((stream2._duplexState & WRITE_UPDATING) === 0) this.update(); + else this.updateNextTick(); + } + function afterDestroy(err) { + const stream2 = this.stream; + if (!err && this.error !== STREAM_DESTROYED) err = this.error; + if (err) stream2.emit("error", err); + stream2._duplexState |= DESTROYED; + stream2.emit("close"); + const rs = stream2._readableState; + const ws = stream2._writableState; + if (rs !== null && rs.pipeline !== null) rs.pipeline.done(stream2, err); + if (ws !== null) { + while (ws.drains !== null && ws.drains.length > 0) ws.drains.shift().resolve(false); + if (ws.pipeline !== null) ws.pipeline.done(stream2, err); + } + } + function afterWrite(err) { + const stream2 = this.stream; + if (err) stream2.destroy(err); + stream2._duplexState &= WRITE_NOT_ACTIVE; + if (this.drains !== null) tickDrains(this.drains); + if ((stream2._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) { + stream2._duplexState &= WRITE_DRAINED; + if ((stream2._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) { + stream2.emit("drain"); + } + } + this.updateCallback(); + } + function afterRead(err) { + if (err) this.stream.destroy(err); + this.stream._duplexState &= READ_NOT_ACTIVE; + if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0) this.stream._duplexState &= READ_NO_READ_AHEAD; + this.updateCallback(); + } + function updateReadNT() { + if ((this.stream._duplexState & READ_UPDATING) === 0) { + this.stream._duplexState &= READ_NOT_NEXT_TICK; + this.update(); + } + } + function updateWriteNT() { + if ((this.stream._duplexState & WRITE_UPDATING) === 0) { + this.stream._duplexState &= WRITE_NOT_NEXT_TICK; + this.update(); + } + } + function tickDrains(drains) { + for (let i = 0; i < drains.length; i++) { + if (--drains[i].writes === 0) { + drains.shift().resolve(true); + i--; + } + } + } + function afterOpen(err) { + const stream2 = this.stream; + if (err) stream2.destroy(err); + if ((stream2._duplexState & DESTROYING) === 0) { + if ((stream2._duplexState & READ_PRIMARY_STATUS) === 0) stream2._duplexState |= READ_PRIMARY; + if ((stream2._duplexState & WRITE_PRIMARY_STATUS) === 0) stream2._duplexState |= WRITE_PRIMARY; + stream2.emit("open"); + } + stream2._duplexState &= NOT_ACTIVE; + if (stream2._writableState !== null) { + stream2._writableState.updateCallback(); + } + if (stream2._readableState !== null) { + stream2._readableState.updateCallback(); + } + } + function afterTransform(err, data) { + if (data !== void 0 && data !== null) this.push(data); + this._writableState.afterWrite(err); + } + function newListener(name) { + if (this._readableState !== null) { + if (name === "data") { + this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD; + this._readableState.updateNextTick(); + } + if (name === "readable") { + this._duplexState |= READ_EMIT_READABLE; + this._readableState.updateNextTick(); + } + } + if (this._writableState !== null) { + if (name === "drain") { + this._duplexState |= WRITE_EMIT_DRAIN; + this._writableState.updateNextTick(); + } + } + } + var Stream = class extends EventEmitter { + constructor(opts) { + super(); + this._duplexState = 0; + this._readableState = null; + this._writableState = null; + if (opts) { + if (opts.open) this._open = opts.open; + if (opts.destroy) this._destroy = opts.destroy; + if (opts.predestroy) this._predestroy = opts.predestroy; + if (opts.signal) { + opts.signal.addEventListener("abort", abort.bind(this)); + } + } + this.on("newListener", newListener); + } + _open(cb) { + cb(null); + } + _destroy(cb) { + cb(null); + } + _predestroy() { + } + get readable() { + return this._readableState !== null ? true : void 0; + } + get writable() { + return this._writableState !== null ? true : void 0; + } + get destroyed() { + return (this._duplexState & DESTROYED) !== 0; + } + get destroying() { + return (this._duplexState & DESTROY_STATUS) !== 0; + } + destroy(err) { + if ((this._duplexState & DESTROY_STATUS) === 0) { + if (!err) err = STREAM_DESTROYED; + this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY; + if (this._readableState !== null) { + this._readableState.highWaterMark = 0; + this._readableState.error = err; + } + if (this._writableState !== null) { + this._writableState.highWaterMark = 0; + this._writableState.error = err; + } + this._duplexState |= PREDESTROYING; + this._predestroy(); + this._duplexState &= NOT_PREDESTROYING; + if (this._readableState !== null) this._readableState.updateNextTick(); + if (this._writableState !== null) this._writableState.updateNextTick(); + } + } + }; + var Readable2 = class _Readable extends Stream { + constructor(opts) { + super(opts); + this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD; + this._readableState = new ReadableState(this, opts); + if (opts) { + if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD; + if (opts.read) this._read = opts.read; + if (opts.eagerOpen) this._readableState.updateNextTick(); + if (opts.encoding) this.setEncoding(opts.encoding); + } + } + setEncoding(encoding) { + const dec = new TextDecoder2(encoding); + const map = this._readableState.map || echo; + this._readableState.map = mapOrSkip; + return this; + function mapOrSkip(data) { + const next = dec.push(data); + return next === "" && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next); + } + } + _read(cb) { + cb(null); + } + pipe(dest, cb) { + this._readableState.updateNextTick(); + this._readableState.pipe(dest, cb); + return dest; + } + read() { + this._readableState.updateNextTick(); + return this._readableState.read(); + } + push(data) { + this._readableState.updateNextTickIfOpen(); + return this._readableState.push(data); + } + unshift(data) { + this._readableState.updateNextTickIfOpen(); + return this._readableState.unshift(data); + } + resume() { + this._duplexState |= READ_RESUMED_READ_AHEAD; + this._readableState.updateNextTick(); + return this; + } + pause() { + this._duplexState &= this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED; + return this; + } + static _fromAsyncIterator(ite, opts) { + let destroy; + const rs = new _Readable({ + ...opts, + read(cb) { + ite.next().then(push).then(cb.bind(null, null)).catch(cb); + }, + predestroy() { + destroy = ite.return(); + }, + destroy(cb) { + if (!destroy) return cb(null); + destroy.then(cb.bind(null, null)).catch(cb); + } + }); + return rs; + function push(data) { + if (data.done) rs.push(null); + else rs.push(data.value); + } + } + static from(data, opts) { + if (isReadStreamx(data)) return data; + if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts); + if (!Array.isArray(data)) data = data === void 0 ? [] : [data]; + let i = 0; + return new _Readable({ + ...opts, + read(cb) { + this.push(i === data.length ? null : data[i++]); + cb(null); + } + }); + } + static isBackpressured(rs) { + return (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 || rs._readableState.buffered >= rs._readableState.highWaterMark; + } + static isPaused(rs) { + return (rs._duplexState & READ_RESUMED) === 0; + } + [asyncIterator]() { + const stream2 = this; + let error2 = null; + let promiseResolve = null; + let promiseReject = null; + this.on("error", (err) => { + error2 = err; + }); + this.on("readable", onreadable); + this.on("close", onclose); + return { + [asyncIterator]() { + return this; + }, + next() { + return new Promise(function(resolve, reject) { + promiseResolve = resolve; + promiseReject = reject; + const data = stream2.read(); + if (data !== null) ondata(data); + else if ((stream2._duplexState & DESTROYED) !== 0) ondata(null); + }); + }, + return() { + return destroy(null); + }, + throw(err) { + return destroy(err); + } + }; + function onreadable() { + if (promiseResolve !== null) ondata(stream2.read()); + } + function onclose() { + if (promiseResolve !== null) ondata(null); + } + function ondata(data) { + if (promiseReject === null) return; + if (error2) promiseReject(error2); + else if (data === null && (stream2._duplexState & READ_DONE) === 0) promiseReject(STREAM_DESTROYED); + else promiseResolve({ value: data, done: data === null }); + promiseReject = promiseResolve = null; + } + function destroy(err) { + stream2.destroy(err); + return new Promise((resolve, reject) => { + if (stream2._duplexState & DESTROYED) return resolve({ value: void 0, done: true }); + stream2.once("close", function() { + if (err) reject(err); + else resolve({ value: void 0, done: true }); + }); + }); + } + } + }; + var Writable2 = class extends Stream { + constructor(opts) { + super(opts); + this._duplexState |= OPENING | READ_DONE; + this._writableState = new WritableState(this, opts); + if (opts) { + if (opts.writev) this._writev = opts.writev; + if (opts.write) this._write = opts.write; + if (opts.final) this._final = opts.final; + if (opts.eagerOpen) this._writableState.updateNextTick(); + } + } + cork() { + this._duplexState |= WRITE_CORKED; + } + uncork() { + this._duplexState &= WRITE_NOT_CORKED; + this._writableState.updateNextTick(); + } + _writev(batch, cb) { + cb(null); + } + _write(data, cb) { + this._writableState.autoBatch(data, cb); + } + _final(cb) { + cb(null); + } + static isBackpressured(ws) { + return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0; + } + static drained(ws) { + if (ws.destroyed) return Promise.resolve(false); + const state = ws._writableState; + const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length; + const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0); + if (writes === 0) return Promise.resolve(true); + if (state.drains === null) state.drains = []; + return new Promise((resolve) => { + state.drains.push({ writes, resolve }); + }); + } + write(data) { + this._writableState.updateNextTick(); + return this._writableState.push(data); + } + end(data) { + this._writableState.updateNextTick(); + this._writableState.end(data); + return this; + } + }; + var Duplex = class extends Readable2 { + // and Writable + constructor(opts) { + super(opts); + this._duplexState = OPENING | this._duplexState & READ_READ_AHEAD; + this._writableState = new WritableState(this, opts); + if (opts) { + if (opts.writev) this._writev = opts.writev; + if (opts.write) this._write = opts.write; + if (opts.final) this._final = opts.final; + } + } + cork() { + this._duplexState |= WRITE_CORKED; + } + uncork() { + this._duplexState &= WRITE_NOT_CORKED; + this._writableState.updateNextTick(); + } + _writev(batch, cb) { + cb(null); + } + _write(data, cb) { + this._writableState.autoBatch(data, cb); + } + _final(cb) { + cb(null); + } + write(data) { + this._writableState.updateNextTick(); + return this._writableState.push(data); + } + end(data) { + this._writableState.updateNextTick(); + this._writableState.end(data); + return this; + } + }; + var Transform = class extends Duplex { + constructor(opts) { + super(opts); + this._transformState = new TransformState(this); + if (opts) { + if (opts.transform) this._transform = opts.transform; + if (opts.flush) this._flush = opts.flush; + } + } + _write(data, cb) { + if (this._readableState.buffered >= this._readableState.highWaterMark) { + this._transformState.data = data; + } else { + this._transform(data, this._transformState.afterTransform); + } + } + _read(cb) { + if (this._transformState.data !== null) { + const data = this._transformState.data; + this._transformState.data = null; + cb(null); + this._transform(data, this._transformState.afterTransform); + } else { + cb(null); + } + } + destroy(err) { + super.destroy(err); + if (this._transformState.data !== null) { + this._transformState.data = null; + this._transformState.afterTransform(); + } + } + _transform(data, cb) { + cb(null, data); + } + _flush(cb) { + cb(null); + } + _final(cb) { + this._transformState.afterFinal = cb; + this._flush(transformAfterFlush.bind(this)); + } + }; + var PassThrough = class extends Transform { + }; + function transformAfterFlush(err, data) { + const cb = this._transformState.afterFinal; + if (err) return cb(err); + if (data !== null && data !== void 0) this.push(data); + this.push(null); + cb(null); + } + function pipelinePromise(...streams) { + return new Promise((resolve, reject) => { + return pipeline(...streams, (err) => { + if (err) return reject(err); + resolve(); + }); + }); + } + function pipeline(stream2, ...streams) { + const all = Array.isArray(stream2) ? [...stream2, ...streams] : [stream2, ...streams]; + const done = all.length && typeof all[all.length - 1] === "function" ? all.pop() : null; + if (all.length < 2) throw new Error("Pipeline requires at least 2 streams"); + let src = all[0]; + let dest = null; + let error2 = null; + for (let i = 1; i < all.length; i++) { + dest = all[i]; + if (isStreamx(src)) { + src.pipe(dest, onerror); + } else { + errorHandle(src, true, i > 1, onerror); + src.pipe(dest); + } + src = dest; + } + if (done) { + let fin = false; + const autoDestroy = isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy); + dest.on("error", (err) => { + if (error2 === null) error2 = err; + }); + dest.on("finish", () => { + fin = true; + if (!autoDestroy) done(error2); + }); + if (autoDestroy) { + dest.on("close", () => done(error2 || (fin ? null : PREMATURE_CLOSE))); + } + } + return dest; + function errorHandle(s, rd, wr, onerror2) { + s.on("error", onerror2); + s.on("close", onclose); + function onclose() { + if (rd && s._readableState && !s._readableState.ended) return onerror2(PREMATURE_CLOSE); + if (wr && s._writableState && !s._writableState.ended) return onerror2(PREMATURE_CLOSE); + } + } + function onerror(err) { + if (!err || error2) return; + error2 = err; + for (const s of all) { + s.destroy(err); + } + } + } + function echo(s) { + return s; + } + function isStream(stream2) { + return !!stream2._readableState || !!stream2._writableState; + } + function isStreamx(stream2) { + return typeof stream2._duplexState === "number" && isStream(stream2); + } + function isEnded(stream2) { + return !!stream2._readableState && stream2._readableState.ended; + } + function isFinished(stream2) { + return !!stream2._writableState && stream2._writableState.ended; + } + function getStreamError(stream2, opts = {}) { + const err = stream2._readableState && stream2._readableState.error || stream2._writableState && stream2._writableState.error; + return !opts.all && err === STREAM_DESTROYED ? null : err; + } + function isReadStreamx(stream2) { + return isStreamx(stream2) && stream2.readable; + } + function isDisturbed(stream2) { + return (stream2._duplexState & OPENING) !== OPENING || (stream2._duplexState & ACTIVE_OR_TICKING) !== 0; + } + function isTypedArray(data) { + return typeof data === "object" && data !== null && typeof data.byteLength === "number"; + } + function defaultByteLength(data) { + return isTypedArray(data) ? data.byteLength : 1024; + } + function noop3() { + } + function abort() { + this.destroy(new Error("Stream aborted.")); + } + function isWritev(s) { + return s._writev !== Writable2.prototype._writev && s._writev !== Duplex.prototype._writev; + } + module2.exports = { + pipeline, + pipelinePromise, + isStream, + isStreamx, + isEnded, + isFinished, + isDisturbed, + getStreamError, + Stream, + Writable: Writable2, + Readable: Readable2, + Duplex, + Transform, + // Export PassThrough for compatibility with Node.js core's stream module + PassThrough + }; + } +}); + +// node_modules/tar-stream/headers.js +var require_headers3 = __commonJS({ + "node_modules/tar-stream/headers.js"(exports2) { + var b4a = require_b4a(); + var ZEROS = "0000000000000000000"; + var SEVENS = "7777777777777777777"; + var ZERO_OFFSET = "0".charCodeAt(0); + var USTAR_MAGIC = b4a.from([117, 115, 116, 97, 114, 0]); + var USTAR_VER = b4a.from([ZERO_OFFSET, ZERO_OFFSET]); + var GNU_MAGIC = b4a.from([117, 115, 116, 97, 114, 32]); + var GNU_VER = b4a.from([32, 0]); + var MASK = 4095; + var MAGIC_OFFSET = 257; + var VERSION_OFFSET = 263; + exports2.decodeLongPath = function decodeLongPath(buf, encoding) { + return decodeStr(buf, 0, buf.length, encoding); + }; + exports2.encodePax = function encodePax(opts) { + let result = ""; + if (opts.name) result += addLength(" path=" + opts.name + "\n"); + if (opts.linkname) result += addLength(" linkpath=" + opts.linkname + "\n"); + const pax = opts.pax; + if (pax) { + for (const key in pax) { + result += addLength(" " + key + "=" + pax[key] + "\n"); + } + } + return b4a.from(result); + }; + exports2.decodePax = function decodePax(buf) { + const result = {}; + while (buf.length) { + let i = 0; + while (i < buf.length && buf[i] !== 32) i++; + const len = parseInt(b4a.toString(buf.subarray(0, i)), 10); + if (!len) return result; + const b = b4a.toString(buf.subarray(i + 1, len - 1)); + const keyIndex = b.indexOf("="); + if (keyIndex === -1) return result; + result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1); + buf = buf.subarray(len); + } + return result; + }; + exports2.encode = function encode(opts) { + const buf = b4a.alloc(512); + let name = opts.name; + let prefix = ""; + if (opts.typeflag === 5 && name[name.length - 1] !== "/") name += "/"; + if (b4a.byteLength(name) !== name.length) return null; + while (b4a.byteLength(name) > 100) { + const i = name.indexOf("/"); + if (i === -1) return null; + prefix += prefix ? "/" + name.slice(0, i) : name.slice(0, i); + name = name.slice(i + 1); + } + if (b4a.byteLength(name) > 100 || b4a.byteLength(prefix) > 155) return null; + if (opts.linkname && b4a.byteLength(opts.linkname) > 100) return null; + b4a.write(buf, name); + b4a.write(buf, encodeOct(opts.mode & MASK, 6), 100); + b4a.write(buf, encodeOct(opts.uid, 6), 108); + b4a.write(buf, encodeOct(opts.gid, 6), 116); + encodeSize(opts.size, buf, 124); + b4a.write(buf, encodeOct(opts.mtime.getTime() / 1e3 | 0, 11), 136); + buf[156] = ZERO_OFFSET + toTypeflag(opts.type); + if (opts.linkname) b4a.write(buf, opts.linkname, 157); + b4a.copy(USTAR_MAGIC, buf, MAGIC_OFFSET); + b4a.copy(USTAR_VER, buf, VERSION_OFFSET); + if (opts.uname) b4a.write(buf, opts.uname, 265); + if (opts.gname) b4a.write(buf, opts.gname, 297); + b4a.write(buf, encodeOct(opts.devmajor || 0, 6), 329); + b4a.write(buf, encodeOct(opts.devminor || 0, 6), 337); + if (prefix) b4a.write(buf, prefix, 345); + b4a.write(buf, encodeOct(cksum(buf), 6), 148); + return buf; + }; + exports2.decode = function decode(buf, filenameEncoding, allowUnknownFormat) { + let typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET; + let name = decodeStr(buf, 0, 100, filenameEncoding); + const mode = decodeOct(buf, 100, 8); + const uid = decodeOct(buf, 108, 8); + const gid = decodeOct(buf, 116, 8); + const size = decodeOct(buf, 124, 12); + const mtime = decodeOct(buf, 136, 12); + const type = toType(typeflag); + const linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100, filenameEncoding); + const uname = decodeStr(buf, 265, 32); + const gname = decodeStr(buf, 297, 32); + const devmajor = decodeOct(buf, 329, 8); + const devminor = decodeOct(buf, 337, 8); + const c = cksum(buf); + if (c === 8 * 32) return null; + if (c !== decodeOct(buf, 148, 8)) throw new Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?"); + if (isUSTAR(buf)) { + if (buf[345]) name = decodeStr(buf, 345, 155, filenameEncoding) + "/" + name; + } else if (isGNU(buf)) { + } else { + if (!allowUnknownFormat) { + throw new Error("Invalid tar header: unknown format."); + } + } + if (typeflag === 0 && name && name[name.length - 1] === "/") typeflag = 5; + return { + name, + mode, + uid, + gid, + size, + byteOffset: 0, + mtime: new Date(1e3 * mtime), + type, + linkname, + uname, + gname, + devmajor, + devminor, + pax: null + }; + }; + function isUSTAR(buf) { + return b4a.equals(USTAR_MAGIC, buf.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6)); + } + function isGNU(buf) { + return b4a.equals(GNU_MAGIC, buf.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6)) && b4a.equals(GNU_VER, buf.subarray(VERSION_OFFSET, VERSION_OFFSET + 2)); + } + function clamp(index, len, defaultValue) { + if (typeof index !== "number") return defaultValue; + index = ~~index; + if (index >= len) return len; + if (index >= 0) return index; + index += len; + if (index >= 0) return index; + return 0; + } + function toType(flag) { + switch (flag) { + case 0: + return "file"; + case 1: + return "link"; + case 2: + return "symlink"; + case 3: + return "character-device"; + case 4: + return "block-device"; + case 5: + return "directory"; + case 6: + return "fifo"; + case 7: + return "contiguous-file"; + case 72: + return "pax-header"; + case 55: + return "pax-global-header"; + case 27: + return "gnu-long-link-path"; + case 28: + case 30: + return "gnu-long-path"; + } + return null; + } + function toTypeflag(flag) { + switch (flag) { + case "file": + return 0; + case "link": + return 1; + case "symlink": + return 2; + case "character-device": + return 3; + case "block-device": + return 4; + case "directory": + return 5; + case "fifo": + return 6; + case "contiguous-file": + return 7; + case "pax-header": + return 72; + } + return 0; + } + function indexOf(block, num, offset, end) { + for (; offset < end; offset++) { + if (block[offset] === num) return offset; + } + return end; + } + function cksum(block) { + let sum = 8 * 32; + for (let i = 0; i < 148; i++) sum += block[i]; + for (let j = 156; j < 512; j++) sum += block[j]; + return sum; + } + function encodeOct(val, n) { + val = val.toString(8); + if (val.length > n) return SEVENS.slice(0, n) + " "; + return ZEROS.slice(0, n - val.length) + val + " "; + } + function encodeSizeBin(num, buf, off) { + buf[off] = 128; + for (let i = 11; i > 0; i--) { + buf[off + i] = num & 255; + num = Math.floor(num / 256); + } + } + function encodeSize(num, buf, off) { + if (num.toString(8).length > 11) { + encodeSizeBin(num, buf, off); + } else { + b4a.write(buf, encodeOct(num, 11), off); + } + } + function parse256(buf) { + let positive; + if (buf[0] === 128) positive = true; + else if (buf[0] === 255) positive = false; + else return null; + const tuple = []; + let i; + for (i = buf.length - 1; i > 0; i--) { + const byte = buf[i]; + if (positive) tuple.push(byte); + else tuple.push(255 - byte); + } + let sum = 0; + const l = tuple.length; + for (i = 0; i < l; i++) { + sum += tuple[i] * Math.pow(256, i); + } + return positive ? sum : -1 * sum; + } + function decodeOct(val, offset, length) { + val = val.subarray(offset, offset + length); + offset = 0; + if (val[offset] & 128) { + return parse256(val); + } else { + while (offset < val.length && val[offset] === 32) offset++; + const end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length); + while (offset < end && val[offset] === 0) offset++; + if (end === offset) return 0; + return parseInt(b4a.toString(val.subarray(offset, end)), 8); + } + } + function decodeStr(val, offset, length, encoding) { + return b4a.toString(val.subarray(offset, indexOf(val, 0, offset, offset + length)), encoding); + } + function addLength(str) { + const len = b4a.byteLength(str); + let digits = Math.floor(Math.log(len) / Math.log(10)) + 1; + if (len + digits >= Math.pow(10, digits)) digits++; + return len + digits + str; + } + } +}); + +// node_modules/tar-stream/extract.js +var require_extract2 = __commonJS({ + "node_modules/tar-stream/extract.js"(exports2, module2) { + var { Writable: Writable2, Readable: Readable2, getStreamError } = require_streamx(); + var FIFO = require_fast_fifo(); + var b4a = require_b4a(); + var headers = require_headers3(); + var EMPTY = b4a.alloc(0); + var MAX_HEADER_SIZE = 4 * 1024 * 1024; + var BufferList = class { + constructor() { + this.buffered = 0; + this.shifted = 0; + this.queue = new FIFO(); + this._offset = 0; + } + push(buffer) { + this.buffered += buffer.byteLength; + this.queue.push(buffer); + } + shiftFirst(size) { + return this.buffered === 0 ? null : this._next(size); + } + shift(size) { + if (size > this.buffered) return null; + if (size === 0) return EMPTY; + let chunk = this._next(size); + if (size === chunk.byteLength) return chunk; + const chunks = [chunk]; + while ((size -= chunk.byteLength) > 0) { + chunk = this._next(size); + chunks.push(chunk); + } + return b4a.concat(chunks); + } + _next(size) { + const buf = this.queue.peek(); + const rem = buf.byteLength - this._offset; + if (size >= rem) { + const sub = this._offset ? buf.subarray(this._offset, buf.byteLength) : buf; + this.queue.shift(); + this._offset = 0; + this.buffered -= rem; + this.shifted += rem; + return sub; + } + this.buffered -= size; + this.shifted += size; + return buf.subarray(this._offset, this._offset += size); + } + }; + var Source = class extends Readable2 { + constructor(self2, header, offset) { + super(); + this.header = header; + this.offset = offset; + this._parent = self2; + } + _read(cb) { + if (this.header.size === 0) { + this.push(null); + } + if (this._parent._stream === this) { + this._parent._update(); + } + cb(null); + } + _predestroy() { + this._parent.destroy(getStreamError(this)); + } + _detach() { + if (this._parent._stream === this) { + this._parent._stream = null; + this._parent._missing = overflow(this.header.size); + this._parent._update(); + } + } + _destroy(cb) { + this._detach(); + cb(null); + } + }; + var Extract = class extends Writable2 { + constructor(opts) { + super(opts); + if (!opts) opts = {}; + this._buffer = new BufferList(); + this._offset = 0; + this._header = null; + this._stream = null; + this._missing = 0; + this._longHeader = false; + this._callback = noop3; + this._locked = false; + this._finished = false; + this._pax = null; + this._paxGlobal = null; + this._gnuLongPath = null; + this._gnuLongLinkPath = null; + this._filenameEncoding = opts.filenameEncoding || "utf-8"; + this._allowUnknownFormat = !!opts.allowUnknownFormat; + this._unlockBound = this._unlock.bind(this); + } + _unlock(err) { + this._locked = false; + if (err) { + this.destroy(err); + this._continueWrite(err); + return; + } + this._update(); + } + _consumeHeader() { + if (this._locked) return false; + this._offset = this._buffer.shifted; + try { + this._header = headers.decode(this._buffer.shift(512), this._filenameEncoding, this._allowUnknownFormat); + } catch (err) { + this._continueWrite(err); + return false; + } + if (!this._header) return true; + this._header.byteOffset = this._buffer.shifted; + switch (this._header.type) { + case "gnu-long-path": + case "gnu-long-link-path": + case "pax-global-header": + case "pax-header": + this._longHeader = true; + this._missing = this._header.size; + if (this._missing > MAX_HEADER_SIZE) { + this._continueWrite(new Error("Header exceeds max size")); + return false; + } + return true; + } + this._locked = true; + this._applyLongHeaders(); + if (!(this._header.size >= 0)) { + this._continueWrite(new Error("Invalid header")); + return false; + } + if (this._header.size === 0 || this._header.type === "directory") { + this.emit("entry", this._header, this._createStream(), this._unlockBound); + return true; + } + this._stream = this._createStream(); + this._missing = this._header.size; + this.emit("entry", this._header, this._stream, this._unlockBound); + return true; + } + _applyLongHeaders() { + if (this._gnuLongPath) { + this._header.name = this._gnuLongPath; + this._gnuLongPath = null; + } + if (this._gnuLongLinkPath) { + this._header.linkname = this._gnuLongLinkPath; + this._gnuLongLinkPath = null; + } + if (this._pax) { + if (this._pax.path) this._header.name = this._pax.path; + if (this._pax.linkpath) this._header.linkname = this._pax.linkpath; + if (this._pax.size) this._header.size = parseInt(this._pax.size, 10); + this._header.pax = this._pax; + this._pax = null; + } + } + _decodeLongHeader(buf) { + switch (this._header.type) { + case "gnu-long-path": + this._gnuLongPath = headers.decodeLongPath(buf, this._filenameEncoding); + break; + case "gnu-long-link-path": + this._gnuLongLinkPath = headers.decodeLongPath(buf, this._filenameEncoding); + break; + case "pax-global-header": + this._paxGlobal = headers.decodePax(buf); + break; + case "pax-header": + this._pax = this._paxGlobal === null ? headers.decodePax(buf) : Object.assign({}, this._paxGlobal, headers.decodePax(buf)); + break; + } + } + _consumeLongHeader() { + this._longHeader = false; + this._missing = overflow(this._header.size); + const buf = this._buffer.shift(this._header.size); + try { + this._decodeLongHeader(buf); + } catch (err) { + this._continueWrite(err); + return false; + } + return true; + } + _consumeStream() { + const buf = this._buffer.shiftFirst(this._missing); + if (buf === null) return false; + this._missing -= buf.byteLength; + const drained = this._stream.push(buf); + if (this._missing === 0) { + this._stream.push(null); + if (drained) this._stream._detach(); + return drained && this._locked === false; + } + return drained; + } + _createStream() { + return new Source(this, this._header, this._offset); + } + _update() { + while (this._buffer.buffered > 0 && !this.destroying) { + if (this._missing > 0) { + if (this._stream !== null) { + if (this._consumeStream() === false) return; + continue; + } + if (this._longHeader === true) { + if (this._missing > this._buffer.buffered) break; + if (this._consumeLongHeader() === false) return false; + continue; + } + const ignore = this._buffer.shiftFirst(this._missing); + if (ignore !== null) this._missing -= ignore.byteLength; + continue; + } + if (this._buffer.buffered < 512) break; + if (this._stream !== null || this._consumeHeader() === false) return; + } + this._continueWrite(null); + } + _continueWrite(err) { + const cb = this._callback; + this._callback = noop3; + cb(err); + } + _write(data, cb) { + this._callback = cb; + this._buffer.push(data); + this._update(); + } + _final(cb) { + this._finished = this._missing === 0 && this._buffer.buffered === 0; + cb(this._finished ? null : new Error("Unexpected end of data")); + } + _predestroy() { + this._continueWrite(null); + } + _destroy(cb) { + if (this._stream) this._stream.destroy(getStreamError(this)); + cb(null); + } + [Symbol.asyncIterator]() { + let error2 = null; + let promiseResolve = null; + let promiseReject = null; + let entryStream = null; + let entryCallback = null; + const extract2 = this; + this.on("entry", onentry); + this.on("error", (err) => { + error2 = err; + }); + this.on("close", onclose); + return { + [Symbol.asyncIterator]() { + return this; + }, + next() { + return new Promise(onnext); + }, + return() { + return destroy(null); + }, + throw(err) { + return destroy(err); + } + }; + function consumeCallback(err) { + if (!entryCallback) return; + const cb = entryCallback; + entryCallback = null; + cb(err); + } + function onnext(resolve, reject) { + if (error2) { + return reject(error2); + } + if (entryStream) { + resolve({ value: entryStream, done: false }); + entryStream = null; + return; + } + promiseResolve = resolve; + promiseReject = reject; + consumeCallback(null); + if (extract2._finished && promiseResolve) { + promiseResolve({ value: void 0, done: true }); + promiseResolve = promiseReject = null; + } + } + function onentry(header, stream2, callback) { + entryCallback = callback; + stream2.on("error", noop3); + if (promiseResolve) { + promiseResolve({ value: stream2, done: false }); + promiseResolve = promiseReject = null; + } else { + entryStream = stream2; + } + } + function onclose() { + consumeCallback(error2); + if (!promiseResolve) return; + if (error2) promiseReject(error2); + else promiseResolve({ value: void 0, done: true }); + promiseResolve = promiseReject = null; + } + function destroy(err) { + extract2.destroy(err); + consumeCallback(err); + return new Promise((resolve, reject) => { + if (extract2.destroyed) return resolve({ value: void 0, done: true }); + extract2.once("close", function() { + if (err) reject(err); + else resolve({ value: void 0, done: true }); + }); + }); + } + } + }; + module2.exports = function extract2(opts) { + return new Extract(opts); + }; + function noop3() { + } + function overflow(size) { + size &= 511; + return size && 512 - size; + } + } +}); + +// node_modules/tar-stream/constants.js +var require_constants8 = __commonJS({ + "node_modules/tar-stream/constants.js"(exports2, module2) { + var constants3 = { + // just for envs without fs + S_IFMT: 61440, + S_IFDIR: 16384, + S_IFCHR: 8192, + S_IFBLK: 24576, + S_IFIFO: 4096, + S_IFLNK: 40960 + }; + try { + module2.exports = require("fs").constants || constants3; + } catch { + module2.exports = constants3; + } + } +}); + +// node_modules/tar-stream/pack.js +var require_pack2 = __commonJS({ + "node_modules/tar-stream/pack.js"(exports2, module2) { + var { Readable: Readable2, Writable: Writable2, getStreamError } = require_streamx(); + var b4a = require_b4a(); + var constants3 = require_constants8(); + var headers = require_headers3(); + var DMODE = 493; + var FMODE = 420; + var END_OF_TAR = b4a.alloc(1024); + var Sink = class extends Writable2 { + constructor(pack2, header, callback) { + super({ mapWritable, eagerOpen: true }); + this.written = 0; + this.header = header; + this._callback = callback; + this._linkname = null; + this._isLinkname = header.type === "symlink" && !header.linkname; + this._isVoid = header.type !== "file" && header.type !== "contiguous-file"; + this._finished = false; + this._pack = pack2; + this._openCallback = null; + if (this._pack._stream === null) this._pack._stream = this; + else this._pack._pending.push(this); + } + _open(cb) { + this._openCallback = cb; + if (this._pack._stream === this) this._continueOpen(); + } + _continuePack(err) { + if (this._callback === null) return; + const callback = this._callback; + this._callback = null; + callback(err); + } + _continueOpen() { + if (this._pack._stream === null) this._pack._stream = this; + const cb = this._openCallback; + this._openCallback = null; + if (cb === null) return; + if (this._pack.destroying) return cb(new Error("pack stream destroyed")); + if (this._pack._finalized) return cb(new Error("pack stream is already finalized")); + this._pack._stream = this; + if (!this._isLinkname) { + this._pack._encode(this.header); + } + if (this._isVoid) { + this._finish(); + this._continuePack(null); + } + cb(null); + } + _write(data, cb) { + if (this._isLinkname) { + this._linkname = this._linkname ? b4a.concat([this._linkname, data]) : data; + return cb(null); + } + if (this._isVoid) { + if (data.byteLength > 0) { + return cb(new Error("No body allowed for this entry")); + } + return cb(); + } + this.written += data.byteLength; + if (this._pack.push(data)) return cb(); + this._pack._drain = cb; + } + _finish() { + if (this._finished) return; + this._finished = true; + if (this._isLinkname) { + this.header.linkname = this._linkname ? b4a.toString(this._linkname, "utf-8") : ""; + this._pack._encode(this.header); + } + overflow(this._pack, this.header.size); + this._pack._done(this); + } + _final(cb) { + if (this.written !== this.header.size) { + return cb(new Error("Size mismatch")); + } + this._finish(); + cb(null); + } + _getError() { + return getStreamError(this) || new Error("tar entry destroyed"); + } + _predestroy() { + this._pack.destroy(this._getError()); + } + _destroy(cb) { + this._pack._done(this); + this._continuePack(this._finished ? null : this._getError()); + cb(); + } + }; + var Pack = class extends Readable2 { + constructor(opts) { + super(opts); + this._drain = noop3; + this._finalized = false; + this._finalizing = false; + this._pending = []; + this._stream = null; + } + entry(header, buffer, callback) { + if (this._finalized || this.destroying) throw new Error("already finalized or destroyed"); + if (typeof buffer === "function") { + callback = buffer; + buffer = null; + } + if (!callback) callback = noop3; + if (!header.size || header.type === "symlink") header.size = 0; + if (!header.type) header.type = modeToType(header.mode); + if (!header.mode) header.mode = header.type === "directory" ? DMODE : FMODE; + if (!header.uid) header.uid = 0; + if (!header.gid) header.gid = 0; + if (!header.mtime) header.mtime = /* @__PURE__ */ new Date(); + if (typeof buffer === "string") buffer = b4a.from(buffer); + const sink = new Sink(this, header, callback); + if (b4a.isBuffer(buffer)) { + header.size = buffer.byteLength; + sink.write(buffer); + sink.end(); + return sink; + } + if (sink._isVoid) { + return sink; + } + return sink; + } + finalize() { + if (this._stream || this._pending.length > 0) { + this._finalizing = true; + return; + } + if (this._finalized) return; + this._finalized = true; + this.push(END_OF_TAR); + this.push(null); + } + _done(stream2) { + if (stream2 !== this._stream) return; + this._stream = null; + if (this._finalizing) this.finalize(); + if (this._pending.length) this._pending.shift()._continueOpen(); + } + _encode(header) { + if (!header.pax) { + const buf = headers.encode(header); + if (buf) { + this.push(buf); + return; + } + } + this._encodePax(header); + } + _encodePax(header) { + const paxHeader = headers.encodePax({ + name: header.name, + linkname: header.linkname, + pax: header.pax + }); + const newHeader = { + name: "PaxHeader", + mode: header.mode, + uid: header.uid, + gid: header.gid, + size: paxHeader.byteLength, + mtime: header.mtime, + type: "pax-header", + linkname: header.linkname && "PaxHeader", + uname: header.uname, + gname: header.gname, + devmajor: header.devmajor, + devminor: header.devminor + }; + this.push(headers.encode(newHeader)); + this.push(paxHeader); + overflow(this, paxHeader.byteLength); + newHeader.size = header.size; + newHeader.type = header.type; + this.push(headers.encode(newHeader)); + } + _doDrain() { + const drain = this._drain; + this._drain = noop3; + drain(); + } + _predestroy() { + const err = getStreamError(this); + if (this._stream) this._stream.destroy(err); + while (this._pending.length) { + const stream2 = this._pending.shift(); + stream2.destroy(err); + stream2._continueOpen(); + } + this._doDrain(); + } + _read(cb) { + this._doDrain(); + cb(); + } + }; + module2.exports = function pack2(opts) { + return new Pack(opts); + }; + function modeToType(mode) { + switch (mode & constants3.S_IFMT) { + case constants3.S_IFBLK: + return "block-device"; + case constants3.S_IFCHR: + return "character-device"; + case constants3.S_IFDIR: + return "directory"; + case constants3.S_IFIFO: + return "fifo"; + case constants3.S_IFLNK: + return "symlink"; + } + return "file"; + } + function noop3() { + } + function overflow(self2, size) { + size &= 511; + if (size) self2.push(END_OF_TAR.subarray(0, 512 - size)); + } + function mapWritable(buf) { + return b4a.isBuffer(buf) ? buf : b4a.from(buf); + } + } +}); + +// node_modules/tar-stream/index.js +var require_tar_stream2 = __commonJS({ + "node_modules/tar-stream/index.js"(exports2) { + exports2.extract = require_extract2(); + exports2.pack = require_pack2(); + } +}); + +// node_modules/node-forge/lib/forge.js +var require_forge = __commonJS({ + "node_modules/node-forge/lib/forge.js"(exports2, module2) { + module2.exports = { + // default options + options: { + usePureJavaScript: false + } + }; + } +}); + +// node_modules/node-forge/lib/baseN.js +var require_baseN = __commonJS({ + "node_modules/node-forge/lib/baseN.js"(exports2, module2) { + var api = {}; + module2.exports = api; + var _reverseAlphabets = {}; + api.encode = function(input, alphabet, maxline) { + if (typeof alphabet !== "string") { + throw new TypeError('"alphabet" must be a string.'); + } + if (maxline !== void 0 && typeof maxline !== "number") { + throw new TypeError('"maxline" must be a number.'); + } + var output = ""; + if (!(input instanceof Uint8Array)) { + output = _encodeWithByteBuffer(input, alphabet); + } else { + var i = 0; + var base = alphabet.length; + var first = alphabet.charAt(0); + var digits = [0]; + for (i = 0; i < input.length; ++i) { + for (var j = 0, carry = input[i]; j < digits.length; ++j) { + carry += digits[j] << 8; + digits[j] = carry % base; + carry = carry / base | 0; + } + while (carry > 0) { + digits.push(carry % base); + carry = carry / base | 0; + } + } + for (i = 0; input[i] === 0 && i < input.length - 1; ++i) { + output += first; + } + for (i = digits.length - 1; i >= 0; --i) { + output += alphabet[digits[i]]; + } + } + if (maxline) { + var regex = new RegExp(".{1," + maxline + "}", "g"); + output = output.match(regex).join("\r\n"); + } + return output; + }; + api.decode = function(input, alphabet) { + if (typeof input !== "string") { + throw new TypeError('"input" must be a string.'); + } + if (typeof alphabet !== "string") { + throw new TypeError('"alphabet" must be a string.'); + } + var table = _reverseAlphabets[alphabet]; + if (!table) { + table = _reverseAlphabets[alphabet] = []; + for (var i = 0; i < alphabet.length; ++i) { + table[alphabet.charCodeAt(i)] = i; + } + } + input = input.replace(/\s/g, ""); + var base = alphabet.length; + var first = alphabet.charAt(0); + var bytes = [0]; + for (var i = 0; i < input.length; i++) { + var value = table[input.charCodeAt(i)]; + if (value === void 0) { + return; + } + for (var j = 0, carry = value; j < bytes.length; ++j) { + carry += bytes[j] * base; + bytes[j] = carry & 255; + carry >>= 8; + } + while (carry > 0) { + bytes.push(carry & 255); + carry >>= 8; + } + } + for (var k = 0; input[k] === first && k < input.length - 1; ++k) { + bytes.push(0); + } + if (typeof Buffer !== "undefined") { + return Buffer.from(bytes.reverse()); + } + return new Uint8Array(bytes.reverse()); + }; + function _encodeWithByteBuffer(input, alphabet) { + var i = 0; + var base = alphabet.length; + var first = alphabet.charAt(0); + var digits = [0]; + for (i = 0; i < input.length(); ++i) { + for (var j = 0, carry = input.at(i); j < digits.length; ++j) { + carry += digits[j] << 8; + digits[j] = carry % base; + carry = carry / base | 0; + } + while (carry > 0) { + digits.push(carry % base); + carry = carry / base | 0; + } + } + var output = ""; + for (i = 0; input.at(i) === 0 && i < input.length() - 1; ++i) { + output += first; + } + for (i = digits.length - 1; i >= 0; --i) { + output += alphabet[digits[i]]; + } + return output; + } + } +}); + +// node_modules/node-forge/lib/util.js +var require_util13 = __commonJS({ + "node_modules/node-forge/lib/util.js"(exports2, module2) { + var forge = require_forge(); + var baseN = require_baseN(); + var util = module2.exports = forge.util = forge.util || {}; + (function() { + if (typeof process !== "undefined" && process.nextTick && !process.browser) { + util.nextTick = process.nextTick; + if (typeof setImmediate === "function") { + util.setImmediate = setImmediate; + } else { + util.setImmediate = util.nextTick; + } + return; + } + if (typeof setImmediate === "function") { + util.setImmediate = function() { + return setImmediate.apply(void 0, arguments); + }; + util.nextTick = function(callback) { + return setImmediate(callback); + }; + return; + } + util.setImmediate = function(callback) { + setTimeout(callback, 0); + }; + if (typeof window !== "undefined" && typeof window.postMessage === "function") { + let handler3 = function(event) { + if (event.source === window && event.data === msg) { + event.stopPropagation(); + var copy = callbacks.slice(); + callbacks.length = 0; + copy.forEach(function(callback) { + callback(); + }); + } + }; + var handler2 = handler3; + var msg = "forge.setImmediate"; + var callbacks = []; + util.setImmediate = function(callback) { + callbacks.push(callback); + if (callbacks.length === 1) { + window.postMessage(msg, "*"); + } + }; + window.addEventListener("message", handler3, true); + } + if (typeof MutationObserver !== "undefined") { + var now = Date.now(); + var attr = true; + var div = document.createElement("div"); + var callbacks = []; + new MutationObserver(function() { + var copy = callbacks.slice(); + callbacks.length = 0; + copy.forEach(function(callback) { + callback(); + }); + }).observe(div, { attributes: true }); + var oldSetImmediate = util.setImmediate; + util.setImmediate = function(callback) { + if (Date.now() - now > 15) { + now = Date.now(); + oldSetImmediate(callback); + } else { + callbacks.push(callback); + if (callbacks.length === 1) { + div.setAttribute("a", attr = !attr); + } + } + }; + } + util.nextTick = util.setImmediate; + })(); + util.isNodejs = typeof process !== "undefined" && process.versions && process.versions.node; + util.globalScope = (function() { + if (util.isNodejs) { + return global; + } + return typeof self === "undefined" ? window : self; + })(); + util.isArray = Array.isArray || function(x) { + return Object.prototype.toString.call(x) === "[object Array]"; + }; + util.isArrayBuffer = function(x) { + return typeof ArrayBuffer !== "undefined" && x instanceof ArrayBuffer; + }; + util.isArrayBufferView = function(x) { + return x && util.isArrayBuffer(x.buffer) && x.byteLength !== void 0; + }; + function _checkBitsParam(n) { + if (!(n === 8 || n === 16 || n === 24 || n === 32)) { + throw new Error("Only 8, 16, 24, or 32 bits supported: " + n); + } + } + util.ByteBuffer = ByteStringBuffer; + function ByteStringBuffer(b) { + this.data = ""; + this.read = 0; + if (typeof b === "string") { + this.data = b; + } else if (util.isArrayBuffer(b) || util.isArrayBufferView(b)) { + if (typeof Buffer !== "undefined" && b instanceof Buffer) { + this.data = b.toString("binary"); + } else { + var arr = new Uint8Array(b); + try { + this.data = String.fromCharCode.apply(null, arr); + } catch (e) { + for (var i = 0; i < arr.length; ++i) { + this.putByte(arr[i]); + } + } + } + } else if (b instanceof ByteStringBuffer || typeof b === "object" && typeof b.data === "string" && typeof b.read === "number") { + this.data = b.data; + this.read = b.read; + } + this._constructedStringLength = 0; + } + util.ByteStringBuffer = ByteStringBuffer; + var _MAX_CONSTRUCTED_STRING_LENGTH = 4096; + util.ByteStringBuffer.prototype._optimizeConstructedString = function(x) { + this._constructedStringLength += x; + if (this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) { + this.data.substr(0, 1); + this._constructedStringLength = 0; + } + }; + util.ByteStringBuffer.prototype.length = function() { + return this.data.length - this.read; + }; + util.ByteStringBuffer.prototype.isEmpty = function() { + return this.length() <= 0; + }; + util.ByteStringBuffer.prototype.putByte = function(b) { + return this.putBytes(String.fromCharCode(b)); + }; + util.ByteStringBuffer.prototype.fillWithByte = function(b, n) { + b = String.fromCharCode(b); + var d = this.data; + while (n > 0) { + if (n & 1) { + d += b; + } + n >>>= 1; + if (n > 0) { + b += b; + } + } + this.data = d; + this._optimizeConstructedString(n); + return this; + }; + util.ByteStringBuffer.prototype.putBytes = function(bytes) { + this.data += bytes; + this._optimizeConstructedString(bytes.length); + return this; + }; + util.ByteStringBuffer.prototype.putString = function(str) { + return this.putBytes(util.encodeUtf8(str)); + }; + util.ByteStringBuffer.prototype.putInt16 = function(i) { + return this.putBytes( + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i & 255) + ); + }; + util.ByteStringBuffer.prototype.putInt24 = function(i) { + return this.putBytes( + String.fromCharCode(i >> 16 & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i & 255) + ); + }; + util.ByteStringBuffer.prototype.putInt32 = function(i) { + return this.putBytes( + String.fromCharCode(i >> 24 & 255) + String.fromCharCode(i >> 16 & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i & 255) + ); + }; + util.ByteStringBuffer.prototype.putInt16Le = function(i) { + return this.putBytes( + String.fromCharCode(i & 255) + String.fromCharCode(i >> 8 & 255) + ); + }; + util.ByteStringBuffer.prototype.putInt24Le = function(i) { + return this.putBytes( + String.fromCharCode(i & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i >> 16 & 255) + ); + }; + util.ByteStringBuffer.prototype.putInt32Le = function(i) { + return this.putBytes( + String.fromCharCode(i & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i >> 16 & 255) + String.fromCharCode(i >> 24 & 255) + ); + }; + util.ByteStringBuffer.prototype.putInt = function(i, n) { + _checkBitsParam(n); + var bytes = ""; + do { + n -= 8; + bytes += String.fromCharCode(i >> n & 255); + } while (n > 0); + return this.putBytes(bytes); + }; + util.ByteStringBuffer.prototype.putSignedInt = function(i, n) { + if (i < 0) { + i += 2 << n - 1; + } + return this.putInt(i, n); + }; + util.ByteStringBuffer.prototype.putBuffer = function(buffer) { + return this.putBytes(buffer.getBytes()); + }; + util.ByteStringBuffer.prototype.getByte = function() { + return this.data.charCodeAt(this.read++); + }; + util.ByteStringBuffer.prototype.getInt16 = function() { + var rval = this.data.charCodeAt(this.read) << 8 ^ this.data.charCodeAt(this.read + 1); + this.read += 2; + return rval; + }; + util.ByteStringBuffer.prototype.getInt24 = function() { + var rval = this.data.charCodeAt(this.read) << 16 ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2); + this.read += 3; + return rval; + }; + util.ByteStringBuffer.prototype.getInt32 = function() { + var rval = this.data.charCodeAt(this.read) << 24 ^ this.data.charCodeAt(this.read + 1) << 16 ^ this.data.charCodeAt(this.read + 2) << 8 ^ this.data.charCodeAt(this.read + 3); + this.read += 4; + return rval; + }; + util.ByteStringBuffer.prototype.getInt16Le = function() { + var rval = this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8; + this.read += 2; + return rval; + }; + util.ByteStringBuffer.prototype.getInt24Le = function() { + var rval = this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2) << 16; + this.read += 3; + return rval; + }; + util.ByteStringBuffer.prototype.getInt32Le = function() { + var rval = this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2) << 16 ^ this.data.charCodeAt(this.read + 3) << 24; + this.read += 4; + return rval; + }; + util.ByteStringBuffer.prototype.getInt = function(n) { + _checkBitsParam(n); + var rval = 0; + do { + rval = (rval << 8) + this.data.charCodeAt(this.read++); + n -= 8; + } while (n > 0); + return rval; + }; + util.ByteStringBuffer.prototype.getSignedInt = function(n) { + var x = this.getInt(n); + var max = 2 << n - 2; + if (x >= max) { + x -= max << 1; + } + return x; + }; + util.ByteStringBuffer.prototype.getBytes = function(count) { + var rval; + if (count) { + count = Math.min(this.length(), count); + rval = this.data.slice(this.read, this.read + count); + this.read += count; + } else if (count === 0) { + rval = ""; + } else { + rval = this.read === 0 ? this.data : this.data.slice(this.read); + this.clear(); + } + return rval; + }; + util.ByteStringBuffer.prototype.bytes = function(count) { + return typeof count === "undefined" ? this.data.slice(this.read) : this.data.slice(this.read, this.read + count); + }; + util.ByteStringBuffer.prototype.at = function(i) { + return this.data.charCodeAt(this.read + i); + }; + util.ByteStringBuffer.prototype.setAt = function(i, b) { + this.data = this.data.substr(0, this.read + i) + String.fromCharCode(b) + this.data.substr(this.read + i + 1); + return this; + }; + util.ByteStringBuffer.prototype.last = function() { + return this.data.charCodeAt(this.data.length - 1); + }; + util.ByteStringBuffer.prototype.copy = function() { + var c = util.createBuffer(this.data); + c.read = this.read; + return c; + }; + util.ByteStringBuffer.prototype.compact = function() { + if (this.read > 0) { + this.data = this.data.slice(this.read); + this.read = 0; + } + return this; + }; + util.ByteStringBuffer.prototype.clear = function() { + this.data = ""; + this.read = 0; + return this; + }; + util.ByteStringBuffer.prototype.truncate = function(count) { + var len = Math.max(0, this.length() - count); + this.data = this.data.substr(this.read, len); + this.read = 0; + return this; + }; + util.ByteStringBuffer.prototype.toHex = function() { + var rval = ""; + for (var i = this.read; i < this.data.length; ++i) { + var b = this.data.charCodeAt(i); + if (b < 16) { + rval += "0"; + } + rval += b.toString(16); + } + return rval; + }; + util.ByteStringBuffer.prototype.toString = function() { + return util.decodeUtf8(this.bytes()); + }; + function DataBuffer(b, options) { + options = options || {}; + this.read = options.readOffset || 0; + this.growSize = options.growSize || 1024; + var isArrayBuffer = util.isArrayBuffer(b); + var isArrayBufferView = util.isArrayBufferView(b); + if (isArrayBuffer || isArrayBufferView) { + if (isArrayBuffer) { + this.data = new DataView(b); + } else { + this.data = new DataView(b.buffer, b.byteOffset, b.byteLength); + } + this.write = "writeOffset" in options ? options.writeOffset : this.data.byteLength; + return; + } + this.data = new DataView(new ArrayBuffer(0)); + this.write = 0; + if (b !== null && b !== void 0) { + this.putBytes(b); + } + if ("writeOffset" in options) { + this.write = options.writeOffset; + } + } + util.DataBuffer = DataBuffer; + util.DataBuffer.prototype.length = function() { + return this.write - this.read; + }; + util.DataBuffer.prototype.isEmpty = function() { + return this.length() <= 0; + }; + util.DataBuffer.prototype.accommodate = function(amount, growSize) { + if (this.length() >= amount) { + return this; + } + growSize = Math.max(growSize || this.growSize, amount); + var src = new Uint8Array( + this.data.buffer, + this.data.byteOffset, + this.data.byteLength + ); + var dst = new Uint8Array(this.length() + growSize); + dst.set(src); + this.data = new DataView(dst.buffer); + return this; + }; + util.DataBuffer.prototype.putByte = function(b) { + this.accommodate(1); + this.data.setUint8(this.write++, b); + return this; + }; + util.DataBuffer.prototype.fillWithByte = function(b, n) { + this.accommodate(n); + for (var i = 0; i < n; ++i) { + this.data.setUint8(b); + } + return this; + }; + util.DataBuffer.prototype.putBytes = function(bytes, encoding) { + if (util.isArrayBufferView(bytes)) { + var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength); + var len = src.byteLength - src.byteOffset; + this.accommodate(len); + var dst = new Uint8Array(this.data.buffer, this.write); + dst.set(src); + this.write += len; + return this; + } + if (util.isArrayBuffer(bytes)) { + var src = new Uint8Array(bytes); + this.accommodate(src.byteLength); + var dst = new Uint8Array(this.data.buffer); + dst.set(src, this.write); + this.write += src.byteLength; + return this; + } + if (bytes instanceof util.DataBuffer || typeof bytes === "object" && typeof bytes.read === "number" && typeof bytes.write === "number" && util.isArrayBufferView(bytes.data)) { + var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length()); + this.accommodate(src.byteLength); + var dst = new Uint8Array(bytes.data.byteLength, this.write); + dst.set(src); + this.write += src.byteLength; + return this; + } + if (bytes instanceof util.ByteStringBuffer) { + bytes = bytes.data; + encoding = "binary"; + } + encoding = encoding || "binary"; + if (typeof bytes === "string") { + var view; + if (encoding === "hex") { + this.accommodate(Math.ceil(bytes.length / 2)); + view = new Uint8Array(this.data.buffer, this.write); + this.write += util.binary.hex.decode(bytes, view, this.write); + return this; + } + if (encoding === "base64") { + this.accommodate(Math.ceil(bytes.length / 4) * 3); + view = new Uint8Array(this.data.buffer, this.write); + this.write += util.binary.base64.decode(bytes, view, this.write); + return this; + } + if (encoding === "utf8") { + bytes = util.encodeUtf8(bytes); + encoding = "binary"; + } + if (encoding === "binary" || encoding === "raw") { + this.accommodate(bytes.length); + view = new Uint8Array(this.data.buffer, this.write); + this.write += util.binary.raw.decode(view); + return this; + } + if (encoding === "utf16") { + this.accommodate(bytes.length * 2); + view = new Uint16Array(this.data.buffer, this.write); + this.write += util.text.utf16.encode(view); + return this; + } + throw new Error("Invalid encoding: " + encoding); + } + throw Error("Invalid parameter: " + bytes); + }; + util.DataBuffer.prototype.putBuffer = function(buffer) { + this.putBytes(buffer); + buffer.clear(); + return this; + }; + util.DataBuffer.prototype.putString = function(str) { + return this.putBytes(str, "utf16"); + }; + util.DataBuffer.prototype.putInt16 = function(i) { + this.accommodate(2); + this.data.setInt16(this.write, i); + this.write += 2; + return this; + }; + util.DataBuffer.prototype.putInt24 = function(i) { + this.accommodate(3); + this.data.setInt16(this.write, i >> 8 & 65535); + this.data.setInt8(this.write, i >> 16 & 255); + this.write += 3; + return this; + }; + util.DataBuffer.prototype.putInt32 = function(i) { + this.accommodate(4); + this.data.setInt32(this.write, i); + this.write += 4; + return this; + }; + util.DataBuffer.prototype.putInt16Le = function(i) { + this.accommodate(2); + this.data.setInt16(this.write, i, true); + this.write += 2; + return this; + }; + util.DataBuffer.prototype.putInt24Le = function(i) { + this.accommodate(3); + this.data.setInt8(this.write, i >> 16 & 255); + this.data.setInt16(this.write, i >> 8 & 65535, true); + this.write += 3; + return this; + }; + util.DataBuffer.prototype.putInt32Le = function(i) { + this.accommodate(4); + this.data.setInt32(this.write, i, true); + this.write += 4; + return this; + }; + util.DataBuffer.prototype.putInt = function(i, n) { + _checkBitsParam(n); + this.accommodate(n / 8); + do { + n -= 8; + this.data.setInt8(this.write++, i >> n & 255); + } while (n > 0); + return this; + }; + util.DataBuffer.prototype.putSignedInt = function(i, n) { + _checkBitsParam(n); + this.accommodate(n / 8); + if (i < 0) { + i += 2 << n - 1; + } + return this.putInt(i, n); + }; + util.DataBuffer.prototype.getByte = function() { + return this.data.getInt8(this.read++); + }; + util.DataBuffer.prototype.getInt16 = function() { + var rval = this.data.getInt16(this.read); + this.read += 2; + return rval; + }; + util.DataBuffer.prototype.getInt24 = function() { + var rval = this.data.getInt16(this.read) << 8 ^ this.data.getInt8(this.read + 2); + this.read += 3; + return rval; + }; + util.DataBuffer.prototype.getInt32 = function() { + var rval = this.data.getInt32(this.read); + this.read += 4; + return rval; + }; + util.DataBuffer.prototype.getInt16Le = function() { + var rval = this.data.getInt16(this.read, true); + this.read += 2; + return rval; + }; + util.DataBuffer.prototype.getInt24Le = function() { + var rval = this.data.getInt8(this.read) ^ this.data.getInt16(this.read + 1, true) << 8; + this.read += 3; + return rval; + }; + util.DataBuffer.prototype.getInt32Le = function() { + var rval = this.data.getInt32(this.read, true); + this.read += 4; + return rval; + }; + util.DataBuffer.prototype.getInt = function(n) { + _checkBitsParam(n); + var rval = 0; + do { + rval = (rval << 8) + this.data.getInt8(this.read++); + n -= 8; + } while (n > 0); + return rval; + }; + util.DataBuffer.prototype.getSignedInt = function(n) { + var x = this.getInt(n); + var max = 2 << n - 2; + if (x >= max) { + x -= max << 1; + } + return x; + }; + util.DataBuffer.prototype.getBytes = function(count) { + var rval; + if (count) { + count = Math.min(this.length(), count); + rval = this.data.slice(this.read, this.read + count); + this.read += count; + } else if (count === 0) { + rval = ""; + } else { + rval = this.read === 0 ? this.data : this.data.slice(this.read); + this.clear(); + } + return rval; + }; + util.DataBuffer.prototype.bytes = function(count) { + return typeof count === "undefined" ? this.data.slice(this.read) : this.data.slice(this.read, this.read + count); + }; + util.DataBuffer.prototype.at = function(i) { + return this.data.getUint8(this.read + i); + }; + util.DataBuffer.prototype.setAt = function(i, b) { + this.data.setUint8(i, b); + return this; + }; + util.DataBuffer.prototype.last = function() { + return this.data.getUint8(this.write - 1); + }; + util.DataBuffer.prototype.copy = function() { + return new util.DataBuffer(this); + }; + util.DataBuffer.prototype.compact = function() { + if (this.read > 0) { + var src = new Uint8Array(this.data.buffer, this.read); + var dst = new Uint8Array(src.byteLength); + dst.set(src); + this.data = new DataView(dst); + this.write -= this.read; + this.read = 0; + } + return this; + }; + util.DataBuffer.prototype.clear = function() { + this.data = new DataView(new ArrayBuffer(0)); + this.read = this.write = 0; + return this; + }; + util.DataBuffer.prototype.truncate = function(count) { + this.write = Math.max(0, this.length() - count); + this.read = Math.min(this.read, this.write); + return this; + }; + util.DataBuffer.prototype.toHex = function() { + var rval = ""; + for (var i = this.read; i < this.data.byteLength; ++i) { + var b = this.data.getUint8(i); + if (b < 16) { + rval += "0"; + } + rval += b.toString(16); + } + return rval; + }; + util.DataBuffer.prototype.toString = function(encoding) { + var view = new Uint8Array(this.data, this.read, this.length()); + encoding = encoding || "utf8"; + if (encoding === "binary" || encoding === "raw") { + return util.binary.raw.encode(view); + } + if (encoding === "hex") { + return util.binary.hex.encode(view); + } + if (encoding === "base64") { + return util.binary.base64.encode(view); + } + if (encoding === "utf8") { + return util.text.utf8.decode(view); + } + if (encoding === "utf16") { + return util.text.utf16.decode(view); + } + throw new Error("Invalid encoding: " + encoding); + }; + util.createBuffer = function(input, encoding) { + encoding = encoding || "raw"; + if (input !== void 0 && encoding === "utf8") { + input = util.encodeUtf8(input); + } + return new util.ByteBuffer(input); + }; + util.fillString = function(c, n) { + var s = ""; + while (n > 0) { + if (n & 1) { + s += c; + } + n >>>= 1; + if (n > 0) { + c += c; + } + } + return s; + }; + util.xorBytes = function(s1, s2, n) { + var s3 = ""; + var b = ""; + var t = ""; + var i = 0; + var c = 0; + for (; n > 0; --n, ++i) { + b = s1.charCodeAt(i) ^ s2.charCodeAt(i); + if (c >= 10) { + s3 += t; + t = ""; + c = 0; + } + t += String.fromCharCode(b); + ++c; + } + s3 += t; + return s3; + }; + util.hexToBytes = function(hex) { + var rval = ""; + var i = 0; + if (hex.length & true) { + i = 1; + rval += String.fromCharCode(parseInt(hex[0], 16)); + } + for (; i < hex.length; i += 2) { + rval += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); + } + return rval; + }; + util.bytesToHex = function(bytes) { + return util.createBuffer(bytes).toHex(); + }; + util.int32ToBytes = function(i) { + return String.fromCharCode(i >> 24 & 255) + String.fromCharCode(i >> 16 & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i & 255); + }; + var _base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + var _base64Idx = [ + /*43 -43 = 0*/ + /*'+', 1, 2, 3,'/' */ + 62, + -1, + -1, + -1, + 63, + /*'0','1','2','3','4','5','6','7','8','9' */ + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59, + 60, + 61, + /*15, 16, 17,'=', 19, 20, 21 */ + -1, + -1, + -1, + 64, + -1, + -1, + -1, + /*65 - 43 = 22*/ + /*'A','B','C','D','E','F','G','H','I','J','K','L','M', */ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + /*'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */ + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + /*91 - 43 = 48 */ + /*48, 49, 50, 51, 52, 53 */ + -1, + -1, + -1, + -1, + -1, + -1, + /*97 - 43 = 54*/ + /*'a','b','c','d','e','f','g','h','i','j','k','l','m' */ + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + /*'n','o','p','q','r','s','t','u','v','w','x','y','z' */ + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + 51 + ]; + var _base58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; + util.encode64 = function(input, maxline) { + var line = ""; + var output = ""; + var chr1, chr2, chr3; + var i = 0; + while (i < input.length) { + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + line += _base64.charAt(chr1 >> 2); + line += _base64.charAt((chr1 & 3) << 4 | chr2 >> 4); + if (isNaN(chr2)) { + line += "=="; + } else { + line += _base64.charAt((chr2 & 15) << 2 | chr3 >> 6); + line += isNaN(chr3) ? "=" : _base64.charAt(chr3 & 63); + } + if (maxline && line.length > maxline) { + output += line.substr(0, maxline) + "\r\n"; + line = line.substr(maxline); + } + } + output += line; + return output; + }; + util.decode64 = function(input) { + input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); + var output = ""; + var enc1, enc2, enc3, enc4; + var i = 0; + while (i < input.length) { + enc1 = _base64Idx[input.charCodeAt(i++) - 43]; + enc2 = _base64Idx[input.charCodeAt(i++) - 43]; + enc3 = _base64Idx[input.charCodeAt(i++) - 43]; + enc4 = _base64Idx[input.charCodeAt(i++) - 43]; + output += String.fromCharCode(enc1 << 2 | enc2 >> 4); + if (enc3 !== 64) { + output += String.fromCharCode((enc2 & 15) << 4 | enc3 >> 2); + if (enc4 !== 64) { + output += String.fromCharCode((enc3 & 3) << 6 | enc4); + } + } + } + return output; + }; + util.encodeUtf8 = function(str) { + return unescape(encodeURIComponent(str)); + }; + util.decodeUtf8 = function(str) { + return decodeURIComponent(escape(str)); + }; + util.binary = { + raw: {}, + hex: {}, + base64: {}, + base58: {}, + baseN: { + encode: baseN.encode, + decode: baseN.decode + } + }; + util.binary.raw.encode = function(bytes) { + return String.fromCharCode.apply(null, bytes); + }; + util.binary.raw.decode = function(str, output, offset) { + var out = output; + if (!out) { + out = new Uint8Array(str.length); + } + offset = offset || 0; + var j = offset; + for (var i = 0; i < str.length; ++i) { + out[j++] = str.charCodeAt(i); + } + return output ? j - offset : out; + }; + util.binary.hex.encode = util.bytesToHex; + util.binary.hex.decode = function(hex, output, offset) { + var out = output; + if (!out) { + out = new Uint8Array(Math.ceil(hex.length / 2)); + } + offset = offset || 0; + var i = 0, j = offset; + if (hex.length & 1) { + i = 1; + out[j++] = parseInt(hex[0], 16); + } + for (; i < hex.length; i += 2) { + out[j++] = parseInt(hex.substr(i, 2), 16); + } + return output ? j - offset : out; + }; + util.binary.base64.encode = function(input, maxline) { + var line = ""; + var output = ""; + var chr1, chr2, chr3; + var i = 0; + while (i < input.byteLength) { + chr1 = input[i++]; + chr2 = input[i++]; + chr3 = input[i++]; + line += _base64.charAt(chr1 >> 2); + line += _base64.charAt((chr1 & 3) << 4 | chr2 >> 4); + if (isNaN(chr2)) { + line += "=="; + } else { + line += _base64.charAt((chr2 & 15) << 2 | chr3 >> 6); + line += isNaN(chr3) ? "=" : _base64.charAt(chr3 & 63); + } + if (maxline && line.length > maxline) { + output += line.substr(0, maxline) + "\r\n"; + line = line.substr(maxline); + } + } + output += line; + return output; + }; + util.binary.base64.decode = function(input, output, offset) { + var out = output; + if (!out) { + out = new Uint8Array(Math.ceil(input.length / 4) * 3); + } + input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); + offset = offset || 0; + var enc1, enc2, enc3, enc4; + var i = 0, j = offset; + while (i < input.length) { + enc1 = _base64Idx[input.charCodeAt(i++) - 43]; + enc2 = _base64Idx[input.charCodeAt(i++) - 43]; + enc3 = _base64Idx[input.charCodeAt(i++) - 43]; + enc4 = _base64Idx[input.charCodeAt(i++) - 43]; + out[j++] = enc1 << 2 | enc2 >> 4; + if (enc3 !== 64) { + out[j++] = (enc2 & 15) << 4 | enc3 >> 2; + if (enc4 !== 64) { + out[j++] = (enc3 & 3) << 6 | enc4; + } + } + } + return output ? j - offset : out.subarray(0, j); + }; + util.binary.base58.encode = function(input, maxline) { + return util.binary.baseN.encode(input, _base58, maxline); + }; + util.binary.base58.decode = function(input, maxline) { + return util.binary.baseN.decode(input, _base58, maxline); + }; + util.text = { + utf8: {}, + utf16: {} + }; + util.text.utf8.encode = function(str, output, offset) { + str = util.encodeUtf8(str); + var out = output; + if (!out) { + out = new Uint8Array(str.length); + } + offset = offset || 0; + var j = offset; + for (var i = 0; i < str.length; ++i) { + out[j++] = str.charCodeAt(i); + } + return output ? j - offset : out; + }; + util.text.utf8.decode = function(bytes) { + return util.decodeUtf8(String.fromCharCode.apply(null, bytes)); + }; + util.text.utf16.encode = function(str, output, offset) { + var out = output; + if (!out) { + out = new Uint8Array(str.length * 2); + } + var view = new Uint16Array(out.buffer); + offset = offset || 0; + var j = offset; + var k = offset; + for (var i = 0; i < str.length; ++i) { + view[k++] = str.charCodeAt(i); + j += 2; + } + return output ? j - offset : out; + }; + util.text.utf16.decode = function(bytes) { + return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer)); + }; + util.deflate = function(api, bytes, raw) { + bytes = util.decode64(api.deflate(util.encode64(bytes)).rval); + if (raw) { + var start = 2; + var flg = bytes.charCodeAt(1); + if (flg & 32) { + start = 6; + } + bytes = bytes.substring(start, bytes.length - 4); + } + return bytes; + }; + util.inflate = function(api, bytes, raw) { + var rval = api.inflate(util.encode64(bytes)).rval; + return rval === null ? null : util.decode64(rval); + }; + var _setStorageObject = function(api, id, obj) { + if (!api) { + throw new Error("WebStorage not available."); + } + var rval; + if (obj === null) { + rval = api.removeItem(id); + } else { + obj = util.encode64(JSON.stringify(obj)); + rval = api.setItem(id, obj); + } + if (typeof rval !== "undefined" && rval.rval !== true) { + var error2 = new Error(rval.error.message); + error2.id = rval.error.id; + error2.name = rval.error.name; + throw error2; + } + }; + var _getStorageObject = function(api, id) { + if (!api) { + throw new Error("WebStorage not available."); + } + var rval = api.getItem(id); + if (api.init) { + if (rval.rval === null) { + if (rval.error) { + var error2 = new Error(rval.error.message); + error2.id = rval.error.id; + error2.name = rval.error.name; + throw error2; + } + rval = null; + } else { + rval = rval.rval; + } + } + if (rval !== null) { + rval = JSON.parse(util.decode64(rval)); + } + return rval; + }; + var _setItem = function(api, id, key, data) { + var obj = _getStorageObject(api, id); + if (obj === null) { + obj = {}; + } + obj[key] = data; + _setStorageObject(api, id, obj); + }; + var _getItem = function(api, id, key) { + var rval = _getStorageObject(api, id); + if (rval !== null) { + rval = key in rval ? rval[key] : null; + } + return rval; + }; + var _removeItem = function(api, id, key) { + var obj = _getStorageObject(api, id); + if (obj !== null && key in obj) { + delete obj[key]; + var empty = true; + for (var prop in obj) { + empty = false; + break; + } + if (empty) { + obj = null; + } + _setStorageObject(api, id, obj); + } + }; + var _clearItems = function(api, id) { + _setStorageObject(api, id, null); + }; + var _callStorageFunction = function(func, args, location) { + var rval = null; + if (typeof location === "undefined") { + location = ["web", "flash"]; + } + var type; + var done = false; + var exception = null; + for (var idx in location) { + type = location[idx]; + try { + if (type === "flash" || type === "both") { + if (args[0] === null) { + throw new Error("Flash local storage not available."); + } + rval = func.apply(this, args); + done = type === "flash"; + } + if (type === "web" || type === "both") { + args[0] = localStorage; + rval = func.apply(this, args); + done = true; + } + } catch (ex) { + exception = ex; + } + if (done) { + break; + } + } + if (!done) { + throw exception; + } + return rval; + }; + util.setItem = function(api, id, key, data, location) { + _callStorageFunction(_setItem, arguments, location); + }; + util.getItem = function(api, id, key, location) { + return _callStorageFunction(_getItem, arguments, location); + }; + util.removeItem = function(api, id, key, location) { + _callStorageFunction(_removeItem, arguments, location); + }; + util.clearItems = function(api, id, location) { + _callStorageFunction(_clearItems, arguments, location); + }; + util.isEmpty = function(obj) { + for (var prop in obj) { + if (obj.hasOwnProperty(prop)) { + return false; + } + } + return true; + }; + util.format = function(format) { + var re = /%./g; + var match; + var part; + var argi = 0; + var parts = []; + var last = 0; + while (match = re.exec(format)) { + part = format.substring(last, re.lastIndex - 2); + if (part.length > 0) { + parts.push(part); + } + last = re.lastIndex; + var code = match[0][1]; + switch (code) { + case "s": + case "o": + if (argi < arguments.length) { + parts.push(arguments[argi++ + 1]); + } else { + parts.push(""); + } + break; + // FIXME: do proper formatting for numbers, etc + //case 'f': + //case 'd': + case "%": + parts.push("%"); + break; + default: + parts.push("<%" + code + "?>"); + } + } + parts.push(format.substring(last)); + return parts.join(""); + }; + util.formatNumber = function(number, decimals, dec_point, thousands_sep) { + var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals; + var d = dec_point === void 0 ? "," : dec_point; + var t = thousands_sep === void 0 ? "." : thousands_sep, s = n < 0 ? "-" : ""; + var i = parseInt(n = Math.abs(+n || 0).toFixed(c), 10) + ""; + var j = i.length > 3 ? i.length % 3 : 0; + return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); + }; + util.formatSize = function(size) { + if (size >= 1073741824) { + size = util.formatNumber(size / 1073741824, 2, ".", "") + " GiB"; + } else if (size >= 1048576) { + size = util.formatNumber(size / 1048576, 2, ".", "") + " MiB"; + } else if (size >= 1024) { + size = util.formatNumber(size / 1024, 0) + " KiB"; + } else { + size = util.formatNumber(size, 0) + " bytes"; + } + return size; + }; + util.bytesFromIP = function(ip) { + if (ip.indexOf(".") !== -1) { + return util.bytesFromIPv4(ip); + } + if (ip.indexOf(":") !== -1) { + return util.bytesFromIPv6(ip); + } + return null; + }; + util.bytesFromIPv4 = function(ip) { + ip = ip.split("."); + if (ip.length !== 4) { + return null; + } + var b = util.createBuffer(); + for (var i = 0; i < ip.length; ++i) { + var num = parseInt(ip[i], 10); + if (isNaN(num)) { + return null; + } + b.putByte(num); + } + return b.getBytes(); + }; + util.bytesFromIPv6 = function(ip) { + var blanks = 0; + ip = ip.split(":").filter(function(e) { + if (e.length === 0) ++blanks; + return true; + }); + var zeros = (8 - ip.length + blanks) * 2; + var b = util.createBuffer(); + for (var i = 0; i < 8; ++i) { + if (!ip[i] || ip[i].length === 0) { + b.fillWithByte(0, zeros); + zeros = 0; + continue; + } + var bytes = util.hexToBytes(ip[i]); + if (bytes.length < 2) { + b.putByte(0); + } + b.putBytes(bytes); + } + return b.getBytes(); + }; + util.bytesToIP = function(bytes) { + if (bytes.length === 4) { + return util.bytesToIPv4(bytes); + } + if (bytes.length === 16) { + return util.bytesToIPv6(bytes); + } + return null; + }; + util.bytesToIPv4 = function(bytes) { + if (bytes.length !== 4) { + return null; + } + var ip = []; + for (var i = 0; i < bytes.length; ++i) { + ip.push(bytes.charCodeAt(i)); + } + return ip.join("."); + }; + util.bytesToIPv6 = function(bytes) { + if (bytes.length !== 16) { + return null; + } + var ip = []; + var zeroGroups = []; + var zeroMaxGroup = 0; + for (var i = 0; i < bytes.length; i += 2) { + var hex = util.bytesToHex(bytes[i] + bytes[i + 1]); + while (hex[0] === "0" && hex !== "0") { + hex = hex.substr(1); + } + if (hex === "0") { + var last = zeroGroups[zeroGroups.length - 1]; + var idx = ip.length; + if (!last || idx !== last.end + 1) { + zeroGroups.push({ start: idx, end: idx }); + } else { + last.end = idx; + if (last.end - last.start > zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start) { + zeroMaxGroup = zeroGroups.length - 1; + } + } + } + ip.push(hex); + } + if (zeroGroups.length > 0) { + var group = zeroGroups[zeroMaxGroup]; + if (group.end - group.start > 0) { + ip.splice(group.start, group.end - group.start + 1, ""); + if (group.start === 0) { + ip.unshift(""); + } + if (group.end === 7) { + ip.push(""); + } + } + } + return ip.join(":"); + }; + util.estimateCores = function(options, callback) { + if (typeof options === "function") { + callback = options; + options = {}; + } + options = options || {}; + if ("cores" in util && !options.update) { + return callback(null, util.cores); + } + if (typeof navigator !== "undefined" && "hardwareConcurrency" in navigator && navigator.hardwareConcurrency > 0) { + util.cores = navigator.hardwareConcurrency; + return callback(null, util.cores); + } + if (typeof Worker === "undefined") { + util.cores = 1; + return callback(null, util.cores); + } + if (typeof Blob === "undefined") { + util.cores = 2; + return callback(null, util.cores); + } + var blobUrl = URL.createObjectURL(new Blob([ + "(", + function() { + self.addEventListener("message", function(e) { + var st = Date.now(); + var et = st + 4; + while (Date.now() < et) ; + self.postMessage({ st, et }); + }); + }.toString(), + ")()" + ], { type: "application/javascript" })); + sample([], 5, 16); + function sample(max, samples, numWorkers) { + if (samples === 0) { + var avg = Math.floor(max.reduce(function(avg2, x) { + return avg2 + x; + }, 0) / max.length); + util.cores = Math.max(1, avg); + URL.revokeObjectURL(blobUrl); + return callback(null, util.cores); + } + map(numWorkers, function(err, results) { + max.push(reduce(numWorkers, results)); + sample(max, samples - 1, numWorkers); + }); + } + function map(numWorkers, callback2) { + var workers = []; + var results = []; + for (var i = 0; i < numWorkers; ++i) { + var worker = new Worker(blobUrl); + worker.addEventListener("message", function(e) { + results.push(e.data); + if (results.length === numWorkers) { + for (var i2 = 0; i2 < numWorkers; ++i2) { + workers[i2].terminate(); + } + callback2(null, results); + } + }); + workers.push(worker); + } + for (var i = 0; i < numWorkers; ++i) { + workers[i].postMessage(i); + } + } + function reduce(numWorkers, results) { + var overlaps = []; + for (var n = 0; n < numWorkers; ++n) { + var r1 = results[n]; + var overlap = overlaps[n] = []; + for (var i = 0; i < numWorkers; ++i) { + if (n === i) { + continue; + } + var r2 = results[i]; + if (r1.st > r2.st && r1.st < r2.et || r2.st > r1.st && r2.st < r1.et) { + overlap.push(i); + } + } + } + return overlaps.reduce(function(max, overlap2) { + return Math.max(max, overlap2.length); + }, 0); + } + }; + } +}); + +// node_modules/node-forge/lib/cipher.js +var require_cipher = __commonJS({ + "node_modules/node-forge/lib/cipher.js"(exports2, module2) { + var forge = require_forge(); + require_util13(); + module2.exports = forge.cipher = forge.cipher || {}; + forge.cipher.algorithms = forge.cipher.algorithms || {}; + forge.cipher.createCipher = function(algorithm, key) { + var api = algorithm; + if (typeof api === "string") { + api = forge.cipher.getAlgorithm(api); + if (api) { + api = api(); + } + } + if (!api) { + throw new Error("Unsupported algorithm: " + algorithm); + } + return new forge.cipher.BlockCipher({ + algorithm: api, + key, + decrypt: false + }); + }; + forge.cipher.createDecipher = function(algorithm, key) { + var api = algorithm; + if (typeof api === "string") { + api = forge.cipher.getAlgorithm(api); + if (api) { + api = api(); + } + } + if (!api) { + throw new Error("Unsupported algorithm: " + algorithm); + } + return new forge.cipher.BlockCipher({ + algorithm: api, + key, + decrypt: true + }); + }; + forge.cipher.registerAlgorithm = function(name, algorithm) { + name = name.toUpperCase(); + forge.cipher.algorithms[name] = algorithm; + }; + forge.cipher.getAlgorithm = function(name) { + name = name.toUpperCase(); + if (name in forge.cipher.algorithms) { + return forge.cipher.algorithms[name]; + } + return null; + }; + var BlockCipher = forge.cipher.BlockCipher = function(options) { + this.algorithm = options.algorithm; + this.mode = this.algorithm.mode; + this.blockSize = this.mode.blockSize; + this._finish = false; + this._input = null; + this.output = null; + this._op = options.decrypt ? this.mode.decrypt : this.mode.encrypt; + this._decrypt = options.decrypt; + this.algorithm.initialize(options); + }; + BlockCipher.prototype.start = function(options) { + options = options || {}; + var opts = {}; + for (var key in options) { + opts[key] = options[key]; + } + opts.decrypt = this._decrypt; + this._finish = false; + this._input = forge.util.createBuffer(); + this.output = options.output || forge.util.createBuffer(); + this.mode.start(opts); + }; + BlockCipher.prototype.update = function(input) { + if (input) { + this._input.putBuffer(input); + } + while (!this._op.call(this.mode, this._input, this.output, this._finish) && !this._finish) { + } + this._input.compact(); + }; + BlockCipher.prototype.finish = function(pad) { + if (pad && (this.mode.name === "ECB" || this.mode.name === "CBC")) { + this.mode.pad = function(input) { + return pad(this.blockSize, input, false); + }; + this.mode.unpad = function(output) { + return pad(this.blockSize, output, true); + }; + } + var options = {}; + options.decrypt = this._decrypt; + options.overflow = this._input.length() % this.blockSize; + if (!this._decrypt && this.mode.pad) { + if (!this.mode.pad(this._input, options)) { + return false; + } + } + this._finish = true; + this.update(); + if (this._decrypt && this.mode.unpad) { + if (!this.mode.unpad(this.output, options)) { + return false; + } + } + if (this.mode.afterFinish) { + if (!this.mode.afterFinish(this.output, options)) { + return false; + } + } + return true; + }; + } +}); + +// node_modules/node-forge/lib/cipherModes.js +var require_cipherModes = __commonJS({ + "node_modules/node-forge/lib/cipherModes.js"(exports2, module2) { + var forge = require_forge(); + require_util13(); + forge.cipher = forge.cipher || {}; + var modes = module2.exports = forge.cipher.modes = forge.cipher.modes || {}; + modes.ecb = function(options) { + options = options || {}; + this.name = "ECB"; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = new Array(this._ints); + this._outBlock = new Array(this._ints); + }; + modes.ecb.prototype.start = function(options) { + }; + modes.ecb.prototype.encrypt = function(input, output, finish) { + if (input.length() < this.blockSize && !(finish && input.length() > 0)) { + return true; + } + for (var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32(); + } + this.cipher.encrypt(this._inBlock, this._outBlock); + for (var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i]); + } + }; + modes.ecb.prototype.decrypt = function(input, output, finish) { + if (input.length() < this.blockSize && !(finish && input.length() > 0)) { + return true; + } + for (var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32(); + } + this.cipher.decrypt(this._inBlock, this._outBlock); + for (var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i]); + } + }; + modes.ecb.prototype.pad = function(input, options) { + var padding = input.length() === this.blockSize ? this.blockSize : this.blockSize - input.length(); + input.fillWithByte(padding, padding); + return true; + }; + modes.ecb.prototype.unpad = function(output, options) { + if (options.overflow > 0) { + return false; + } + var len = output.length(); + var count = output.at(len - 1); + if (count > this.blockSize << 2) { + return false; + } + output.truncate(count); + return true; + }; + modes.cbc = function(options) { + options = options || {}; + this.name = "CBC"; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = new Array(this._ints); + this._outBlock = new Array(this._ints); + }; + modes.cbc.prototype.start = function(options) { + if (options.iv === null) { + if (!this._prev) { + throw new Error("Invalid IV parameter."); + } + this._iv = this._prev.slice(0); + } else if (!("iv" in options)) { + throw new Error("Invalid IV parameter."); + } else { + this._iv = transformIV(options.iv, this.blockSize); + this._prev = this._iv.slice(0); + } + }; + modes.cbc.prototype.encrypt = function(input, output, finish) { + if (input.length() < this.blockSize && !(finish && input.length() > 0)) { + return true; + } + for (var i = 0; i < this._ints; ++i) { + this._inBlock[i] = this._prev[i] ^ input.getInt32(); + } + this.cipher.encrypt(this._inBlock, this._outBlock); + for (var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i]); + } + this._prev = this._outBlock; + }; + modes.cbc.prototype.decrypt = function(input, output, finish) { + if (input.length() < this.blockSize && !(finish && input.length() > 0)) { + return true; + } + for (var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32(); + } + this.cipher.decrypt(this._inBlock, this._outBlock); + for (var i = 0; i < this._ints; ++i) { + output.putInt32(this._prev[i] ^ this._outBlock[i]); + } + this._prev = this._inBlock.slice(0); + }; + modes.cbc.prototype.pad = function(input, options) { + var padding = input.length() === this.blockSize ? this.blockSize : this.blockSize - input.length(); + input.fillWithByte(padding, padding); + return true; + }; + modes.cbc.prototype.unpad = function(output, options) { + if (options.overflow > 0) { + return false; + } + var len = output.length(); + var count = output.at(len - 1); + if (count > this.blockSize << 2) { + return false; + } + output.truncate(count); + return true; + }; + modes.cfb = function(options) { + options = options || {}; + this.name = "CFB"; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = null; + this._outBlock = new Array(this._ints); + this._partialBlock = new Array(this._ints); + this._partialOutput = forge.util.createBuffer(); + this._partialBytes = 0; + }; + modes.cfb.prototype.start = function(options) { + if (!("iv" in options)) { + throw new Error("Invalid IV parameter."); + } + this._iv = transformIV(options.iv, this.blockSize); + this._inBlock = this._iv.slice(0); + this._partialBytes = 0; + }; + modes.cfb.prototype.encrypt = function(input, output, finish) { + var inputLength = input.length(); + if (inputLength === 0) { + return true; + } + this.cipher.encrypt(this._inBlock, this._outBlock); + if (this._partialBytes === 0 && inputLength >= this.blockSize) { + for (var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32() ^ this._outBlock[i]; + output.putInt32(this._inBlock[i]); + } + return; + } + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if (partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + this._partialOutput.clear(); + for (var i = 0; i < this._ints; ++i) { + this._partialBlock[i] = input.getInt32() ^ this._outBlock[i]; + this._partialOutput.putInt32(this._partialBlock[i]); + } + if (partialBytes > 0) { + input.read -= this.blockSize; + } else { + for (var i = 0; i < this._ints; ++i) { + this._inBlock[i] = this._partialBlock[i]; + } + } + if (this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + if (partialBytes > 0 && !finish) { + output.putBytes(this._partialOutput.getBytes( + partialBytes - this._partialBytes + )); + this._partialBytes = partialBytes; + return true; + } + output.putBytes(this._partialOutput.getBytes( + inputLength - this._partialBytes + )); + this._partialBytes = 0; + }; + modes.cfb.prototype.decrypt = function(input, output, finish) { + var inputLength = input.length(); + if (inputLength === 0) { + return true; + } + this.cipher.encrypt(this._inBlock, this._outBlock); + if (this._partialBytes === 0 && inputLength >= this.blockSize) { + for (var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32(); + output.putInt32(this._inBlock[i] ^ this._outBlock[i]); + } + return; + } + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if (partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + this._partialOutput.clear(); + for (var i = 0; i < this._ints; ++i) { + this._partialBlock[i] = input.getInt32(); + this._partialOutput.putInt32(this._partialBlock[i] ^ this._outBlock[i]); + } + if (partialBytes > 0) { + input.read -= this.blockSize; + } else { + for (var i = 0; i < this._ints; ++i) { + this._inBlock[i] = this._partialBlock[i]; + } + } + if (this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + if (partialBytes > 0 && !finish) { + output.putBytes(this._partialOutput.getBytes( + partialBytes - this._partialBytes + )); + this._partialBytes = partialBytes; + return true; + } + output.putBytes(this._partialOutput.getBytes( + inputLength - this._partialBytes + )); + this._partialBytes = 0; + }; + modes.ofb = function(options) { + options = options || {}; + this.name = "OFB"; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = null; + this._outBlock = new Array(this._ints); + this._partialOutput = forge.util.createBuffer(); + this._partialBytes = 0; + }; + modes.ofb.prototype.start = function(options) { + if (!("iv" in options)) { + throw new Error("Invalid IV parameter."); + } + this._iv = transformIV(options.iv, this.blockSize); + this._inBlock = this._iv.slice(0); + this._partialBytes = 0; + }; + modes.ofb.prototype.encrypt = function(input, output, finish) { + var inputLength = input.length(); + if (input.length() === 0) { + return true; + } + this.cipher.encrypt(this._inBlock, this._outBlock); + if (this._partialBytes === 0 && inputLength >= this.blockSize) { + for (var i = 0; i < this._ints; ++i) { + output.putInt32(input.getInt32() ^ this._outBlock[i]); + this._inBlock[i] = this._outBlock[i]; + } + return; + } + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if (partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + this._partialOutput.clear(); + for (var i = 0; i < this._ints; ++i) { + this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); + } + if (partialBytes > 0) { + input.read -= this.blockSize; + } else { + for (var i = 0; i < this._ints; ++i) { + this._inBlock[i] = this._outBlock[i]; + } + } + if (this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + if (partialBytes > 0 && !finish) { + output.putBytes(this._partialOutput.getBytes( + partialBytes - this._partialBytes + )); + this._partialBytes = partialBytes; + return true; + } + output.putBytes(this._partialOutput.getBytes( + inputLength - this._partialBytes + )); + this._partialBytes = 0; + }; + modes.ofb.prototype.decrypt = modes.ofb.prototype.encrypt; + modes.ctr = function(options) { + options = options || {}; + this.name = "CTR"; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = null; + this._outBlock = new Array(this._ints); + this._partialOutput = forge.util.createBuffer(); + this._partialBytes = 0; + }; + modes.ctr.prototype.start = function(options) { + if (!("iv" in options)) { + throw new Error("Invalid IV parameter."); + } + this._iv = transformIV(options.iv, this.blockSize); + this._inBlock = this._iv.slice(0); + this._partialBytes = 0; + }; + modes.ctr.prototype.encrypt = function(input, output, finish) { + var inputLength = input.length(); + if (inputLength === 0) { + return true; + } + this.cipher.encrypt(this._inBlock, this._outBlock); + if (this._partialBytes === 0 && inputLength >= this.blockSize) { + for (var i = 0; i < this._ints; ++i) { + output.putInt32(input.getInt32() ^ this._outBlock[i]); + } + } else { + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if (partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + this._partialOutput.clear(); + for (var i = 0; i < this._ints; ++i) { + this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); + } + if (partialBytes > 0) { + input.read -= this.blockSize; + } + if (this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + if (partialBytes > 0 && !finish) { + output.putBytes(this._partialOutput.getBytes( + partialBytes - this._partialBytes + )); + this._partialBytes = partialBytes; + return true; + } + output.putBytes(this._partialOutput.getBytes( + inputLength - this._partialBytes + )); + this._partialBytes = 0; + } + inc32(this._inBlock); + }; + modes.ctr.prototype.decrypt = modes.ctr.prototype.encrypt; + modes.gcm = function(options) { + options = options || {}; + this.name = "GCM"; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = new Array(this._ints); + this._outBlock = new Array(this._ints); + this._partialOutput = forge.util.createBuffer(); + this._partialBytes = 0; + this._R = 3774873600; + }; + modes.gcm.prototype.start = function(options) { + if (!("iv" in options)) { + throw new Error("Invalid IV parameter."); + } + var iv = forge.util.createBuffer(options.iv); + this._cipherLength = 0; + var additionalData; + if ("additionalData" in options) { + additionalData = forge.util.createBuffer(options.additionalData); + } else { + additionalData = forge.util.createBuffer(); + } + if ("tagLength" in options) { + this._tagLength = options.tagLength; + } else { + this._tagLength = 128; + } + this._tag = null; + if (options.decrypt) { + this._tag = forge.util.createBuffer(options.tag).getBytes(); + if (this._tag.length !== this._tagLength / 8) { + throw new Error("Authentication tag does not match tag length."); + } + } + this._hashBlock = new Array(this._ints); + this.tag = null; + this._hashSubkey = new Array(this._ints); + this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey); + this.componentBits = 4; + this._m = this.generateHashTable(this._hashSubkey, this.componentBits); + var ivLength = iv.length(); + if (ivLength === 12) { + this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1]; + } else { + this._j0 = [0, 0, 0, 0]; + while (iv.length() > 0) { + this._j0 = this.ghash( + this._hashSubkey, + this._j0, + [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()] + ); + } + this._j0 = this.ghash( + this._hashSubkey, + this._j0, + [0, 0].concat(from64To32(ivLength * 8)) + ); + } + this._inBlock = this._j0.slice(0); + inc32(this._inBlock); + this._partialBytes = 0; + additionalData = forge.util.createBuffer(additionalData); + this._aDataLength = from64To32(additionalData.length() * 8); + var overflow = additionalData.length() % this.blockSize; + if (overflow) { + additionalData.fillWithByte(0, this.blockSize - overflow); + } + this._s = [0, 0, 0, 0]; + while (additionalData.length() > 0) { + this._s = this.ghash(this._hashSubkey, this._s, [ + additionalData.getInt32(), + additionalData.getInt32(), + additionalData.getInt32(), + additionalData.getInt32() + ]); + } + }; + modes.gcm.prototype.encrypt = function(input, output, finish) { + var inputLength = input.length(); + if (inputLength === 0) { + return true; + } + this.cipher.encrypt(this._inBlock, this._outBlock); + if (this._partialBytes === 0 && inputLength >= this.blockSize) { + for (var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i] ^= input.getInt32()); + } + this._cipherLength += this.blockSize; + } else { + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if (partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + this._partialOutput.clear(); + for (var i = 0; i < this._ints; ++i) { + this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); + } + if (partialBytes <= 0 || finish) { + if (finish) { + var overflow = inputLength % this.blockSize; + this._cipherLength += overflow; + this._partialOutput.truncate(this.blockSize - overflow); + } else { + this._cipherLength += this.blockSize; + } + for (var i = 0; i < this._ints; ++i) { + this._outBlock[i] = this._partialOutput.getInt32(); + } + this._partialOutput.read -= this.blockSize; + } + if (this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + if (partialBytes > 0 && !finish) { + input.read -= this.blockSize; + output.putBytes(this._partialOutput.getBytes( + partialBytes - this._partialBytes + )); + this._partialBytes = partialBytes; + return true; + } + output.putBytes(this._partialOutput.getBytes( + inputLength - this._partialBytes + )); + this._partialBytes = 0; + } + this._s = this.ghash(this._hashSubkey, this._s, this._outBlock); + inc32(this._inBlock); + }; + modes.gcm.prototype.decrypt = function(input, output, finish) { + var inputLength = input.length(); + if (inputLength < this.blockSize && !(finish && inputLength > 0)) { + return true; + } + this.cipher.encrypt(this._inBlock, this._outBlock); + inc32(this._inBlock); + this._hashBlock[0] = input.getInt32(); + this._hashBlock[1] = input.getInt32(); + this._hashBlock[2] = input.getInt32(); + this._hashBlock[3] = input.getInt32(); + this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock); + for (var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i] ^ this._hashBlock[i]); + } + if (inputLength < this.blockSize) { + this._cipherLength += inputLength % this.blockSize; + } else { + this._cipherLength += this.blockSize; + } + }; + modes.gcm.prototype.afterFinish = function(output, options) { + var rval = true; + if (options.decrypt && options.overflow) { + output.truncate(this.blockSize - options.overflow); + } + this.tag = forge.util.createBuffer(); + var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8)); + this._s = this.ghash(this._hashSubkey, this._s, lengths); + var tag = []; + this.cipher.encrypt(this._j0, tag); + for (var i = 0; i < this._ints; ++i) { + this.tag.putInt32(this._s[i] ^ tag[i]); + } + this.tag.truncate(this.tag.length() % (this._tagLength / 8)); + if (options.decrypt && this.tag.bytes() !== this._tag) { + rval = false; + } + return rval; + }; + modes.gcm.prototype.multiply = function(x, y) { + var z_i = [0, 0, 0, 0]; + var v_i = y.slice(0); + for (var i = 0; i < 128; ++i) { + var x_i = x[i / 32 | 0] & 1 << 31 - i % 32; + if (x_i) { + z_i[0] ^= v_i[0]; + z_i[1] ^= v_i[1]; + z_i[2] ^= v_i[2]; + z_i[3] ^= v_i[3]; + } + this.pow(v_i, v_i); + } + return z_i; + }; + modes.gcm.prototype.pow = function(x, out) { + var lsb = x[3] & 1; + for (var i = 3; i > 0; --i) { + out[i] = x[i] >>> 1 | (x[i - 1] & 1) << 31; + } + out[0] = x[0] >>> 1; + if (lsb) { + out[0] ^= this._R; + } + }; + modes.gcm.prototype.tableMultiply = function(x) { + var z = [0, 0, 0, 0]; + for (var i = 0; i < 32; ++i) { + var idx = i / 8 | 0; + var x_i = x[idx] >>> (7 - i % 8) * 4 & 15; + var ah = this._m[i][x_i]; + z[0] ^= ah[0]; + z[1] ^= ah[1]; + z[2] ^= ah[2]; + z[3] ^= ah[3]; + } + return z; + }; + modes.gcm.prototype.ghash = function(h, y, x) { + y[0] ^= x[0]; + y[1] ^= x[1]; + y[2] ^= x[2]; + y[3] ^= x[3]; + return this.tableMultiply(y); + }; + modes.gcm.prototype.generateHashTable = function(h, bits) { + var multiplier = 8 / bits; + var perInt = 4 * multiplier; + var size = 16 * multiplier; + var m = new Array(size); + for (var i = 0; i < size; ++i) { + var tmp = [0, 0, 0, 0]; + var idx = i / perInt | 0; + var shft = (perInt - 1 - i % perInt) * bits; + tmp[idx] = 1 << bits - 1 << shft; + m[i] = this.generateSubHashTable(this.multiply(tmp, h), bits); + } + return m; + }; + modes.gcm.prototype.generateSubHashTable = function(mid, bits) { + var size = 1 << bits; + var half = size >>> 1; + var m = new Array(size); + m[half] = mid.slice(0); + var i = half >>> 1; + while (i > 0) { + this.pow(m[2 * i], m[i] = []); + i >>= 1; + } + i = 2; + while (i < half) { + for (var j = 1; j < i; ++j) { + var m_i = m[i]; + var m_j = m[j]; + m[i + j] = [ + m_i[0] ^ m_j[0], + m_i[1] ^ m_j[1], + m_i[2] ^ m_j[2], + m_i[3] ^ m_j[3] + ]; + } + i *= 2; + } + m[0] = [0, 0, 0, 0]; + for (i = half + 1; i < size; ++i) { + var c = m[i ^ half]; + m[i] = [mid[0] ^ c[0], mid[1] ^ c[1], mid[2] ^ c[2], mid[3] ^ c[3]]; + } + return m; + }; + function transformIV(iv, blockSize) { + if (typeof iv === "string") { + iv = forge.util.createBuffer(iv); + } + if (forge.util.isArray(iv) && iv.length > 4) { + var tmp = iv; + iv = forge.util.createBuffer(); + for (var i = 0; i < tmp.length; ++i) { + iv.putByte(tmp[i]); + } + } + if (iv.length() < blockSize) { + throw new Error( + "Invalid IV length; got " + iv.length() + " bytes and expected " + blockSize + " bytes." + ); + } + if (!forge.util.isArray(iv)) { + var ints = []; + var blocks = blockSize / 4; + for (var i = 0; i < blocks; ++i) { + ints.push(iv.getInt32()); + } + iv = ints; + } + return iv; + } + function inc32(block) { + block[block.length - 1] = block[block.length - 1] + 1 & 4294967295; + } + function from64To32(num) { + return [num / 4294967296 | 0, num & 4294967295]; + } + } +}); + +// node_modules/node-forge/lib/aes.js +var require_aes = __commonJS({ + "node_modules/node-forge/lib/aes.js"(exports2, module2) { + var forge = require_forge(); + require_cipher(); + require_cipherModes(); + require_util13(); + module2.exports = forge.aes = forge.aes || {}; + forge.aes.startEncrypting = function(key, iv, output, mode) { + var cipher = _createCipher({ + key, + output, + decrypt: false, + mode + }); + cipher.start(iv); + return cipher; + }; + forge.aes.createEncryptionCipher = function(key, mode) { + return _createCipher({ + key, + output: null, + decrypt: false, + mode + }); + }; + forge.aes.startDecrypting = function(key, iv, output, mode) { + var cipher = _createCipher({ + key, + output, + decrypt: true, + mode + }); + cipher.start(iv); + return cipher; + }; + forge.aes.createDecryptionCipher = function(key, mode) { + return _createCipher({ + key, + output: null, + decrypt: true, + mode + }); + }; + forge.aes.Algorithm = function(name, mode) { + if (!init) { + initialize(); + } + var self2 = this; + self2.name = name; + self2.mode = new mode({ + blockSize: 16, + cipher: { + encrypt: function(inBlock, outBlock) { + return _updateBlock(self2._w, inBlock, outBlock, false); + }, + decrypt: function(inBlock, outBlock) { + return _updateBlock(self2._w, inBlock, outBlock, true); + } + } + }); + self2._init = false; + }; + forge.aes.Algorithm.prototype.initialize = function(options) { + if (this._init) { + return; + } + var key = options.key; + var tmp; + if (typeof key === "string" && (key.length === 16 || key.length === 24 || key.length === 32)) { + key = forge.util.createBuffer(key); + } else if (forge.util.isArray(key) && (key.length === 16 || key.length === 24 || key.length === 32)) { + tmp = key; + key = forge.util.createBuffer(); + for (var i = 0; i < tmp.length; ++i) { + key.putByte(tmp[i]); + } + } + if (!forge.util.isArray(key)) { + tmp = key; + key = []; + var len = tmp.length(); + if (len === 16 || len === 24 || len === 32) { + len = len >>> 2; + for (var i = 0; i < len; ++i) { + key.push(tmp.getInt32()); + } + } + } + if (!forge.util.isArray(key) || !(key.length === 4 || key.length === 6 || key.length === 8)) { + throw new Error("Invalid key parameter."); + } + var mode = this.mode.name; + var encryptOp = ["CFB", "OFB", "CTR", "GCM"].indexOf(mode) !== -1; + this._w = _expandKey(key, options.decrypt && !encryptOp); + this._init = true; + }; + forge.aes._expandKey = function(key, decrypt) { + if (!init) { + initialize(); + } + return _expandKey(key, decrypt); + }; + forge.aes._updateBlock = _updateBlock; + registerAlgorithm("AES-ECB", forge.cipher.modes.ecb); + registerAlgorithm("AES-CBC", forge.cipher.modes.cbc); + registerAlgorithm("AES-CFB", forge.cipher.modes.cfb); + registerAlgorithm("AES-OFB", forge.cipher.modes.ofb); + registerAlgorithm("AES-CTR", forge.cipher.modes.ctr); + registerAlgorithm("AES-GCM", forge.cipher.modes.gcm); + function registerAlgorithm(name, mode) { + var factory = function() { + return new forge.aes.Algorithm(name, mode); + }; + forge.cipher.registerAlgorithm(name, factory); + } + var init = false; + var Nb = 4; + var sbox; + var isbox; + var rcon; + var mix; + var imix; + function initialize() { + init = true; + rcon = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54]; + var xtime = new Array(256); + for (var i = 0; i < 128; ++i) { + xtime[i] = i << 1; + xtime[i + 128] = i + 128 << 1 ^ 283; + } + sbox = new Array(256); + isbox = new Array(256); + mix = new Array(4); + imix = new Array(4); + for (var i = 0; i < 4; ++i) { + mix[i] = new Array(256); + imix[i] = new Array(256); + } + var e = 0, ei = 0, e2, e4, e8, sx, sx2, me, ime; + for (var i = 0; i < 256; ++i) { + sx = ei ^ ei << 1 ^ ei << 2 ^ ei << 3 ^ ei << 4; + sx = sx >> 8 ^ sx & 255 ^ 99; + sbox[e] = sx; + isbox[sx] = e; + sx2 = xtime[sx]; + e2 = xtime[e]; + e4 = xtime[e2]; + e8 = xtime[e4]; + me = sx2 << 24 ^ // 2 + sx << 16 ^ // 1 + sx << 8 ^ // 1 + (sx ^ sx2); + ime = (e2 ^ e4 ^ e8) << 24 ^ // E (14) + (e ^ e8) << 16 ^ // 9 + (e ^ e4 ^ e8) << 8 ^ // D (13) + (e ^ e2 ^ e8); + for (var n = 0; n < 4; ++n) { + mix[n][e] = me; + imix[n][sx] = ime; + me = me << 24 | me >>> 8; + ime = ime << 24 | ime >>> 8; + } + if (e === 0) { + e = ei = 1; + } else { + e = e2 ^ xtime[xtime[xtime[e2 ^ e8]]]; + ei ^= xtime[xtime[ei]]; + } + } + } + function _expandKey(key, decrypt) { + var w = key.slice(0); + var temp, iNk = 1; + var Nk = w.length; + var Nr1 = Nk + 6 + 1; + var end = Nb * Nr1; + for (var i = Nk; i < end; ++i) { + temp = w[i - 1]; + if (i % Nk === 0) { + temp = sbox[temp >>> 16 & 255] << 24 ^ sbox[temp >>> 8 & 255] << 16 ^ sbox[temp & 255] << 8 ^ sbox[temp >>> 24] ^ rcon[iNk] << 24; + iNk++; + } else if (Nk > 6 && i % Nk === 4) { + temp = sbox[temp >>> 24] << 24 ^ sbox[temp >>> 16 & 255] << 16 ^ sbox[temp >>> 8 & 255] << 8 ^ sbox[temp & 255]; + } + w[i] = w[i - Nk] ^ temp; + } + if (decrypt) { + var tmp; + var m0 = imix[0]; + var m1 = imix[1]; + var m2 = imix[2]; + var m3 = imix[3]; + var wnew = w.slice(0); + end = w.length; + for (var i = 0, wi = end - Nb; i < end; i += Nb, wi -= Nb) { + if (i === 0 || i === end - Nb) { + wnew[i] = w[wi]; + wnew[i + 1] = w[wi + 3]; + wnew[i + 2] = w[wi + 2]; + wnew[i + 3] = w[wi + 1]; + } else { + for (var n = 0; n < Nb; ++n) { + tmp = w[wi + n]; + wnew[i + (3 & -n)] = m0[sbox[tmp >>> 24]] ^ m1[sbox[tmp >>> 16 & 255]] ^ m2[sbox[tmp >>> 8 & 255]] ^ m3[sbox[tmp & 255]]; + } + } + } + w = wnew; + } + return w; + } + function _updateBlock(w, input, output, decrypt) { + var Nr = w.length / 4 - 1; + var m0, m1, m2, m3, sub; + if (decrypt) { + m0 = imix[0]; + m1 = imix[1]; + m2 = imix[2]; + m3 = imix[3]; + sub = isbox; + } else { + m0 = mix[0]; + m1 = mix[1]; + m2 = mix[2]; + m3 = mix[3]; + sub = sbox; + } + var a, b, c, d, a2, b2, c2; + a = input[0] ^ w[0]; + b = input[decrypt ? 3 : 1] ^ w[1]; + c = input[2] ^ w[2]; + d = input[decrypt ? 1 : 3] ^ w[3]; + var i = 3; + for (var round = 1; round < Nr; ++round) { + a2 = m0[a >>> 24] ^ m1[b >>> 16 & 255] ^ m2[c >>> 8 & 255] ^ m3[d & 255] ^ w[++i]; + b2 = m0[b >>> 24] ^ m1[c >>> 16 & 255] ^ m2[d >>> 8 & 255] ^ m3[a & 255] ^ w[++i]; + c2 = m0[c >>> 24] ^ m1[d >>> 16 & 255] ^ m2[a >>> 8 & 255] ^ m3[b & 255] ^ w[++i]; + d = m0[d >>> 24] ^ m1[a >>> 16 & 255] ^ m2[b >>> 8 & 255] ^ m3[c & 255] ^ w[++i]; + a = a2; + b = b2; + c = c2; + } + output[0] = sub[a >>> 24] << 24 ^ sub[b >>> 16 & 255] << 16 ^ sub[c >>> 8 & 255] << 8 ^ sub[d & 255] ^ w[++i]; + output[decrypt ? 3 : 1] = sub[b >>> 24] << 24 ^ sub[c >>> 16 & 255] << 16 ^ sub[d >>> 8 & 255] << 8 ^ sub[a & 255] ^ w[++i]; + output[2] = sub[c >>> 24] << 24 ^ sub[d >>> 16 & 255] << 16 ^ sub[a >>> 8 & 255] << 8 ^ sub[b & 255] ^ w[++i]; + output[decrypt ? 1 : 3] = sub[d >>> 24] << 24 ^ sub[a >>> 16 & 255] << 16 ^ sub[b >>> 8 & 255] << 8 ^ sub[c & 255] ^ w[++i]; + } + function _createCipher(options) { + options = options || {}; + var mode = (options.mode || "CBC").toUpperCase(); + var algorithm = "AES-" + mode; + var cipher; + if (options.decrypt) { + cipher = forge.cipher.createDecipher(algorithm, options.key); + } else { + cipher = forge.cipher.createCipher(algorithm, options.key); + } + var start = cipher.start; + cipher.start = function(iv, options2) { + var output = null; + if (options2 instanceof forge.util.ByteBuffer) { + output = options2; + options2 = {}; + } + options2 = options2 || {}; + options2.output = output; + options2.iv = iv; + start.call(cipher, options2); + }; + return cipher; + } + } +}); + +// node_modules/node-forge/lib/oids.js +var require_oids = __commonJS({ + "node_modules/node-forge/lib/oids.js"(exports2, module2) { + var forge = require_forge(); + forge.pki = forge.pki || {}; + var oids = module2.exports = forge.pki.oids = forge.oids = forge.oids || {}; + function _IN(id, name) { + oids[id] = name; + oids[name] = id; + } + function _I_(id, name) { + oids[id] = name; + } + _IN("1.2.840.113549.1.1.1", "rsaEncryption"); + _IN("1.2.840.113549.1.1.4", "md5WithRSAEncryption"); + _IN("1.2.840.113549.1.1.5", "sha1WithRSAEncryption"); + _IN("1.2.840.113549.1.1.7", "RSAES-OAEP"); + _IN("1.2.840.113549.1.1.8", "mgf1"); + _IN("1.2.840.113549.1.1.9", "pSpecified"); + _IN("1.2.840.113549.1.1.10", "RSASSA-PSS"); + _IN("1.2.840.113549.1.1.11", "sha256WithRSAEncryption"); + _IN("1.2.840.113549.1.1.12", "sha384WithRSAEncryption"); + _IN("1.2.840.113549.1.1.13", "sha512WithRSAEncryption"); + _IN("1.3.101.112", "EdDSA25519"); + _IN("1.2.840.10040.4.3", "dsa-with-sha1"); + _IN("1.3.14.3.2.7", "desCBC"); + _IN("1.3.14.3.2.26", "sha1"); + _IN("1.3.14.3.2.29", "sha1WithRSASignature"); + _IN("2.16.840.1.101.3.4.2.1", "sha256"); + _IN("2.16.840.1.101.3.4.2.2", "sha384"); + _IN("2.16.840.1.101.3.4.2.3", "sha512"); + _IN("2.16.840.1.101.3.4.2.4", "sha224"); + _IN("2.16.840.1.101.3.4.2.5", "sha512-224"); + _IN("2.16.840.1.101.3.4.2.6", "sha512-256"); + _IN("1.2.840.113549.2.2", "md2"); + _IN("1.2.840.113549.2.5", "md5"); + _IN("1.2.840.113549.1.7.1", "data"); + _IN("1.2.840.113549.1.7.2", "signedData"); + _IN("1.2.840.113549.1.7.3", "envelopedData"); + _IN("1.2.840.113549.1.7.4", "signedAndEnvelopedData"); + _IN("1.2.840.113549.1.7.5", "digestedData"); + _IN("1.2.840.113549.1.7.6", "encryptedData"); + _IN("1.2.840.113549.1.9.1", "emailAddress"); + _IN("1.2.840.113549.1.9.2", "unstructuredName"); + _IN("1.2.840.113549.1.9.3", "contentType"); + _IN("1.2.840.113549.1.9.4", "messageDigest"); + _IN("1.2.840.113549.1.9.5", "signingTime"); + _IN("1.2.840.113549.1.9.6", "counterSignature"); + _IN("1.2.840.113549.1.9.7", "challengePassword"); + _IN("1.2.840.113549.1.9.8", "unstructuredAddress"); + _IN("1.2.840.113549.1.9.14", "extensionRequest"); + _IN("1.2.840.113549.1.9.20", "friendlyName"); + _IN("1.2.840.113549.1.9.21", "localKeyId"); + _IN("1.2.840.113549.1.9.22.1", "x509Certificate"); + _IN("1.2.840.113549.1.12.10.1.1", "keyBag"); + _IN("1.2.840.113549.1.12.10.1.2", "pkcs8ShroudedKeyBag"); + _IN("1.2.840.113549.1.12.10.1.3", "certBag"); + _IN("1.2.840.113549.1.12.10.1.4", "crlBag"); + _IN("1.2.840.113549.1.12.10.1.5", "secretBag"); + _IN("1.2.840.113549.1.12.10.1.6", "safeContentsBag"); + _IN("1.2.840.113549.1.5.13", "pkcs5PBES2"); + _IN("1.2.840.113549.1.5.12", "pkcs5PBKDF2"); + _IN("1.2.840.113549.1.12.1.1", "pbeWithSHAAnd128BitRC4"); + _IN("1.2.840.113549.1.12.1.2", "pbeWithSHAAnd40BitRC4"); + _IN("1.2.840.113549.1.12.1.3", "pbeWithSHAAnd3-KeyTripleDES-CBC"); + _IN("1.2.840.113549.1.12.1.4", "pbeWithSHAAnd2-KeyTripleDES-CBC"); + _IN("1.2.840.113549.1.12.1.5", "pbeWithSHAAnd128BitRC2-CBC"); + _IN("1.2.840.113549.1.12.1.6", "pbewithSHAAnd40BitRC2-CBC"); + _IN("1.2.840.113549.2.7", "hmacWithSHA1"); + _IN("1.2.840.113549.2.8", "hmacWithSHA224"); + _IN("1.2.840.113549.2.9", "hmacWithSHA256"); + _IN("1.2.840.113549.2.10", "hmacWithSHA384"); + _IN("1.2.840.113549.2.11", "hmacWithSHA512"); + _IN("1.2.840.113549.3.7", "des-EDE3-CBC"); + _IN("2.16.840.1.101.3.4.1.2", "aes128-CBC"); + _IN("2.16.840.1.101.3.4.1.22", "aes192-CBC"); + _IN("2.16.840.1.101.3.4.1.42", "aes256-CBC"); + _IN("2.5.4.3", "commonName"); + _IN("2.5.4.4", "surname"); + _IN("2.5.4.5", "serialNumber"); + _IN("2.5.4.6", "countryName"); + _IN("2.5.4.7", "localityName"); + _IN("2.5.4.8", "stateOrProvinceName"); + _IN("2.5.4.9", "streetAddress"); + _IN("2.5.4.10", "organizationName"); + _IN("2.5.4.11", "organizationalUnitName"); + _IN("2.5.4.12", "title"); + _IN("2.5.4.13", "description"); + _IN("2.5.4.15", "businessCategory"); + _IN("2.5.4.17", "postalCode"); + _IN("2.5.4.42", "givenName"); + _IN("2.5.4.65", "pseudonym"); + _IN("1.3.6.1.4.1.311.60.2.1.2", "jurisdictionOfIncorporationStateOrProvinceName"); + _IN("1.3.6.1.4.1.311.60.2.1.3", "jurisdictionOfIncorporationCountryName"); + _IN("2.16.840.1.113730.1.1", "nsCertType"); + _IN("2.16.840.1.113730.1.13", "nsComment"); + _I_("2.5.29.1", "authorityKeyIdentifier"); + _I_("2.5.29.2", "keyAttributes"); + _I_("2.5.29.3", "certificatePolicies"); + _I_("2.5.29.4", "keyUsageRestriction"); + _I_("2.5.29.5", "policyMapping"); + _I_("2.5.29.6", "subtreesConstraint"); + _I_("2.5.29.7", "subjectAltName"); + _I_("2.5.29.8", "issuerAltName"); + _I_("2.5.29.9", "subjectDirectoryAttributes"); + _I_("2.5.29.10", "basicConstraints"); + _I_("2.5.29.11", "nameConstraints"); + _I_("2.5.29.12", "policyConstraints"); + _I_("2.5.29.13", "basicConstraints"); + _IN("2.5.29.14", "subjectKeyIdentifier"); + _IN("2.5.29.15", "keyUsage"); + _I_("2.5.29.16", "privateKeyUsagePeriod"); + _IN("2.5.29.17", "subjectAltName"); + _IN("2.5.29.18", "issuerAltName"); + _IN("2.5.29.19", "basicConstraints"); + _I_("2.5.29.20", "cRLNumber"); + _I_("2.5.29.21", "cRLReason"); + _I_("2.5.29.22", "expirationDate"); + _I_("2.5.29.23", "instructionCode"); + _I_("2.5.29.24", "invalidityDate"); + _I_("2.5.29.25", "cRLDistributionPoints"); + _I_("2.5.29.26", "issuingDistributionPoint"); + _I_("2.5.29.27", "deltaCRLIndicator"); + _I_("2.5.29.28", "issuingDistributionPoint"); + _I_("2.5.29.29", "certificateIssuer"); + _I_("2.5.29.30", "nameConstraints"); + _IN("2.5.29.31", "cRLDistributionPoints"); + _IN("2.5.29.32", "certificatePolicies"); + _I_("2.5.29.33", "policyMappings"); + _I_("2.5.29.34", "policyConstraints"); + _IN("2.5.29.35", "authorityKeyIdentifier"); + _I_("2.5.29.36", "policyConstraints"); + _IN("2.5.29.37", "extKeyUsage"); + _I_("2.5.29.46", "freshestCRL"); + _I_("2.5.29.54", "inhibitAnyPolicy"); + _IN("1.3.6.1.4.1.11129.2.4.2", "timestampList"); + _IN("1.3.6.1.5.5.7.1.1", "authorityInfoAccess"); + _IN("1.3.6.1.5.5.7.3.1", "serverAuth"); + _IN("1.3.6.1.5.5.7.3.2", "clientAuth"); + _IN("1.3.6.1.5.5.7.3.3", "codeSigning"); + _IN("1.3.6.1.5.5.7.3.4", "emailProtection"); + _IN("1.3.6.1.5.5.7.3.8", "timeStamping"); + } +}); + +// node_modules/node-forge/lib/asn1.js +var require_asn1 = __commonJS({ + "node_modules/node-forge/lib/asn1.js"(exports2, module2) { + var forge = require_forge(); + require_util13(); + require_oids(); + var asn1 = module2.exports = forge.asn1 = forge.asn1 || {}; + asn1.Class = { + UNIVERSAL: 0, + APPLICATION: 64, + CONTEXT_SPECIFIC: 128, + PRIVATE: 192 + }; + asn1.Type = { + NONE: 0, + BOOLEAN: 1, + INTEGER: 2, + BITSTRING: 3, + OCTETSTRING: 4, + NULL: 5, + OID: 6, + ODESC: 7, + EXTERNAL: 8, + REAL: 9, + ENUMERATED: 10, + EMBEDDED: 11, + UTF8: 12, + ROID: 13, + SEQUENCE: 16, + SET: 17, + PRINTABLESTRING: 19, + IA5STRING: 22, + UTCTIME: 23, + GENERALIZEDTIME: 24, + BMPSTRING: 30 + }; + asn1.maxDepth = 256; + asn1.create = function(tagClass, type, constructed, value, options) { + if (forge.util.isArray(value)) { + var tmp = []; + for (var i = 0; i < value.length; ++i) { + if (value[i] !== void 0) { + tmp.push(value[i]); + } + } + value = tmp; + } + var obj = { + tagClass, + type, + constructed, + composed: constructed || forge.util.isArray(value), + value + }; + if (options && "bitStringContents" in options) { + obj.bitStringContents = options.bitStringContents; + obj.original = asn1.copy(obj); + } + return obj; + }; + asn1.copy = function(obj, options) { + var copy; + if (forge.util.isArray(obj)) { + copy = []; + for (var i = 0; i < obj.length; ++i) { + copy.push(asn1.copy(obj[i], options)); + } + return copy; + } + if (typeof obj === "string") { + return obj; + } + copy = { + tagClass: obj.tagClass, + type: obj.type, + constructed: obj.constructed, + composed: obj.composed, + value: asn1.copy(obj.value, options) + }; + if (options && !options.excludeBitStringContents) { + copy.bitStringContents = obj.bitStringContents; + } + return copy; + }; + asn1.equals = function(obj1, obj2, options) { + if (forge.util.isArray(obj1)) { + if (!forge.util.isArray(obj2)) { + return false; + } + if (obj1.length !== obj2.length) { + return false; + } + for (var i = 0; i < obj1.length; ++i) { + if (!asn1.equals(obj1[i], obj2[i])) { + return false; + } + } + return true; + } + if (typeof obj1 !== typeof obj2) { + return false; + } + if (typeof obj1 === "string") { + return obj1 === obj2; + } + var equal = obj1.tagClass === obj2.tagClass && obj1.type === obj2.type && obj1.constructed === obj2.constructed && obj1.composed === obj2.composed && asn1.equals(obj1.value, obj2.value); + if (options && options.includeBitStringContents) { + equal = equal && obj1.bitStringContents === obj2.bitStringContents; + } + return equal; + }; + asn1.getBerValueLength = function(b) { + var b2 = b.getByte(); + if (b2 === 128) { + return void 0; + } + var length; + var longForm = b2 & 128; + if (!longForm) { + length = b2; + } else { + length = b.getInt((b2 & 127) << 3); + } + return length; + }; + function _checkBufferLength(bytes, remaining, n) { + if (n > remaining) { + var error2 = new Error("Too few bytes to parse DER."); + error2.available = bytes.length(); + error2.remaining = remaining; + error2.requested = n; + throw error2; + } + } + var _getValueLength = function(bytes, remaining) { + var b2 = bytes.getByte(); + remaining--; + if (b2 === 128) { + return void 0; + } + var length; + var longForm = b2 & 128; + if (!longForm) { + length = b2; + } else { + var longFormBytes = b2 & 127; + _checkBufferLength(bytes, remaining, longFormBytes); + length = bytes.getInt(longFormBytes << 3); + } + if (length < 0) { + throw new Error("Negative length: " + length); + } + return length; + }; + asn1.fromDer = function(bytes, options) { + if (options === void 0) { + options = { + strict: true, + parseAllBytes: true, + decodeBitStrings: true + }; + } + if (typeof options === "boolean") { + options = { + strict: options, + parseAllBytes: true, + decodeBitStrings: true + }; + } + if (!("strict" in options)) { + options.strict = true; + } + if (!("parseAllBytes" in options)) { + options.parseAllBytes = true; + } + if (!("decodeBitStrings" in options)) { + options.decodeBitStrings = true; + } + if (!("maxDepth" in options)) { + options.maxDepth = asn1.maxDepth; + } + if (typeof bytes === "string") { + bytes = forge.util.createBuffer(bytes); + } + var byteCount = bytes.length(); + var value = _fromDer(bytes, bytes.length(), 0, options); + if (options.parseAllBytes && bytes.length() !== 0) { + var error2 = new Error("Unparsed DER bytes remain after ASN.1 parsing."); + error2.byteCount = byteCount; + error2.remaining = bytes.length(); + throw error2; + } + return value; + }; + function _fromDer(bytes, remaining, depth, options) { + if (depth >= options.maxDepth) { + throw new Error("ASN.1 parsing error: Max depth exceeded."); + } + var start; + _checkBufferLength(bytes, remaining, 2); + var b1 = bytes.getByte(); + remaining--; + var tagClass = b1 & 192; + var type = b1 & 31; + start = bytes.length(); + var length = _getValueLength(bytes, remaining); + remaining -= start - bytes.length(); + if (length !== void 0 && length > remaining) { + if (options.strict) { + var error2 = new Error("Too few bytes to read ASN.1 value."); + error2.available = bytes.length(); + error2.remaining = remaining; + error2.requested = length; + throw error2; + } + length = remaining; + } + var value; + var bitStringContents; + var constructed = (b1 & 32) === 32; + if (constructed) { + value = []; + if (length === void 0) { + for (; ; ) { + _checkBufferLength(bytes, remaining, 2); + if (bytes.bytes(2) === String.fromCharCode(0, 0)) { + bytes.getBytes(2); + remaining -= 2; + break; + } + start = bytes.length(); + value.push(_fromDer(bytes, remaining, depth + 1, options)); + remaining -= start - bytes.length(); + } + } else { + while (length > 0) { + start = bytes.length(); + value.push(_fromDer(bytes, length, depth + 1, options)); + remaining -= start - bytes.length(); + length -= start - bytes.length(); + } + } + } + if (value === void 0 && tagClass === asn1.Class.UNIVERSAL && type === asn1.Type.BITSTRING) { + bitStringContents = bytes.bytes(length); + } + if (value === void 0 && options.decodeBitStrings && tagClass === asn1.Class.UNIVERSAL && // FIXME: OCTET STRINGs not yet supported here + // .. other parts of forge expect to decode OCTET STRINGs manually + type === asn1.Type.BITSTRING && length > 1) { + var savedRead = bytes.read; + var savedRemaining = remaining; + var unused = 0; + if (type === asn1.Type.BITSTRING) { + _checkBufferLength(bytes, remaining, 1); + unused = bytes.getByte(); + remaining--; + } + if (unused === 0) { + try { + start = bytes.length(); + var subOptions = { + // enforce strict mode to avoid parsing ASN.1 from plain data + strict: true, + decodeBitStrings: true + }; + var composed = _fromDer(bytes, remaining, depth + 1, subOptions); + var used = start - bytes.length(); + remaining -= used; + if (type == asn1.Type.BITSTRING) { + used++; + } + var tc = composed.tagClass; + if (used === length && (tc === asn1.Class.UNIVERSAL || tc === asn1.Class.CONTEXT_SPECIFIC)) { + value = [composed]; + } + } catch (ex) { + } + } + if (value === void 0) { + bytes.read = savedRead; + remaining = savedRemaining; + } + } + if (value === void 0) { + if (length === void 0) { + if (options.strict) { + throw new Error("Non-constructed ASN.1 object of indefinite length."); + } + length = remaining; + } + if (type === asn1.Type.BMPSTRING) { + value = ""; + for (; length > 0; length -= 2) { + _checkBufferLength(bytes, remaining, 2); + value += String.fromCharCode(bytes.getInt16()); + remaining -= 2; + } + } else { + value = bytes.getBytes(length); + remaining -= length; + } + } + var asn1Options = bitStringContents === void 0 ? null : { + bitStringContents + }; + return asn1.create(tagClass, type, constructed, value, asn1Options); + } + asn1.toDer = function(obj) { + var bytes = forge.util.createBuffer(); + var b1 = obj.tagClass | obj.type; + var value = forge.util.createBuffer(); + var useBitStringContents = false; + if ("bitStringContents" in obj) { + useBitStringContents = true; + if (obj.original) { + useBitStringContents = asn1.equals(obj, obj.original); + } + } + if (useBitStringContents) { + value.putBytes(obj.bitStringContents); + } else if (obj.composed) { + if (obj.constructed) { + b1 |= 32; + } else { + value.putByte(0); + } + for (var i = 0; i < obj.value.length; ++i) { + if (obj.value[i] !== void 0) { + value.putBuffer(asn1.toDer(obj.value[i])); + } + } + } else { + if (obj.type === asn1.Type.BMPSTRING) { + for (var i = 0; i < obj.value.length; ++i) { + value.putInt16(obj.value.charCodeAt(i)); + } + } else { + if (obj.type === asn1.Type.INTEGER && obj.value.length > 1 && // leading 0x00 for positive integer + (obj.value.charCodeAt(0) === 0 && (obj.value.charCodeAt(1) & 128) === 0 || // leading 0xFF for negative integer + obj.value.charCodeAt(0) === 255 && (obj.value.charCodeAt(1) & 128) === 128)) { + value.putBytes(obj.value.substr(1)); + } else { + value.putBytes(obj.value); + } + } + } + bytes.putByte(b1); + if (value.length() <= 127) { + bytes.putByte(value.length() & 127); + } else { + var len = value.length(); + var lenBytes = ""; + do { + lenBytes += String.fromCharCode(len & 255); + len = len >>> 8; + } while (len > 0); + bytes.putByte(lenBytes.length | 128); + for (var i = lenBytes.length - 1; i >= 0; --i) { + bytes.putByte(lenBytes.charCodeAt(i)); + } + } + bytes.putBuffer(value); + return bytes; + }; + asn1.oidToDer = function(oid) { + var values = oid.split("."); + var bytes = forge.util.createBuffer(); + bytes.putByte(40 * parseInt(values[0], 10) + parseInt(values[1], 10)); + var last, valueBytes, value, b; + for (var i = 2; i < values.length; ++i) { + last = true; + valueBytes = []; + value = parseInt(values[i], 10); + if (value > 4294967295) { + throw new Error("OID value too large; max is 32-bits."); + } + do { + b = value & 127; + value = value >>> 7; + if (!last) { + b |= 128; + } + valueBytes.push(b); + last = false; + } while (value > 0); + for (var n = valueBytes.length - 1; n >= 0; --n) { + bytes.putByte(valueBytes[n]); + } + } + return bytes; + }; + asn1.derToOid = function(bytes) { + var oid; + if (typeof bytes === "string") { + bytes = forge.util.createBuffer(bytes); + } + var b = bytes.getByte(); + oid = Math.floor(b / 40) + "." + b % 40; + var value = 0; + while (bytes.length() > 0) { + if (value > 70368744177663) { + throw new Error("OID value too large; max is 53-bits."); + } + b = bytes.getByte(); + value = value * 128; + if (b & 128) { + value += b & 127; + } else { + oid += "." + (value + b); + value = 0; + } + } + return oid; + }; + asn1.utcTimeToDate = function(utc) { + var date = /* @__PURE__ */ new Date(); + var year = parseInt(utc.substr(0, 2), 10); + year = year >= 50 ? 1900 + year : 2e3 + year; + var MM = parseInt(utc.substr(2, 2), 10) - 1; + var DD = parseInt(utc.substr(4, 2), 10); + var hh = parseInt(utc.substr(6, 2), 10); + var mm = parseInt(utc.substr(8, 2), 10); + var ss = 0; + if (utc.length > 11) { + var c = utc.charAt(10); + var end = 10; + if (c !== "+" && c !== "-") { + ss = parseInt(utc.substr(10, 2), 10); + end += 2; + } + } + date.setUTCFullYear(year, MM, DD); + date.setUTCHours(hh, mm, ss, 0); + if (end) { + c = utc.charAt(end); + if (c === "+" || c === "-") { + var hhoffset = parseInt(utc.substr(end + 1, 2), 10); + var mmoffset = parseInt(utc.substr(end + 4, 2), 10); + var offset = hhoffset * 60 + mmoffset; + offset *= 6e4; + if (c === "+") { + date.setTime(+date - offset); + } else { + date.setTime(+date + offset); + } + } + } + return date; + }; + asn1.generalizedTimeToDate = function(gentime) { + var date = /* @__PURE__ */ new Date(); + var YYYY = parseInt(gentime.substr(0, 4), 10); + var MM = parseInt(gentime.substr(4, 2), 10) - 1; + var DD = parseInt(gentime.substr(6, 2), 10); + var hh = parseInt(gentime.substr(8, 2), 10); + var mm = parseInt(gentime.substr(10, 2), 10); + var ss = parseInt(gentime.substr(12, 2), 10); + var fff = 0; + var offset = 0; + var isUTC = false; + if (gentime.charAt(gentime.length - 1) === "Z") { + isUTC = true; + } + var end = gentime.length - 5, c = gentime.charAt(end); + if (c === "+" || c === "-") { + var hhoffset = parseInt(gentime.substr(end + 1, 2), 10); + var mmoffset = parseInt(gentime.substr(end + 4, 2), 10); + offset = hhoffset * 60 + mmoffset; + offset *= 6e4; + if (c === "+") { + offset *= -1; + } + isUTC = true; + } + if (gentime.charAt(14) === ".") { + fff = parseFloat(gentime.substr(14), 10) * 1e3; + } + if (isUTC) { + date.setUTCFullYear(YYYY, MM, DD); + date.setUTCHours(hh, mm, ss, fff); + date.setTime(+date + offset); + } else { + date.setFullYear(YYYY, MM, DD); + date.setHours(hh, mm, ss, fff); + } + return date; + }; + asn1.dateToUtcTime = function(date) { + if (typeof date === "string") { + return date; + } + var rval = ""; + var format = []; + format.push(("" + date.getUTCFullYear()).substr(2)); + format.push("" + (date.getUTCMonth() + 1)); + format.push("" + date.getUTCDate()); + format.push("" + date.getUTCHours()); + format.push("" + date.getUTCMinutes()); + format.push("" + date.getUTCSeconds()); + for (var i = 0; i < format.length; ++i) { + if (format[i].length < 2) { + rval += "0"; + } + rval += format[i]; + } + rval += "Z"; + return rval; + }; + asn1.dateToGeneralizedTime = function(date) { + if (typeof date === "string") { + return date; + } + var rval = ""; + var format = []; + format.push("" + date.getUTCFullYear()); + format.push("" + (date.getUTCMonth() + 1)); + format.push("" + date.getUTCDate()); + format.push("" + date.getUTCHours()); + format.push("" + date.getUTCMinutes()); + format.push("" + date.getUTCSeconds()); + for (var i = 0; i < format.length; ++i) { + if (format[i].length < 2) { + rval += "0"; + } + rval += format[i]; + } + rval += "Z"; + return rval; + }; + asn1.integerToDer = function(x) { + var rval = forge.util.createBuffer(); + if (x >= -128 && x < 128) { + return rval.putSignedInt(x, 8); + } + if (x >= -32768 && x < 32768) { + return rval.putSignedInt(x, 16); + } + if (x >= -8388608 && x < 8388608) { + return rval.putSignedInt(x, 24); + } + if (x >= -2147483648 && x < 2147483648) { + return rval.putSignedInt(x, 32); + } + var error2 = new Error("Integer too large; max is 32-bits."); + error2.integer = x; + throw error2; + }; + asn1.derToInteger = function(bytes) { + if (typeof bytes === "string") { + bytes = forge.util.createBuffer(bytes); + } + var n = bytes.length() * 8; + if (n > 32) { + throw new Error("Integer too large; max is 32-bits."); + } + return bytes.getSignedInt(n); + }; + asn1.validate = function(obj, v, capture, errors) { + var rval = false; + if ((obj.tagClass === v.tagClass || typeof v.tagClass === "undefined") && (obj.type === v.type || typeof v.type === "undefined")) { + if (obj.constructed === v.constructed || typeof v.constructed === "undefined") { + rval = true; + if (v.value && forge.util.isArray(v.value)) { + var j = 0; + for (var i = 0; rval && i < v.value.length; ++i) { + var schemaItem = v.value[i]; + rval = !!schemaItem.optional; + var objChild = obj.value[j]; + if (!objChild) { + if (!schemaItem.optional) { + rval = false; + if (errors) { + errors.push("[" + v.name + '] Missing required element. Expected tag class "' + schemaItem.tagClass + '", type "' + schemaItem.type + '"'); + } + } + continue; + } + var schemaHasTag = typeof schemaItem.tagClass !== "undefined" && typeof schemaItem.type !== "undefined"; + if (schemaHasTag && (objChild.tagClass !== schemaItem.tagClass || objChild.type !== schemaItem.type)) { + if (schemaItem.optional) { + rval = true; + continue; + } else { + rval = false; + if (errors) { + errors.push("[" + v.name + "] Tag mismatch. Expected (" + schemaItem.tagClass + "," + schemaItem.type + "), got (" + objChild.tagClass + "," + objChild.type + ")"); + } + break; + } + } + var childRval = asn1.validate(objChild, schemaItem, capture, errors); + if (childRval) { + ++j; + rval = true; + } else if (schemaItem.optional) { + rval = true; + } else { + rval = false; + break; + } + } + } + if (rval && capture) { + if (v.capture) { + capture[v.capture] = obj.value; + } + if (v.captureAsn1) { + capture[v.captureAsn1] = obj; + } + if (v.captureBitStringContents && "bitStringContents" in obj) { + capture[v.captureBitStringContents] = obj.bitStringContents; + } + if (v.captureBitStringValue && "bitStringContents" in obj) { + var value; + if (obj.bitStringContents.length < 2) { + capture[v.captureBitStringValue] = ""; + } else { + var unused = obj.bitStringContents.charCodeAt(0); + if (unused !== 0) { + throw new Error( + "captureBitStringValue only supported for zero unused bits" + ); + } + capture[v.captureBitStringValue] = obj.bitStringContents.slice(1); + } + } + } + } else if (errors) { + errors.push( + "[" + v.name + '] Expected constructed "' + v.constructed + '", got "' + obj.constructed + '"' + ); + } + } else if (errors) { + if (obj.tagClass !== v.tagClass) { + errors.push( + "[" + v.name + '] Expected tag class "' + v.tagClass + '", got "' + obj.tagClass + '"' + ); + } + if (obj.type !== v.type) { + errors.push( + "[" + v.name + '] Expected type "' + v.type + '", got "' + obj.type + '"' + ); + } + } + return rval; + }; + var _nonLatinRegex = /[^\\u0000-\\u00ff]/; + asn1.prettyPrint = function(obj, level, indentation) { + var rval = ""; + level = level || 0; + indentation = indentation || 2; + if (level > 0) { + rval += "\n"; + } + var indent = ""; + for (var i = 0; i < level * indentation; ++i) { + indent += " "; + } + rval += indent + "Tag: "; + switch (obj.tagClass) { + case asn1.Class.UNIVERSAL: + rval += "Universal:"; + break; + case asn1.Class.APPLICATION: + rval += "Application:"; + break; + case asn1.Class.CONTEXT_SPECIFIC: + rval += "Context-Specific:"; + break; + case asn1.Class.PRIVATE: + rval += "Private:"; + break; + } + if (obj.tagClass === asn1.Class.UNIVERSAL) { + rval += obj.type; + switch (obj.type) { + case asn1.Type.NONE: + rval += " (None)"; + break; + case asn1.Type.BOOLEAN: + rval += " (Boolean)"; + break; + case asn1.Type.INTEGER: + rval += " (Integer)"; + break; + case asn1.Type.BITSTRING: + rval += " (Bit string)"; + break; + case asn1.Type.OCTETSTRING: + rval += " (Octet string)"; + break; + case asn1.Type.NULL: + rval += " (Null)"; + break; + case asn1.Type.OID: + rval += " (Object Identifier)"; + break; + case asn1.Type.ODESC: + rval += " (Object Descriptor)"; + break; + case asn1.Type.EXTERNAL: + rval += " (External or Instance of)"; + break; + case asn1.Type.REAL: + rval += " (Real)"; + break; + case asn1.Type.ENUMERATED: + rval += " (Enumerated)"; + break; + case asn1.Type.EMBEDDED: + rval += " (Embedded PDV)"; + break; + case asn1.Type.UTF8: + rval += " (UTF8)"; + break; + case asn1.Type.ROID: + rval += " (Relative Object Identifier)"; + break; + case asn1.Type.SEQUENCE: + rval += " (Sequence)"; + break; + case asn1.Type.SET: + rval += " (Set)"; + break; + case asn1.Type.PRINTABLESTRING: + rval += " (Printable String)"; + break; + case asn1.Type.IA5String: + rval += " (IA5String (ASCII))"; + break; + case asn1.Type.UTCTIME: + rval += " (UTC time)"; + break; + case asn1.Type.GENERALIZEDTIME: + rval += " (Generalized time)"; + break; + case asn1.Type.BMPSTRING: + rval += " (BMP String)"; + break; + } + } else { + rval += obj.type; + } + rval += "\n"; + rval += indent + "Constructed: " + obj.constructed + "\n"; + if (obj.composed) { + var subvalues = 0; + var sub = ""; + for (var i = 0; i < obj.value.length; ++i) { + if (obj.value[i] !== void 0) { + subvalues += 1; + sub += asn1.prettyPrint(obj.value[i], level + 1, indentation); + if (i + 1 < obj.value.length) { + sub += ","; + } + } + } + rval += indent + "Sub values: " + subvalues + sub; + } else { + rval += indent + "Value: "; + if (obj.type === asn1.Type.OID) { + var oid = asn1.derToOid(obj.value); + rval += oid; + if (forge.pki && forge.pki.oids) { + if (oid in forge.pki.oids) { + rval += " (" + forge.pki.oids[oid] + ") "; + } + } + } + if (obj.type === asn1.Type.INTEGER) { + try { + rval += asn1.derToInteger(obj.value); + } catch (ex) { + rval += "0x" + forge.util.bytesToHex(obj.value); + } + } else if (obj.type === asn1.Type.BITSTRING) { + if (obj.value.length > 1) { + rval += "0x" + forge.util.bytesToHex(obj.value.slice(1)); + } else { + rval += "(none)"; + } + if (obj.value.length > 0) { + var unused = obj.value.charCodeAt(0); + if (unused == 1) { + rval += " (1 unused bit shown)"; + } else if (unused > 1) { + rval += " (" + unused + " unused bits shown)"; + } + } + } else if (obj.type === asn1.Type.OCTETSTRING) { + if (!_nonLatinRegex.test(obj.value)) { + rval += "(" + obj.value + ") "; + } + rval += "0x" + forge.util.bytesToHex(obj.value); + } else if (obj.type === asn1.Type.UTF8) { + try { + rval += forge.util.decodeUtf8(obj.value); + } catch (e) { + if (e.message === "URI malformed") { + rval += "0x" + forge.util.bytesToHex(obj.value) + " (malformed UTF8)"; + } else { + throw e; + } + } + } else if (obj.type === asn1.Type.PRINTABLESTRING || obj.type === asn1.Type.IA5String) { + rval += obj.value; + } else if (_nonLatinRegex.test(obj.value)) { + rval += "0x" + forge.util.bytesToHex(obj.value); + } else if (obj.value.length === 0) { + rval += "[null]"; + } else { + rval += obj.value; + } + } + return rval; + }; + } +}); + +// node_modules/node-forge/lib/md.js +var require_md = __commonJS({ + "node_modules/node-forge/lib/md.js"(exports2, module2) { + var forge = require_forge(); + module2.exports = forge.md = forge.md || {}; + forge.md.algorithms = forge.md.algorithms || {}; + } +}); + +// node_modules/node-forge/lib/hmac.js +var require_hmac = __commonJS({ + "node_modules/node-forge/lib/hmac.js"(exports2, module2) { + var forge = require_forge(); + require_md(); + require_util13(); + var hmac = module2.exports = forge.hmac = forge.hmac || {}; + hmac.create = function() { + var _key = null; + var _md = null; + var _ipadding = null; + var _opadding = null; + var ctx = {}; + ctx.start = function(md2, key) { + if (md2 !== null) { + if (typeof md2 === "string") { + md2 = md2.toLowerCase(); + if (md2 in forge.md.algorithms) { + _md = forge.md.algorithms[md2].create(); + } else { + throw new Error('Unknown hash algorithm "' + md2 + '"'); + } + } else { + _md = md2; + } + } + if (key === null) { + key = _key; + } else { + if (typeof key === "string") { + key = forge.util.createBuffer(key); + } else if (forge.util.isArray(key)) { + var tmp = key; + key = forge.util.createBuffer(); + for (var i = 0; i < tmp.length; ++i) { + key.putByte(tmp[i]); + } + } + var keylen = key.length(); + if (keylen > _md.blockLength) { + _md.start(); + _md.update(key.bytes()); + key = _md.digest(); + } + _ipadding = forge.util.createBuffer(); + _opadding = forge.util.createBuffer(); + keylen = key.length(); + for (var i = 0; i < keylen; ++i) { + var tmp = key.at(i); + _ipadding.putByte(54 ^ tmp); + _opadding.putByte(92 ^ tmp); + } + if (keylen < _md.blockLength) { + var tmp = _md.blockLength - keylen; + for (var i = 0; i < tmp; ++i) { + _ipadding.putByte(54); + _opadding.putByte(92); + } + } + _key = key; + _ipadding = _ipadding.bytes(); + _opadding = _opadding.bytes(); + } + _md.start(); + _md.update(_ipadding); + }; + ctx.update = function(bytes) { + _md.update(bytes); + }; + ctx.getMac = function() { + var inner = _md.digest().bytes(); + _md.start(); + _md.update(_opadding); + _md.update(inner); + return _md.digest(); + }; + ctx.digest = ctx.getMac; + return ctx; + }; + } +}); + +// node_modules/node-forge/lib/md5.js +var require_md5 = __commonJS({ + "node_modules/node-forge/lib/md5.js"(exports2, module2) { + var forge = require_forge(); + require_md(); + require_util13(); + var md5 = module2.exports = forge.md5 = forge.md5 || {}; + forge.md.md5 = forge.md.algorithms.md5 = md5; + md5.create = function() { + if (!_initialized) { + _init(); + } + var _state = null; + var _input = forge.util.createBuffer(); + var _w = new Array(16); + var md2 = { + algorithm: "md5", + blockLength: 64, + digestLength: 16, + // 56-bit length of message so far (does not including padding) + messageLength: 0, + // true message length + fullMessageLength: null, + // size of message length in bytes + messageLengthSize: 8 + }; + md2.start = function() { + md2.messageLength = 0; + md2.fullMessageLength = md2.messageLength64 = []; + var int32s = md2.messageLengthSize / 4; + for (var i = 0; i < int32s; ++i) { + md2.fullMessageLength.push(0); + } + _input = forge.util.createBuffer(); + _state = { + h0: 1732584193, + h1: 4023233417, + h2: 2562383102, + h3: 271733878 + }; + return md2; + }; + md2.start(); + md2.update = function(msg, encoding) { + if (encoding === "utf8") { + msg = forge.util.encodeUtf8(msg); + } + var len = msg.length; + md2.messageLength += len; + len = [len / 4294967296 >>> 0, len >>> 0]; + for (var i = md2.fullMessageLength.length - 1; i >= 0; --i) { + md2.fullMessageLength[i] += len[1]; + len[1] = len[0] + (md2.fullMessageLength[i] / 4294967296 >>> 0); + md2.fullMessageLength[i] = md2.fullMessageLength[i] >>> 0; + len[0] = len[1] / 4294967296 >>> 0; + } + _input.putBytes(msg); + _update(_state, _w, _input); + if (_input.read > 2048 || _input.length() === 0) { + _input.compact(); + } + return md2; + }; + md2.digest = function() { + var finalBlock = forge.util.createBuffer(); + finalBlock.putBytes(_input.bytes()); + var remaining = md2.fullMessageLength[md2.fullMessageLength.length - 1] + md2.messageLengthSize; + var overflow = remaining & md2.blockLength - 1; + finalBlock.putBytes(_padding.substr(0, md2.blockLength - overflow)); + var bits, carry = 0; + for (var i = md2.fullMessageLength.length - 1; i >= 0; --i) { + bits = md2.fullMessageLength[i] * 8 + carry; + carry = bits / 4294967296 >>> 0; + finalBlock.putInt32Le(bits >>> 0); + } + var s2 = { + h0: _state.h0, + h1: _state.h1, + h2: _state.h2, + h3: _state.h3 + }; + _update(s2, _w, finalBlock); + var rval = forge.util.createBuffer(); + rval.putInt32Le(s2.h0); + rval.putInt32Le(s2.h1); + rval.putInt32Le(s2.h2); + rval.putInt32Le(s2.h3); + return rval; + }; + return md2; + }; + var _padding = null; + var _g = null; + var _r = null; + var _k = null; + var _initialized = false; + function _init() { + _padding = String.fromCharCode(128); + _padding += forge.util.fillString(String.fromCharCode(0), 64); + _g = [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 1, + 6, + 11, + 0, + 5, + 10, + 15, + 4, + 9, + 14, + 3, + 8, + 13, + 2, + 7, + 12, + 5, + 8, + 11, + 14, + 1, + 4, + 7, + 10, + 13, + 0, + 3, + 6, + 9, + 12, + 15, + 2, + 0, + 7, + 14, + 5, + 12, + 3, + 10, + 1, + 8, + 15, + 6, + 13, + 4, + 11, + 2, + 9 + ]; + _r = [ + 7, + 12, + 17, + 22, + 7, + 12, + 17, + 22, + 7, + 12, + 17, + 22, + 7, + 12, + 17, + 22, + 5, + 9, + 14, + 20, + 5, + 9, + 14, + 20, + 5, + 9, + 14, + 20, + 5, + 9, + 14, + 20, + 4, + 11, + 16, + 23, + 4, + 11, + 16, + 23, + 4, + 11, + 16, + 23, + 4, + 11, + 16, + 23, + 6, + 10, + 15, + 21, + 6, + 10, + 15, + 21, + 6, + 10, + 15, + 21, + 6, + 10, + 15, + 21 + ]; + _k = new Array(64); + for (var i = 0; i < 64; ++i) { + _k[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296); + } + _initialized = true; + } + function _update(s, w, bytes) { + var t, a, b, c, d, f, r, i; + var len = bytes.length(); + while (len >= 64) { + a = s.h0; + b = s.h1; + c = s.h2; + d = s.h3; + for (i = 0; i < 16; ++i) { + w[i] = bytes.getInt32Le(); + f = d ^ b & (c ^ d); + t = a + f + _k[i] + w[i]; + r = _r[i]; + a = d; + d = c; + c = b; + b += t << r | t >>> 32 - r; + } + for (; i < 32; ++i) { + f = c ^ d & (b ^ c); + t = a + f + _k[i] + w[_g[i]]; + r = _r[i]; + a = d; + d = c; + c = b; + b += t << r | t >>> 32 - r; + } + for (; i < 48; ++i) { + f = b ^ c ^ d; + t = a + f + _k[i] + w[_g[i]]; + r = _r[i]; + a = d; + d = c; + c = b; + b += t << r | t >>> 32 - r; + } + for (; i < 64; ++i) { + f = c ^ (b | ~d); + t = a + f + _k[i] + w[_g[i]]; + r = _r[i]; + a = d; + d = c; + c = b; + b += t << r | t >>> 32 - r; + } + s.h0 = s.h0 + a | 0; + s.h1 = s.h1 + b | 0; + s.h2 = s.h2 + c | 0; + s.h3 = s.h3 + d | 0; + len -= 64; + } + } + } +}); + +// node_modules/node-forge/lib/pem.js +var require_pem = __commonJS({ + "node_modules/node-forge/lib/pem.js"(exports2, module2) { + var forge = require_forge(); + require_util13(); + var pem = module2.exports = forge.pem = forge.pem || {}; + pem.encode = function(msg, options) { + options = options || {}; + var rval = "-----BEGIN " + msg.type + "-----\r\n"; + var header; + if (msg.procType) { + header = { + name: "Proc-Type", + values: [String(msg.procType.version), msg.procType.type] + }; + rval += foldHeader(header); + } + if (msg.contentDomain) { + header = { name: "Content-Domain", values: [msg.contentDomain] }; + rval += foldHeader(header); + } + if (msg.dekInfo) { + header = { name: "DEK-Info", values: [msg.dekInfo.algorithm] }; + if (msg.dekInfo.parameters) { + header.values.push(msg.dekInfo.parameters); + } + rval += foldHeader(header); + } + if (msg.headers) { + for (var i = 0; i < msg.headers.length; ++i) { + rval += foldHeader(msg.headers[i]); + } + } + if (msg.procType) { + rval += "\r\n"; + } + rval += forge.util.encode64(msg.body, options.maxline || 64) + "\r\n"; + rval += "-----END " + msg.type + "-----\r\n"; + return rval; + }; + pem.decode = function(str) { + var rval = []; + var rMessage = /\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g; + var rHeader = /([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/; + var rCRLF = /\r?\n/; + var match; + while (true) { + match = rMessage.exec(str); + if (!match) { + break; + } + var type = match[1]; + if (type === "NEW CERTIFICATE REQUEST") { + type = "CERTIFICATE REQUEST"; + } + var msg = { + type, + procType: null, + contentDomain: null, + dekInfo: null, + headers: [], + body: forge.util.decode64(match[3]) + }; + rval.push(msg); + if (!match[2]) { + continue; + } + var lines = match[2].split(rCRLF); + var li = 0; + while (match && li < lines.length) { + var line = lines[li].replace(/\s+$/, ""); + for (var nl = li + 1; nl < lines.length; ++nl) { + var next = lines[nl]; + if (!/\s/.test(next[0])) { + break; + } + line += next; + li = nl; + } + match = line.match(rHeader); + if (match) { + var header = { name: match[1], values: [] }; + var values = match[2].split(","); + for (var vi = 0; vi < values.length; ++vi) { + header.values.push(ltrim(values[vi])); + } + if (!msg.procType) { + if (header.name !== "Proc-Type") { + throw new Error('Invalid PEM formatted message. The first encapsulated header must be "Proc-Type".'); + } else if (header.values.length !== 2) { + throw new Error('Invalid PEM formatted message. The "Proc-Type" header must have two subfields.'); + } + msg.procType = { version: values[0], type: values[1] }; + } else if (!msg.contentDomain && header.name === "Content-Domain") { + msg.contentDomain = values[0] || ""; + } else if (!msg.dekInfo && header.name === "DEK-Info") { + if (header.values.length === 0) { + throw new Error('Invalid PEM formatted message. The "DEK-Info" header must have at least one subfield.'); + } + msg.dekInfo = { algorithm: values[0], parameters: values[1] || null }; + } else { + msg.headers.push(header); + } + } + ++li; + } + if (msg.procType === "ENCRYPTED" && !msg.dekInfo) { + throw new Error('Invalid PEM formatted message. The "DEK-Info" header must be present if "Proc-Type" is "ENCRYPTED".'); + } + } + if (rval.length === 0) { + throw new Error("Invalid PEM formatted message."); + } + return rval; + }; + function foldHeader(header) { + var rval = header.name + ": "; + var values = []; + var insertSpace = function(match, $1) { + return " " + $1; + }; + for (var i = 0; i < header.values.length; ++i) { + values.push(header.values[i].replace(/^(\S+\r\n)/, insertSpace)); + } + rval += values.join(",") + "\r\n"; + var length = 0; + var candidate = -1; + for (var i = 0; i < rval.length; ++i, ++length) { + if (length > 65 && candidate !== -1) { + var insert = rval[candidate]; + if (insert === ",") { + ++candidate; + rval = rval.substr(0, candidate) + "\r\n " + rval.substr(candidate); + } else { + rval = rval.substr(0, candidate) + "\r\n" + insert + rval.substr(candidate + 1); + } + length = i - candidate - 1; + candidate = -1; + ++i; + } else if (rval[i] === " " || rval[i] === " " || rval[i] === ",") { + candidate = i; + } + } + return rval; + } + function ltrim(str) { + return str.replace(/^\s+/, ""); + } + } +}); + +// node_modules/node-forge/lib/des.js +var require_des = __commonJS({ + "node_modules/node-forge/lib/des.js"(exports2, module2) { + var forge = require_forge(); + require_cipher(); + require_cipherModes(); + require_util13(); + module2.exports = forge.des = forge.des || {}; + forge.des.startEncrypting = function(key, iv, output, mode) { + var cipher = _createCipher({ + key, + output, + decrypt: false, + mode: mode || (iv === null ? "ECB" : "CBC") + }); + cipher.start(iv); + return cipher; + }; + forge.des.createEncryptionCipher = function(key, mode) { + return _createCipher({ + key, + output: null, + decrypt: false, + mode + }); + }; + forge.des.startDecrypting = function(key, iv, output, mode) { + var cipher = _createCipher({ + key, + output, + decrypt: true, + mode: mode || (iv === null ? "ECB" : "CBC") + }); + cipher.start(iv); + return cipher; + }; + forge.des.createDecryptionCipher = function(key, mode) { + return _createCipher({ + key, + output: null, + decrypt: true, + mode + }); + }; + forge.des.Algorithm = function(name, mode) { + var self2 = this; + self2.name = name; + self2.mode = new mode({ + blockSize: 8, + cipher: { + encrypt: function(inBlock, outBlock) { + return _updateBlock(self2._keys, inBlock, outBlock, false); + }, + decrypt: function(inBlock, outBlock) { + return _updateBlock(self2._keys, inBlock, outBlock, true); + } + } + }); + self2._init = false; + }; + forge.des.Algorithm.prototype.initialize = function(options) { + if (this._init) { + return; + } + var key = forge.util.createBuffer(options.key); + if (this.name.indexOf("3DES") === 0) { + if (key.length() !== 24) { + throw new Error("Invalid Triple-DES key size: " + key.length() * 8); + } + } + this._keys = _createKeys(key); + this._init = true; + }; + registerAlgorithm("DES-ECB", forge.cipher.modes.ecb); + registerAlgorithm("DES-CBC", forge.cipher.modes.cbc); + registerAlgorithm("DES-CFB", forge.cipher.modes.cfb); + registerAlgorithm("DES-OFB", forge.cipher.modes.ofb); + registerAlgorithm("DES-CTR", forge.cipher.modes.ctr); + registerAlgorithm("3DES-ECB", forge.cipher.modes.ecb); + registerAlgorithm("3DES-CBC", forge.cipher.modes.cbc); + registerAlgorithm("3DES-CFB", forge.cipher.modes.cfb); + registerAlgorithm("3DES-OFB", forge.cipher.modes.ofb); + registerAlgorithm("3DES-CTR", forge.cipher.modes.ctr); + function registerAlgorithm(name, mode) { + var factory = function() { + return new forge.des.Algorithm(name, mode); + }; + forge.cipher.registerAlgorithm(name, factory); + } + var spfunction1 = [16843776, 0, 65536, 16843780, 16842756, 66564, 4, 65536, 1024, 16843776, 16843780, 1024, 16778244, 16842756, 16777216, 4, 1028, 16778240, 16778240, 66560, 66560, 16842752, 16842752, 16778244, 65540, 16777220, 16777220, 65540, 0, 1028, 66564, 16777216, 65536, 16843780, 4, 16842752, 16843776, 16777216, 16777216, 1024, 16842756, 65536, 66560, 16777220, 1024, 4, 16778244, 66564, 16843780, 65540, 16842752, 16778244, 16777220, 1028, 66564, 16843776, 1028, 16778240, 16778240, 0, 65540, 66560, 0, 16842756]; + var spfunction2 = [-2146402272, -2147450880, 32768, 1081376, 1048576, 32, -2146435040, -2147450848, -2147483616, -2146402272, -2146402304, -2147483648, -2147450880, 1048576, 32, -2146435040, 1081344, 1048608, -2147450848, 0, -2147483648, 32768, 1081376, -2146435072, 1048608, -2147483616, 0, 1081344, 32800, -2146402304, -2146435072, 32800, 0, 1081376, -2146435040, 1048576, -2147450848, -2146435072, -2146402304, 32768, -2146435072, -2147450880, 32, -2146402272, 1081376, 32, 32768, -2147483648, 32800, -2146402304, 1048576, -2147483616, 1048608, -2147450848, -2147483616, 1048608, 1081344, 0, -2147450880, 32800, -2147483648, -2146435040, -2146402272, 1081344]; + var spfunction3 = [520, 134349312, 0, 134348808, 134218240, 0, 131592, 134218240, 131080, 134217736, 134217736, 131072, 134349320, 131080, 134348800, 520, 134217728, 8, 134349312, 512, 131584, 134348800, 134348808, 131592, 134218248, 131584, 131072, 134218248, 8, 134349320, 512, 134217728, 134349312, 134217728, 131080, 520, 131072, 134349312, 134218240, 0, 512, 131080, 134349320, 134218240, 134217736, 512, 0, 134348808, 134218248, 131072, 134217728, 134349320, 8, 131592, 131584, 134217736, 134348800, 134218248, 520, 134348800, 131592, 8, 134348808, 131584]; + var spfunction4 = [8396801, 8321, 8321, 128, 8396928, 8388737, 8388609, 8193, 0, 8396800, 8396800, 8396929, 129, 0, 8388736, 8388609, 1, 8192, 8388608, 8396801, 128, 8388608, 8193, 8320, 8388737, 1, 8320, 8388736, 8192, 8396928, 8396929, 129, 8388736, 8388609, 8396800, 8396929, 129, 0, 0, 8396800, 8320, 8388736, 8388737, 1, 8396801, 8321, 8321, 128, 8396929, 129, 1, 8192, 8388609, 8193, 8396928, 8388737, 8193, 8320, 8388608, 8396801, 128, 8388608, 8192, 8396928]; + var spfunction5 = [256, 34078976, 34078720, 1107296512, 524288, 256, 1073741824, 34078720, 1074266368, 524288, 33554688, 1074266368, 1107296512, 1107820544, 524544, 1073741824, 33554432, 1074266112, 1074266112, 0, 1073742080, 1107820800, 1107820800, 33554688, 1107820544, 1073742080, 0, 1107296256, 34078976, 33554432, 1107296256, 524544, 524288, 1107296512, 256, 33554432, 1073741824, 34078720, 1107296512, 1074266368, 33554688, 1073741824, 1107820544, 34078976, 1074266368, 256, 33554432, 1107820544, 1107820800, 524544, 1107296256, 1107820800, 34078720, 0, 1074266112, 1107296256, 524544, 33554688, 1073742080, 524288, 0, 1074266112, 34078976, 1073742080]; + var spfunction6 = [536870928, 541065216, 16384, 541081616, 541065216, 16, 541081616, 4194304, 536887296, 4210704, 4194304, 536870928, 4194320, 536887296, 536870912, 16400, 0, 4194320, 536887312, 16384, 4210688, 536887312, 16, 541065232, 541065232, 0, 4210704, 541081600, 16400, 4210688, 541081600, 536870912, 536887296, 16, 541065232, 4210688, 541081616, 4194304, 16400, 536870928, 4194304, 536887296, 536870912, 16400, 536870928, 541081616, 4210688, 541065216, 4210704, 541081600, 0, 541065232, 16, 16384, 541065216, 4210704, 16384, 4194320, 536887312, 0, 541081600, 536870912, 4194320, 536887312]; + var spfunction7 = [2097152, 69206018, 67110914, 0, 2048, 67110914, 2099202, 69208064, 69208066, 2097152, 0, 67108866, 2, 67108864, 69206018, 2050, 67110912, 2099202, 2097154, 67110912, 67108866, 69206016, 69208064, 2097154, 69206016, 2048, 2050, 69208066, 2099200, 2, 67108864, 2099200, 67108864, 2099200, 2097152, 67110914, 67110914, 69206018, 69206018, 2, 2097154, 67108864, 67110912, 2097152, 69208064, 2050, 2099202, 69208064, 2050, 67108866, 69208066, 69206016, 2099200, 0, 2, 69208066, 0, 2099202, 69206016, 2048, 67108866, 67110912, 2048, 2097154]; + var spfunction8 = [268439616, 4096, 262144, 268701760, 268435456, 268439616, 64, 268435456, 262208, 268697600, 268701760, 266240, 268701696, 266304, 4096, 64, 268697600, 268435520, 268439552, 4160, 266240, 262208, 268697664, 268701696, 4160, 0, 0, 268697664, 268435520, 268439552, 266304, 262144, 266304, 262144, 268701696, 4096, 64, 268697664, 4096, 266304, 268439552, 64, 268435520, 268697600, 268697664, 268435456, 262144, 268439616, 0, 268701760, 262208, 268435520, 268697600, 268439552, 268439616, 0, 268701760, 266240, 266240, 4160, 4160, 262208, 268435456, 268701696]; + function _createKeys(key) { + var pc2bytes0 = [0, 4, 536870912, 536870916, 65536, 65540, 536936448, 536936452, 512, 516, 536871424, 536871428, 66048, 66052, 536936960, 536936964], pc2bytes1 = [0, 1, 1048576, 1048577, 67108864, 67108865, 68157440, 68157441, 256, 257, 1048832, 1048833, 67109120, 67109121, 68157696, 68157697], pc2bytes2 = [0, 8, 2048, 2056, 16777216, 16777224, 16779264, 16779272, 0, 8, 2048, 2056, 16777216, 16777224, 16779264, 16779272], pc2bytes3 = [0, 2097152, 134217728, 136314880, 8192, 2105344, 134225920, 136323072, 131072, 2228224, 134348800, 136445952, 139264, 2236416, 134356992, 136454144], pc2bytes4 = [0, 262144, 16, 262160, 0, 262144, 16, 262160, 4096, 266240, 4112, 266256, 4096, 266240, 4112, 266256], pc2bytes5 = [0, 1024, 32, 1056, 0, 1024, 32, 1056, 33554432, 33555456, 33554464, 33555488, 33554432, 33555456, 33554464, 33555488], pc2bytes6 = [0, 268435456, 524288, 268959744, 2, 268435458, 524290, 268959746, 0, 268435456, 524288, 268959744, 2, 268435458, 524290, 268959746], pc2bytes7 = [0, 65536, 2048, 67584, 536870912, 536936448, 536872960, 536938496, 131072, 196608, 133120, 198656, 537001984, 537067520, 537004032, 537069568], pc2bytes8 = [0, 262144, 0, 262144, 2, 262146, 2, 262146, 33554432, 33816576, 33554432, 33816576, 33554434, 33816578, 33554434, 33816578], pc2bytes9 = [0, 268435456, 8, 268435464, 0, 268435456, 8, 268435464, 1024, 268436480, 1032, 268436488, 1024, 268436480, 1032, 268436488], pc2bytes10 = [0, 32, 0, 32, 1048576, 1048608, 1048576, 1048608, 8192, 8224, 8192, 8224, 1056768, 1056800, 1056768, 1056800], pc2bytes11 = [0, 16777216, 512, 16777728, 2097152, 18874368, 2097664, 18874880, 67108864, 83886080, 67109376, 83886592, 69206016, 85983232, 69206528, 85983744], pc2bytes12 = [0, 4096, 134217728, 134221824, 524288, 528384, 134742016, 134746112, 16, 4112, 134217744, 134221840, 524304, 528400, 134742032, 134746128], pc2bytes13 = [0, 4, 256, 260, 0, 4, 256, 260, 1, 5, 257, 261, 1, 5, 257, 261]; + var iterations = key.length() > 8 ? 3 : 1; + var keys = []; + var shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0]; + var n = 0, tmp; + for (var j = 0; j < iterations; j++) { + var left = key.getInt32(); + var right = key.getInt32(); + tmp = (left >>> 4 ^ right) & 252645135; + right ^= tmp; + left ^= tmp << 4; + tmp = (right >>> -16 ^ left) & 65535; + left ^= tmp; + right ^= tmp << -16; + tmp = (left >>> 2 ^ right) & 858993459; + right ^= tmp; + left ^= tmp << 2; + tmp = (right >>> -16 ^ left) & 65535; + left ^= tmp; + right ^= tmp << -16; + tmp = (left >>> 1 ^ right) & 1431655765; + right ^= tmp; + left ^= tmp << 1; + tmp = (right >>> 8 ^ left) & 16711935; + left ^= tmp; + right ^= tmp << 8; + tmp = (left >>> 1 ^ right) & 1431655765; + right ^= tmp; + left ^= tmp << 1; + tmp = left << 8 | right >>> 20 & 240; + left = right << 24 | right << 8 & 16711680 | right >>> 8 & 65280 | right >>> 24 & 240; + right = tmp; + for (var i = 0; i < shifts.length; ++i) { + if (shifts[i]) { + left = left << 2 | left >>> 26; + right = right << 2 | right >>> 26; + } else { + left = left << 1 | left >>> 27; + right = right << 1 | right >>> 27; + } + left &= -15; + right &= -15; + var lefttmp = pc2bytes0[left >>> 28] | pc2bytes1[left >>> 24 & 15] | pc2bytes2[left >>> 20 & 15] | pc2bytes3[left >>> 16 & 15] | pc2bytes4[left >>> 12 & 15] | pc2bytes5[left >>> 8 & 15] | pc2bytes6[left >>> 4 & 15]; + var righttmp = pc2bytes7[right >>> 28] | pc2bytes8[right >>> 24 & 15] | pc2bytes9[right >>> 20 & 15] | pc2bytes10[right >>> 16 & 15] | pc2bytes11[right >>> 12 & 15] | pc2bytes12[right >>> 8 & 15] | pc2bytes13[right >>> 4 & 15]; + tmp = (righttmp >>> 16 ^ lefttmp) & 65535; + keys[n++] = lefttmp ^ tmp; + keys[n++] = righttmp ^ tmp << 16; + } + } + return keys; + } + function _updateBlock(keys, input, output, decrypt) { + var iterations = keys.length === 32 ? 3 : 9; + var looping; + if (iterations === 3) { + looping = decrypt ? [30, -2, -2] : [0, 32, 2]; + } else { + looping = decrypt ? [94, 62, -2, 32, 64, 2, 30, -2, -2] : [0, 32, 2, 62, 30, -2, 64, 96, 2]; + } + var tmp; + var left = input[0]; + var right = input[1]; + tmp = (left >>> 4 ^ right) & 252645135; + right ^= tmp; + left ^= tmp << 4; + tmp = (left >>> 16 ^ right) & 65535; + right ^= tmp; + left ^= tmp << 16; + tmp = (right >>> 2 ^ left) & 858993459; + left ^= tmp; + right ^= tmp << 2; + tmp = (right >>> 8 ^ left) & 16711935; + left ^= tmp; + right ^= tmp << 8; + tmp = (left >>> 1 ^ right) & 1431655765; + right ^= tmp; + left ^= tmp << 1; + left = left << 1 | left >>> 31; + right = right << 1 | right >>> 31; + for (var j = 0; j < iterations; j += 3) { + var endloop = looping[j + 1]; + var loopinc = looping[j + 2]; + for (var i = looping[j]; i != endloop; i += loopinc) { + var right1 = right ^ keys[i]; + var right2 = (right >>> 4 | right << 28) ^ keys[i + 1]; + tmp = left; + left = right; + right = tmp ^ (spfunction2[right1 >>> 24 & 63] | spfunction4[right1 >>> 16 & 63] | spfunction6[right1 >>> 8 & 63] | spfunction8[right1 & 63] | spfunction1[right2 >>> 24 & 63] | spfunction3[right2 >>> 16 & 63] | spfunction5[right2 >>> 8 & 63] | spfunction7[right2 & 63]); + } + tmp = left; + left = right; + right = tmp; + } + left = left >>> 1 | left << 31; + right = right >>> 1 | right << 31; + tmp = (left >>> 1 ^ right) & 1431655765; + right ^= tmp; + left ^= tmp << 1; + tmp = (right >>> 8 ^ left) & 16711935; + left ^= tmp; + right ^= tmp << 8; + tmp = (right >>> 2 ^ left) & 858993459; + left ^= tmp; + right ^= tmp << 2; + tmp = (left >>> 16 ^ right) & 65535; + right ^= tmp; + left ^= tmp << 16; + tmp = (left >>> 4 ^ right) & 252645135; + right ^= tmp; + left ^= tmp << 4; + output[0] = left; + output[1] = right; + } + function _createCipher(options) { + options = options || {}; + var mode = (options.mode || "CBC").toUpperCase(); + var algorithm = "DES-" + mode; + var cipher; + if (options.decrypt) { + cipher = forge.cipher.createDecipher(algorithm, options.key); + } else { + cipher = forge.cipher.createCipher(algorithm, options.key); + } + var start = cipher.start; + cipher.start = function(iv, options2) { + var output = null; + if (options2 instanceof forge.util.ByteBuffer) { + output = options2; + options2 = {}; + } + options2 = options2 || {}; + options2.output = output; + options2.iv = iv; + start.call(cipher, options2); + }; + return cipher; + } + } +}); + +// node_modules/node-forge/lib/pbkdf2.js +var require_pbkdf2 = __commonJS({ + "node_modules/node-forge/lib/pbkdf2.js"(exports2, module2) { + var forge = require_forge(); + require_hmac(); + require_md(); + require_util13(); + var pkcs5 = forge.pkcs5 = forge.pkcs5 || {}; + var crypto; + if (forge.util.isNodejs && !forge.options.usePureJavaScript) { + crypto = require("crypto"); + } + module2.exports = forge.pbkdf2 = pkcs5.pbkdf2 = function(p, s, c, dkLen, md2, callback) { + if (typeof md2 === "function") { + callback = md2; + md2 = null; + } + if (forge.util.isNodejs && !forge.options.usePureJavaScript && crypto.pbkdf2 && (md2 === null || typeof md2 !== "object") && (crypto.pbkdf2Sync.length > 4 || (!md2 || md2 === "sha1"))) { + if (typeof md2 !== "string") { + md2 = "sha1"; + } + p = Buffer.from(p, "binary"); + s = Buffer.from(s, "binary"); + if (!callback) { + if (crypto.pbkdf2Sync.length === 4) { + return crypto.pbkdf2Sync(p, s, c, dkLen).toString("binary"); + } + return crypto.pbkdf2Sync(p, s, c, dkLen, md2).toString("binary"); + } + if (crypto.pbkdf2Sync.length === 4) { + return crypto.pbkdf2(p, s, c, dkLen, function(err2, key) { + if (err2) { + return callback(err2); + } + callback(null, key.toString("binary")); + }); + } + return crypto.pbkdf2(p, s, c, dkLen, md2, function(err2, key) { + if (err2) { + return callback(err2); + } + callback(null, key.toString("binary")); + }); + } + if (typeof md2 === "undefined" || md2 === null) { + md2 = "sha1"; + } + if (typeof md2 === "string") { + if (!(md2 in forge.md.algorithms)) { + throw new Error("Unknown hash algorithm: " + md2); + } + md2 = forge.md[md2].create(); + } + var hLen = md2.digestLength; + if (dkLen > 4294967295 * hLen) { + var err = new Error("Derived key is too long."); + if (callback) { + return callback(err); + } + throw err; + } + var len = Math.ceil(dkLen / hLen); + var r = dkLen - (len - 1) * hLen; + var prf = forge.hmac.create(); + prf.start(md2, p); + var dk = ""; + var xor, u_c, u_c1; + if (!callback) { + for (var i = 1; i <= len; ++i) { + prf.start(null, null); + prf.update(s); + prf.update(forge.util.int32ToBytes(i)); + xor = u_c1 = prf.digest().getBytes(); + for (var j = 2; j <= c; ++j) { + prf.start(null, null); + prf.update(u_c1); + u_c = prf.digest().getBytes(); + xor = forge.util.xorBytes(xor, u_c, hLen); + u_c1 = u_c; + } + dk += i < len ? xor : xor.substr(0, r); + } + return dk; + } + var i = 1, j; + function outer() { + if (i > len) { + return callback(null, dk); + } + prf.start(null, null); + prf.update(s); + prf.update(forge.util.int32ToBytes(i)); + xor = u_c1 = prf.digest().getBytes(); + j = 2; + inner(); + } + function inner() { + if (j <= c) { + prf.start(null, null); + prf.update(u_c1); + u_c = prf.digest().getBytes(); + xor = forge.util.xorBytes(xor, u_c, hLen); + u_c1 = u_c; + ++j; + return forge.util.setImmediate(inner); + } + dk += i < len ? xor : xor.substr(0, r); + ++i; + outer(); + } + outer(); + }; + } +}); + +// node_modules/node-forge/lib/sha256.js +var require_sha256 = __commonJS({ + "node_modules/node-forge/lib/sha256.js"(exports2, module2) { + var forge = require_forge(); + require_md(); + require_util13(); + var sha256 = module2.exports = forge.sha256 = forge.sha256 || {}; + forge.md.sha256 = forge.md.algorithms.sha256 = sha256; + sha256.create = function() { + if (!_initialized) { + _init(); + } + var _state = null; + var _input = forge.util.createBuffer(); + var _w = new Array(64); + var md2 = { + algorithm: "sha256", + blockLength: 64, + digestLength: 32, + // 56-bit length of message so far (does not including padding) + messageLength: 0, + // true message length + fullMessageLength: null, + // size of message length in bytes + messageLengthSize: 8 + }; + md2.start = function() { + md2.messageLength = 0; + md2.fullMessageLength = md2.messageLength64 = []; + var int32s = md2.messageLengthSize / 4; + for (var i = 0; i < int32s; ++i) { + md2.fullMessageLength.push(0); + } + _input = forge.util.createBuffer(); + _state = { + h0: 1779033703, + h1: 3144134277, + h2: 1013904242, + h3: 2773480762, + h4: 1359893119, + h5: 2600822924, + h6: 528734635, + h7: 1541459225 + }; + return md2; + }; + md2.start(); + md2.update = function(msg, encoding) { + if (encoding === "utf8") { + msg = forge.util.encodeUtf8(msg); + } + var len = msg.length; + md2.messageLength += len; + len = [len / 4294967296 >>> 0, len >>> 0]; + for (var i = md2.fullMessageLength.length - 1; i >= 0; --i) { + md2.fullMessageLength[i] += len[1]; + len[1] = len[0] + (md2.fullMessageLength[i] / 4294967296 >>> 0); + md2.fullMessageLength[i] = md2.fullMessageLength[i] >>> 0; + len[0] = len[1] / 4294967296 >>> 0; + } + _input.putBytes(msg); + _update(_state, _w, _input); + if (_input.read > 2048 || _input.length() === 0) { + _input.compact(); + } + return md2; + }; + md2.digest = function() { + var finalBlock = forge.util.createBuffer(); + finalBlock.putBytes(_input.bytes()); + var remaining = md2.fullMessageLength[md2.fullMessageLength.length - 1] + md2.messageLengthSize; + var overflow = remaining & md2.blockLength - 1; + finalBlock.putBytes(_padding.substr(0, md2.blockLength - overflow)); + var next, carry; + var bits = md2.fullMessageLength[0] * 8; + for (var i = 0; i < md2.fullMessageLength.length - 1; ++i) { + next = md2.fullMessageLength[i + 1] * 8; + carry = next / 4294967296 >>> 0; + bits += carry; + finalBlock.putInt32(bits >>> 0); + bits = next >>> 0; + } + finalBlock.putInt32(bits); + var s2 = { + h0: _state.h0, + h1: _state.h1, + h2: _state.h2, + h3: _state.h3, + h4: _state.h4, + h5: _state.h5, + h6: _state.h6, + h7: _state.h7 + }; + _update(s2, _w, finalBlock); + var rval = forge.util.createBuffer(); + rval.putInt32(s2.h0); + rval.putInt32(s2.h1); + rval.putInt32(s2.h2); + rval.putInt32(s2.h3); + rval.putInt32(s2.h4); + rval.putInt32(s2.h5); + rval.putInt32(s2.h6); + rval.putInt32(s2.h7); + return rval; + }; + return md2; + }; + var _padding = null; + var _initialized = false; + var _k = null; + function _init() { + _padding = String.fromCharCode(128); + _padding += forge.util.fillString(String.fromCharCode(0), 64); + _k = [ + 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 + ]; + _initialized = true; + } + function _update(s, w, bytes) { + var t1, t2, s0, s1, ch, maj, i, a, b, c, d, e, f, g, h; + var len = bytes.length(); + while (len >= 64) { + for (i = 0; i < 16; ++i) { + w[i] = bytes.getInt32(); + } + for (; i < 64; ++i) { + t1 = w[i - 2]; + t1 = (t1 >>> 17 | t1 << 15) ^ (t1 >>> 19 | t1 << 13) ^ t1 >>> 10; + t2 = w[i - 15]; + t2 = (t2 >>> 7 | t2 << 25) ^ (t2 >>> 18 | t2 << 14) ^ t2 >>> 3; + w[i] = t1 + w[i - 7] + t2 + w[i - 16] | 0; + } + a = s.h0; + b = s.h1; + c = s.h2; + d = s.h3; + e = s.h4; + f = s.h5; + g = s.h6; + h = s.h7; + for (i = 0; i < 64; ++i) { + s1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7); + ch = g ^ e & (f ^ g); + s0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10); + maj = a & b | c & (a ^ b); + t1 = h + s1 + ch + _k[i] + w[i]; + t2 = s0 + maj; + h = g; + g = f; + f = e; + e = d + t1 >>> 0; + d = c; + c = b; + b = a; + a = t1 + t2 >>> 0; + } + s.h0 = s.h0 + a | 0; + s.h1 = s.h1 + b | 0; + s.h2 = s.h2 + c | 0; + s.h3 = s.h3 + d | 0; + s.h4 = s.h4 + e | 0; + s.h5 = s.h5 + f | 0; + s.h6 = s.h6 + g | 0; + s.h7 = s.h7 + h | 0; + len -= 64; + } + } + } +}); + +// node_modules/node-forge/lib/prng.js +var require_prng = __commonJS({ + "node_modules/node-forge/lib/prng.js"(exports2, module2) { + var forge = require_forge(); + require_util13(); + var _crypto = null; + if (forge.util.isNodejs && !forge.options.usePureJavaScript && !process.versions["node-webkit"]) { + _crypto = require("crypto"); + } + var prng = module2.exports = forge.prng = forge.prng || {}; + prng.create = function(plugin) { + var ctx = { + plugin, + key: null, + seed: null, + time: null, + // number of reseeds so far + reseeds: 0, + // amount of data generated so far + generated: 0, + // no initial key bytes + keyBytes: "" + }; + var md2 = plugin.md; + var pools = new Array(32); + for (var i = 0; i < 32; ++i) { + pools[i] = md2.create(); + } + ctx.pools = pools; + ctx.pool = 0; + ctx.generate = function(count, callback) { + if (!callback) { + return ctx.generateSync(count); + } + var cipher = ctx.plugin.cipher; + var increment = ctx.plugin.increment; + var formatKey = ctx.plugin.formatKey; + var formatSeed = ctx.plugin.formatSeed; + var b = forge.util.createBuffer(); + ctx.key = null; + generate(); + function generate(err) { + if (err) { + return callback(err); + } + if (b.length() >= count) { + return callback(null, b.getBytes(count)); + } + if (ctx.generated > 1048575) { + ctx.key = null; + } + if (ctx.key === null) { + return forge.util.nextTick(function() { + _reseed(generate); + }); + } + var bytes = cipher(ctx.key, ctx.seed); + ctx.generated += bytes.length; + b.putBytes(bytes); + ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed))); + ctx.seed = formatSeed(cipher(ctx.key, ctx.seed)); + forge.util.setImmediate(generate); + } + }; + ctx.generateSync = function(count) { + var cipher = ctx.plugin.cipher; + var increment = ctx.plugin.increment; + var formatKey = ctx.plugin.formatKey; + var formatSeed = ctx.plugin.formatSeed; + ctx.key = null; + var b = forge.util.createBuffer(); + while (b.length() < count) { + if (ctx.generated > 1048575) { + ctx.key = null; + } + if (ctx.key === null) { + _reseedSync(); + } + var bytes = cipher(ctx.key, ctx.seed); + ctx.generated += bytes.length; + b.putBytes(bytes); + ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed))); + ctx.seed = formatSeed(cipher(ctx.key, ctx.seed)); + } + return b.getBytes(count); + }; + function _reseed(callback) { + if (ctx.pools[0].messageLength >= 32) { + _seed(); + return callback(); + } + var needed = 32 - ctx.pools[0].messageLength << 5; + ctx.seedFile(needed, function(err, bytes) { + if (err) { + return callback(err); + } + ctx.collect(bytes); + _seed(); + callback(); + }); + } + function _reseedSync() { + if (ctx.pools[0].messageLength >= 32) { + return _seed(); + } + var needed = 32 - ctx.pools[0].messageLength << 5; + ctx.collect(ctx.seedFileSync(needed)); + _seed(); + } + function _seed() { + ctx.reseeds = ctx.reseeds === 4294967295 ? 0 : ctx.reseeds + 1; + var md3 = ctx.plugin.md.create(); + md3.update(ctx.keyBytes); + var _2powK = 1; + for (var k = 0; k < 32; ++k) { + if (ctx.reseeds % _2powK === 0) { + md3.update(ctx.pools[k].digest().getBytes()); + ctx.pools[k].start(); + } + _2powK = _2powK << 1; + } + ctx.keyBytes = md3.digest().getBytes(); + md3.start(); + md3.update(ctx.keyBytes); + var seedBytes = md3.digest().getBytes(); + ctx.key = ctx.plugin.formatKey(ctx.keyBytes); + ctx.seed = ctx.plugin.formatSeed(seedBytes); + ctx.generated = 0; + } + function defaultSeedFile(needed) { + var getRandomValues = null; + var globalScope = forge.util.globalScope; + var _crypto2 = globalScope.crypto || globalScope.msCrypto; + if (_crypto2 && _crypto2.getRandomValues) { + getRandomValues = function(arr) { + return _crypto2.getRandomValues(arr); + }; + } + var b = forge.util.createBuffer(); + if (getRandomValues) { + while (b.length() < needed) { + var count = Math.max(1, Math.min(needed - b.length(), 65536) / 4); + var entropy = new Uint32Array(Math.floor(count)); + try { + getRandomValues(entropy); + for (var i2 = 0; i2 < entropy.length; ++i2) { + b.putInt32(entropy[i2]); + } + } catch (e) { + if (!(typeof QuotaExceededError !== "undefined" && e instanceof QuotaExceededError)) { + throw e; + } + } + } + } + if (b.length() < needed) { + var hi, lo, next; + var seed = Math.floor(Math.random() * 65536); + while (b.length() < needed) { + lo = 16807 * (seed & 65535); + hi = 16807 * (seed >> 16); + lo += (hi & 32767) << 16; + lo += hi >> 15; + lo = (lo & 2147483647) + (lo >> 31); + seed = lo & 4294967295; + for (var i2 = 0; i2 < 3; ++i2) { + next = seed >>> (i2 << 3); + next ^= Math.floor(Math.random() * 256); + b.putByte(next & 255); + } + } + } + return b.getBytes(needed); + } + if (_crypto) { + ctx.seedFile = function(needed, callback) { + _crypto.randomBytes(needed, function(err, bytes) { + if (err) { + return callback(err); + } + callback(null, bytes.toString()); + }); + }; + ctx.seedFileSync = function(needed) { + return _crypto.randomBytes(needed).toString(); + }; + } else { + ctx.seedFile = function(needed, callback) { + try { + callback(null, defaultSeedFile(needed)); + } catch (e) { + callback(e); + } + }; + ctx.seedFileSync = defaultSeedFile; + } + ctx.collect = function(bytes) { + var count = bytes.length; + for (var i2 = 0; i2 < count; ++i2) { + ctx.pools[ctx.pool].update(bytes.substr(i2, 1)); + ctx.pool = ctx.pool === 31 ? 0 : ctx.pool + 1; + } + }; + ctx.collectInt = function(i2, n) { + var bytes = ""; + for (var x = 0; x < n; x += 8) { + bytes += String.fromCharCode(i2 >> x & 255); + } + ctx.collect(bytes); + }; + ctx.registerWorker = function(worker) { + if (worker === self) { + ctx.seedFile = function(needed, callback) { + function listener2(e) { + var data = e.data; + if (data.forge && data.forge.prng) { + self.removeEventListener("message", listener2); + callback(data.forge.prng.err, data.forge.prng.bytes); + } + } + self.addEventListener("message", listener2); + self.postMessage({ forge: { prng: { needed } } }); + }; + } else { + var listener = function(e) { + var data = e.data; + if (data.forge && data.forge.prng) { + ctx.seedFile(data.forge.prng.needed, function(err, bytes) { + worker.postMessage({ forge: { prng: { err, bytes } } }); + }); + } + }; + worker.addEventListener("message", listener); + } + }; + return ctx; + }; + } +}); + +// node_modules/node-forge/lib/random.js +var require_random = __commonJS({ + "node_modules/node-forge/lib/random.js"(exports2, module2) { + var forge = require_forge(); + require_aes(); + require_sha256(); + require_prng(); + require_util13(); + (function() { + if (forge.random && forge.random.getBytes) { + module2.exports = forge.random; + return; + } + (function(jQuery2) { + var prng_aes = {}; + var _prng_aes_output = new Array(4); + var _prng_aes_buffer = forge.util.createBuffer(); + prng_aes.formatKey = function(key2) { + var tmp = forge.util.createBuffer(key2); + key2 = new Array(4); + key2[0] = tmp.getInt32(); + key2[1] = tmp.getInt32(); + key2[2] = tmp.getInt32(); + key2[3] = tmp.getInt32(); + return forge.aes._expandKey(key2, false); + }; + prng_aes.formatSeed = function(seed) { + var tmp = forge.util.createBuffer(seed); + seed = new Array(4); + seed[0] = tmp.getInt32(); + seed[1] = tmp.getInt32(); + seed[2] = tmp.getInt32(); + seed[3] = tmp.getInt32(); + return seed; + }; + prng_aes.cipher = function(key2, seed) { + forge.aes._updateBlock(key2, seed, _prng_aes_output, false); + _prng_aes_buffer.putInt32(_prng_aes_output[0]); + _prng_aes_buffer.putInt32(_prng_aes_output[1]); + _prng_aes_buffer.putInt32(_prng_aes_output[2]); + _prng_aes_buffer.putInt32(_prng_aes_output[3]); + return _prng_aes_buffer.getBytes(); + }; + prng_aes.increment = function(seed) { + ++seed[3]; + return seed; + }; + prng_aes.md = forge.md.sha256; + function spawnPrng() { + var ctx = forge.prng.create(prng_aes); + ctx.getBytes = function(count, callback) { + return ctx.generate(count, callback); + }; + ctx.getBytesSync = function(count) { + return ctx.generate(count); + }; + return ctx; + } + var _ctx = spawnPrng(); + var getRandomValues = null; + var globalScope = forge.util.globalScope; + var _crypto = globalScope.crypto || globalScope.msCrypto; + if (_crypto && _crypto.getRandomValues) { + getRandomValues = function(arr) { + return _crypto.getRandomValues(arr); + }; + } + if (forge.options.usePureJavaScript || !forge.util.isNodejs && !getRandomValues) { + if (typeof window === "undefined" || window.document === void 0) { + } + _ctx.collectInt(+/* @__PURE__ */ new Date(), 32); + if (typeof navigator !== "undefined") { + var _navBytes = ""; + for (var key in navigator) { + try { + if (typeof navigator[key] == "string") { + _navBytes += navigator[key]; + } + } catch (e) { + } + } + _ctx.collect(_navBytes); + _navBytes = null; + } + if (jQuery2) { + jQuery2().mousemove(function(e) { + _ctx.collectInt(e.clientX, 16); + _ctx.collectInt(e.clientY, 16); + }); + jQuery2().keypress(function(e) { + _ctx.collectInt(e.charCode, 8); + }); + } + } + if (!forge.random) { + forge.random = _ctx; + } else { + for (var key in _ctx) { + forge.random[key] = _ctx[key]; + } + } + forge.random.createInstance = spawnPrng; + module2.exports = forge.random; + })(typeof jQuery !== "undefined" ? jQuery : null); + })(); + } +}); + +// node_modules/node-forge/lib/rc2.js +var require_rc2 = __commonJS({ + "node_modules/node-forge/lib/rc2.js"(exports2, module2) { + var forge = require_forge(); + require_util13(); + var piTable = [ + 217, + 120, + 249, + 196, + 25, + 221, + 181, + 237, + 40, + 233, + 253, + 121, + 74, + 160, + 216, + 157, + 198, + 126, + 55, + 131, + 43, + 118, + 83, + 142, + 98, + 76, + 100, + 136, + 68, + 139, + 251, + 162, + 23, + 154, + 89, + 245, + 135, + 179, + 79, + 19, + 97, + 69, + 109, + 141, + 9, + 129, + 125, + 50, + 189, + 143, + 64, + 235, + 134, + 183, + 123, + 11, + 240, + 149, + 33, + 34, + 92, + 107, + 78, + 130, + 84, + 214, + 101, + 147, + 206, + 96, + 178, + 28, + 115, + 86, + 192, + 20, + 167, + 140, + 241, + 220, + 18, + 117, + 202, + 31, + 59, + 190, + 228, + 209, + 66, + 61, + 212, + 48, + 163, + 60, + 182, + 38, + 111, + 191, + 14, + 218, + 70, + 105, + 7, + 87, + 39, + 242, + 29, + 155, + 188, + 148, + 67, + 3, + 248, + 17, + 199, + 246, + 144, + 239, + 62, + 231, + 6, + 195, + 213, + 47, + 200, + 102, + 30, + 215, + 8, + 232, + 234, + 222, + 128, + 82, + 238, + 247, + 132, + 170, + 114, + 172, + 53, + 77, + 106, + 42, + 150, + 26, + 210, + 113, + 90, + 21, + 73, + 116, + 75, + 159, + 208, + 94, + 4, + 24, + 164, + 236, + 194, + 224, + 65, + 110, + 15, + 81, + 203, + 204, + 36, + 145, + 175, + 80, + 161, + 244, + 112, + 57, + 153, + 124, + 58, + 133, + 35, + 184, + 180, + 122, + 252, + 2, + 54, + 91, + 37, + 85, + 151, + 49, + 45, + 93, + 250, + 152, + 227, + 138, + 146, + 174, + 5, + 223, + 41, + 16, + 103, + 108, + 186, + 201, + 211, + 0, + 230, + 207, + 225, + 158, + 168, + 44, + 99, + 22, + 1, + 63, + 88, + 226, + 137, + 169, + 13, + 56, + 52, + 27, + 171, + 51, + 255, + 176, + 187, + 72, + 12, + 95, + 185, + 177, + 205, + 46, + 197, + 243, + 219, + 71, + 229, + 165, + 156, + 119, + 10, + 166, + 32, + 104, + 254, + 127, + 193, + 173 + ]; + var s = [1, 2, 3, 5]; + var rol = function(word, bits) { + return word << bits & 65535 | (word & 65535) >> 16 - bits; + }; + var ror = function(word, bits) { + return (word & 65535) >> bits | word << 16 - bits & 65535; + }; + module2.exports = forge.rc2 = forge.rc2 || {}; + forge.rc2.expandKey = function(key, effKeyBits) { + if (typeof key === "string") { + key = forge.util.createBuffer(key); + } + effKeyBits = effKeyBits || 128; + var L = key; + var T = key.length(); + var T1 = effKeyBits; + var T8 = Math.ceil(T1 / 8); + var TM = 255 >> (T1 & 7); + var i; + for (i = T; i < 128; i++) { + L.putByte(piTable[L.at(i - 1) + L.at(i - T) & 255]); + } + L.setAt(128 - T8, piTable[L.at(128 - T8) & TM]); + for (i = 127 - T8; i >= 0; i--) { + L.setAt(i, piTable[L.at(i + 1) ^ L.at(i + T8)]); + } + return L; + }; + var createCipher = function(key, bits, encrypt) { + var _finish = false, _input = null, _output = null, _iv = null; + var mixRound, mashRound; + var i, j, K = []; + key = forge.rc2.expandKey(key, bits); + for (i = 0; i < 64; i++) { + K.push(key.getInt16Le()); + } + if (encrypt) { + mixRound = function(R) { + for (i = 0; i < 4; i++) { + R[i] += K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) + (~R[(i + 3) % 4] & R[(i + 1) % 4]); + R[i] = rol(R[i], s[i]); + j++; + } + }; + mashRound = function(R) { + for (i = 0; i < 4; i++) { + R[i] += K[R[(i + 3) % 4] & 63]; + } + }; + } else { + mixRound = function(R) { + for (i = 3; i >= 0; i--) { + R[i] = ror(R[i], s[i]); + R[i] -= K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) + (~R[(i + 3) % 4] & R[(i + 1) % 4]); + j--; + } + }; + mashRound = function(R) { + for (i = 3; i >= 0; i--) { + R[i] -= K[R[(i + 3) % 4] & 63]; + } + }; + } + var runPlan = function(plan) { + var R = []; + for (i = 0; i < 4; i++) { + var val = _input.getInt16Le(); + if (_iv !== null) { + if (encrypt) { + val ^= _iv.getInt16Le(); + } else { + _iv.putInt16Le(val); + } + } + R.push(val & 65535); + } + j = encrypt ? 0 : 63; + for (var ptr = 0; ptr < plan.length; ptr++) { + for (var ctr = 0; ctr < plan[ptr][0]; ctr++) { + plan[ptr][1](R); + } + } + for (i = 0; i < 4; i++) { + if (_iv !== null) { + if (encrypt) { + _iv.putInt16Le(R[i]); + } else { + R[i] ^= _iv.getInt16Le(); + } + } + _output.putInt16Le(R[i]); + } + }; + var cipher = null; + cipher = { + /** + * Starts or restarts the encryption or decryption process, whichever + * was previously configured. + * + * To use the cipher in CBC mode, iv may be given either as a string + * of bytes, or as a byte buffer. For ECB mode, give null as iv. + * + * @param iv the initialization vector to use, null for ECB mode. + * @param output the output the buffer to write to, null to create one. + */ + start: function(iv, output) { + if (iv) { + if (typeof iv === "string") { + iv = forge.util.createBuffer(iv); + } + } + _finish = false; + _input = forge.util.createBuffer(); + _output = output || new forge.util.createBuffer(); + _iv = iv; + cipher.output = _output; + }, + /** + * Updates the next block. + * + * @param input the buffer to read from. + */ + update: function(input) { + if (!_finish) { + _input.putBuffer(input); + } + while (_input.length() >= 8) { + runPlan([ + [5, mixRound], + [1, mashRound], + [6, mixRound], + [1, mashRound], + [5, mixRound] + ]); + } + }, + /** + * Finishes encrypting or decrypting. + * + * @param pad a padding function to use, null for PKCS#7 padding, + * signature(blockSize, buffer, decrypt). + * + * @return true if successful, false on error. + */ + finish: function(pad) { + var rval = true; + if (encrypt) { + if (pad) { + rval = pad(8, _input, !encrypt); + } else { + var padding = _input.length() === 8 ? 8 : 8 - _input.length(); + _input.fillWithByte(padding, padding); + } + } + if (rval) { + _finish = true; + cipher.update(); + } + if (!encrypt) { + rval = _input.length() === 0; + if (rval) { + if (pad) { + rval = pad(8, _output, !encrypt); + } else { + var len = _output.length(); + var count = _output.at(len - 1); + if (count > len) { + rval = false; + } else { + _output.truncate(count); + } + } + } + } + return rval; + } + }; + return cipher; + }; + forge.rc2.startEncrypting = function(key, iv, output) { + var cipher = forge.rc2.createEncryptionCipher(key, 128); + cipher.start(iv, output); + return cipher; + }; + forge.rc2.createEncryptionCipher = function(key, bits) { + return createCipher(key, bits, true); + }; + forge.rc2.startDecrypting = function(key, iv, output) { + var cipher = forge.rc2.createDecryptionCipher(key, 128); + cipher.start(iv, output); + return cipher; + }; + forge.rc2.createDecryptionCipher = function(key, bits) { + return createCipher(key, bits, false); + }; + } +}); + +// node_modules/node-forge/lib/jsbn.js +var require_jsbn = __commonJS({ + "node_modules/node-forge/lib/jsbn.js"(exports2, module2) { + var forge = require_forge(); + module2.exports = forge.jsbn = forge.jsbn || {}; + var dbits; + var canary = 244837814094590; + var j_lm = (canary & 16777215) == 15715070; + function BigInteger(a, b, c) { + this.data = []; + if (a != null) + if ("number" == typeof a) this.fromNumber(a, b, c); + else if (b == null && "string" != typeof a) this.fromString(a, 256); + else this.fromString(a, b); + } + forge.jsbn.BigInteger = BigInteger; + function nbi() { + return new BigInteger(null); + } + function am1(i, x, w, j, c, n) { + while (--n >= 0) { + var v = x * this.data[i++] + w.data[j] + c; + c = Math.floor(v / 67108864); + w.data[j++] = v & 67108863; + } + return c; + } + function am2(i, x, w, j, c, n) { + var xl = x & 32767, xh = x >> 15; + while (--n >= 0) { + var l = this.data[i] & 32767; + var h = this.data[i++] >> 15; + var m = xh * l + h * xl; + l = xl * l + ((m & 32767) << 15) + w.data[j] + (c & 1073741823); + c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30); + w.data[j++] = l & 1073741823; + } + return c; + } + function am3(i, x, w, j, c, n) { + var xl = x & 16383, xh = x >> 14; + while (--n >= 0) { + var l = this.data[i] & 16383; + var h = this.data[i++] >> 14; + var m = xh * l + h * xl; + l = xl * l + ((m & 16383) << 14) + w.data[j] + c; + c = (l >> 28) + (m >> 14) + xh * h; + w.data[j++] = l & 268435455; + } + return c; + } + if (typeof navigator === "undefined") { + BigInteger.prototype.am = am3; + dbits = 28; + } else if (j_lm && navigator.appName == "Microsoft Internet Explorer") { + BigInteger.prototype.am = am2; + dbits = 30; + } else if (j_lm && navigator.appName != "Netscape") { + BigInteger.prototype.am = am1; + dbits = 26; + } else { + BigInteger.prototype.am = am3; + dbits = 28; + } + BigInteger.prototype.DB = dbits; + BigInteger.prototype.DM = (1 << dbits) - 1; + BigInteger.prototype.DV = 1 << dbits; + var BI_FP = 52; + BigInteger.prototype.FV = Math.pow(2, BI_FP); + BigInteger.prototype.F1 = BI_FP - dbits; + BigInteger.prototype.F2 = 2 * dbits - BI_FP; + var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; + var BI_RC = new Array(); + var rr; + var vv; + rr = "0".charCodeAt(0); + for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; + rr = "a".charCodeAt(0); + for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; + rr = "A".charCodeAt(0); + for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; + function int2char(n) { + return BI_RM.charAt(n); + } + function intAt(s, i) { + var c = BI_RC[s.charCodeAt(i)]; + return c == null ? -1 : c; + } + function bnpCopyTo(r) { + for (var i = this.t - 1; i >= 0; --i) r.data[i] = this.data[i]; + r.t = this.t; + r.s = this.s; + } + function bnpFromInt(x) { + this.t = 1; + this.s = x < 0 ? -1 : 0; + if (x > 0) this.data[0] = x; + else if (x < -1) this.data[0] = x + this.DV; + else this.t = 0; + } + function nbv(i) { + var r = nbi(); + r.fromInt(i); + return r; + } + function bnpFromString(s, b) { + var k; + if (b == 16) k = 4; + else if (b == 8) k = 3; + else if (b == 256) k = 8; + else if (b == 2) k = 1; + else if (b == 32) k = 5; + else if (b == 4) k = 2; + else { + this.fromRadix(s, b); + return; + } + this.t = 0; + this.s = 0; + var i = s.length, mi = false, sh = 0; + while (--i >= 0) { + var x = k == 8 ? s[i] & 255 : intAt(s, i); + if (x < 0) { + if (s.charAt(i) == "-") mi = true; + continue; + } + mi = false; + if (sh == 0) + this.data[this.t++] = x; + else if (sh + k > this.DB) { + this.data[this.t - 1] |= (x & (1 << this.DB - sh) - 1) << sh; + this.data[this.t++] = x >> this.DB - sh; + } else + this.data[this.t - 1] |= x << sh; + sh += k; + if (sh >= this.DB) sh -= this.DB; + } + if (k == 8 && (s[0] & 128) != 0) { + this.s = -1; + if (sh > 0) this.data[this.t - 1] |= (1 << this.DB - sh) - 1 << sh; + } + this.clamp(); + if (mi) BigInteger.ZERO.subTo(this, this); + } + function bnpClamp() { + var c = this.s & this.DM; + while (this.t > 0 && this.data[this.t - 1] == c) --this.t; + } + function bnToString(b) { + if (this.s < 0) return "-" + this.negate().toString(b); + var k; + if (b == 16) k = 4; + else if (b == 8) k = 3; + else if (b == 2) k = 1; + else if (b == 32) k = 5; + else if (b == 4) k = 2; + else return this.toRadix(b); + var km = (1 << k) - 1, d, m = false, r = "", i = this.t; + var p = this.DB - i * this.DB % k; + if (i-- > 0) { + if (p < this.DB && (d = this.data[i] >> p) > 0) { + m = true; + r = int2char(d); + } + while (i >= 0) { + if (p < k) { + d = (this.data[i] & (1 << p) - 1) << k - p; + d |= this.data[--i] >> (p += this.DB - k); + } else { + d = this.data[i] >> (p -= k) & km; + if (p <= 0) { + p += this.DB; + --i; + } + } + if (d > 0) m = true; + if (m) r += int2char(d); + } + } + return m ? r : "0"; + } + function bnNegate() { + var r = nbi(); + BigInteger.ZERO.subTo(this, r); + return r; + } + function bnAbs() { + return this.s < 0 ? this.negate() : this; + } + function bnCompareTo(a) { + var r = this.s - a.s; + if (r != 0) return r; + var i = this.t; + r = i - a.t; + if (r != 0) return this.s < 0 ? -r : r; + while (--i >= 0) if ((r = this.data[i] - a.data[i]) != 0) return r; + return 0; + } + function nbits(x) { + var r = 1, t; + if ((t = x >>> 16) != 0) { + x = t; + r += 16; + } + if ((t = x >> 8) != 0) { + x = t; + r += 8; + } + if ((t = x >> 4) != 0) { + x = t; + r += 4; + } + if ((t = x >> 2) != 0) { + x = t; + r += 2; + } + if ((t = x >> 1) != 0) { + x = t; + r += 1; + } + return r; + } + function bnBitLength() { + if (this.t <= 0) return 0; + return this.DB * (this.t - 1) + nbits(this.data[this.t - 1] ^ this.s & this.DM); + } + function bnpDLShiftTo(n, r) { + var i; + for (i = this.t - 1; i >= 0; --i) r.data[i + n] = this.data[i]; + for (i = n - 1; i >= 0; --i) r.data[i] = 0; + r.t = this.t + n; + r.s = this.s; + } + function bnpDRShiftTo(n, r) { + for (var i = n; i < this.t; ++i) r.data[i - n] = this.data[i]; + r.t = Math.max(this.t - n, 0); + r.s = this.s; + } + function bnpLShiftTo(n, r) { + var bs = n % this.DB; + var cbs = this.DB - bs; + var bm = (1 << cbs) - 1; + var ds = Math.floor(n / this.DB), c = this.s << bs & this.DM, i; + for (i = this.t - 1; i >= 0; --i) { + r.data[i + ds + 1] = this.data[i] >> cbs | c; + c = (this.data[i] & bm) << bs; + } + for (i = ds - 1; i >= 0; --i) r.data[i] = 0; + r.data[ds] = c; + r.t = this.t + ds + 1; + r.s = this.s; + r.clamp(); + } + function bnpRShiftTo(n, r) { + r.s = this.s; + var ds = Math.floor(n / this.DB); + if (ds >= this.t) { + r.t = 0; + return; + } + var bs = n % this.DB; + var cbs = this.DB - bs; + var bm = (1 << bs) - 1; + r.data[0] = this.data[ds] >> bs; + for (var i = ds + 1; i < this.t; ++i) { + r.data[i - ds - 1] |= (this.data[i] & bm) << cbs; + r.data[i - ds] = this.data[i] >> bs; + } + if (bs > 0) r.data[this.t - ds - 1] |= (this.s & bm) << cbs; + r.t = this.t - ds; + r.clamp(); + } + function bnpSubTo(a, r) { + var i = 0, c = 0, m = Math.min(a.t, this.t); + while (i < m) { + c += this.data[i] - a.data[i]; + r.data[i++] = c & this.DM; + c >>= this.DB; + } + if (a.t < this.t) { + c -= a.s; + while (i < this.t) { + c += this.data[i]; + r.data[i++] = c & this.DM; + c >>= this.DB; + } + c += this.s; + } else { + c += this.s; + while (i < a.t) { + c -= a.data[i]; + r.data[i++] = c & this.DM; + c >>= this.DB; + } + c -= a.s; + } + r.s = c < 0 ? -1 : 0; + if (c < -1) r.data[i++] = this.DV + c; + else if (c > 0) r.data[i++] = c; + r.t = i; + r.clamp(); + } + function bnpMultiplyTo(a, r) { + var x = this.abs(), y = a.abs(); + var i = x.t; + r.t = i + y.t; + while (--i >= 0) r.data[i] = 0; + for (i = 0; i < y.t; ++i) r.data[i + x.t] = x.am(0, y.data[i], r, i, 0, x.t); + r.s = 0; + r.clamp(); + if (this.s != a.s) BigInteger.ZERO.subTo(r, r); + } + function bnpSquareTo(r) { + var x = this.abs(); + var i = r.t = 2 * x.t; + while (--i >= 0) r.data[i] = 0; + for (i = 0; i < x.t - 1; ++i) { + var c = x.am(i, x.data[i], r, 2 * i, 0, 1); + if ((r.data[i + x.t] += x.am(i + 1, 2 * x.data[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { + r.data[i + x.t] -= x.DV; + r.data[i + x.t + 1] = 1; + } + } + if (r.t > 0) r.data[r.t - 1] += x.am(i, x.data[i], r, 2 * i, 0, 1); + r.s = 0; + r.clamp(); + } + function bnpDivRemTo(m, q, r) { + var pm = m.abs(); + if (pm.t <= 0) return; + var pt = this.abs(); + if (pt.t < pm.t) { + if (q != null) q.fromInt(0); + if (r != null) this.copyTo(r); + return; + } + if (r == null) r = nbi(); + var y = nbi(), ts = this.s, ms = m.s; + var nsh = this.DB - nbits(pm.data[pm.t - 1]); + if (nsh > 0) { + pm.lShiftTo(nsh, y); + pt.lShiftTo(nsh, r); + } else { + pm.copyTo(y); + pt.copyTo(r); + } + var ys = y.t; + var y0 = y.data[ys - 1]; + if (y0 == 0) return; + var yt = y0 * (1 << this.F1) + (ys > 1 ? y.data[ys - 2] >> this.F2 : 0); + var d1 = this.FV / yt, d2 = (1 << this.F1) / yt, e = 1 << this.F2; + var i = r.t, j = i - ys, t = q == null ? nbi() : q; + y.dlShiftTo(j, t); + if (r.compareTo(t) >= 0) { + r.data[r.t++] = 1; + r.subTo(t, r); + } + BigInteger.ONE.dlShiftTo(ys, t); + t.subTo(y, y); + while (y.t < ys) y.data[y.t++] = 0; + while (--j >= 0) { + var qd = r.data[--i] == y0 ? this.DM : Math.floor(r.data[i] * d1 + (r.data[i - 1] + e) * d2); + if ((r.data[i] += y.am(0, qd, r, j, 0, ys)) < qd) { + y.dlShiftTo(j, t); + r.subTo(t, r); + while (r.data[i] < --qd) r.subTo(t, r); + } + } + if (q != null) { + r.drShiftTo(ys, q); + if (ts != ms) BigInteger.ZERO.subTo(q, q); + } + r.t = ys; + r.clamp(); + if (nsh > 0) r.rShiftTo(nsh, r); + if (ts < 0) BigInteger.ZERO.subTo(r, r); + } + function bnMod(a) { + var r = nbi(); + this.abs().divRemTo(a, null, r); + if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r); + return r; + } + function Classic(m) { + this.m = m; + } + function cConvert(x) { + if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); + else return x; + } + function cRevert(x) { + return x; + } + function cReduce(x) { + x.divRemTo(this.m, null, x); + } + function cMulTo(x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); + } + function cSqrTo(x, r) { + x.squareTo(r); + this.reduce(r); + } + Classic.prototype.convert = cConvert; + Classic.prototype.revert = cRevert; + Classic.prototype.reduce = cReduce; + Classic.prototype.mulTo = cMulTo; + Classic.prototype.sqrTo = cSqrTo; + function bnpInvDigit() { + if (this.t < 1) return 0; + var x = this.data[0]; + if ((x & 1) == 0) return 0; + var y = x & 3; + y = y * (2 - (x & 15) * y) & 15; + y = y * (2 - (x & 255) * y) & 255; + y = y * (2 - ((x & 65535) * y & 65535)) & 65535; + y = y * (2 - x * y % this.DV) % this.DV; + return y > 0 ? this.DV - y : -y; + } + function Montgomery(m) { + this.m = m; + this.mp = m.invDigit(); + this.mpl = this.mp & 32767; + this.mph = this.mp >> 15; + this.um = (1 << m.DB - 15) - 1; + this.mt2 = 2 * m.t; + } + function montConvert(x) { + var r = nbi(); + x.abs().dlShiftTo(this.m.t, r); + r.divRemTo(this.m, null, r); + if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r); + return r; + } + function montRevert(x) { + var r = nbi(); + x.copyTo(r); + this.reduce(r); + return r; + } + function montReduce(x) { + while (x.t <= this.mt2) + x.data[x.t++] = 0; + for (var i = 0; i < this.m.t; ++i) { + var j = x.data[i] & 32767; + var u0 = j * this.mpl + ((j * this.mph + (x.data[i] >> 15) * this.mpl & this.um) << 15) & x.DM; + j = i + this.m.t; + x.data[j] += this.m.am(0, u0, x, i, 0, this.m.t); + while (x.data[j] >= x.DV) { + x.data[j] -= x.DV; + x.data[++j]++; + } + } + x.clamp(); + x.drShiftTo(this.m.t, x); + if (x.compareTo(this.m) >= 0) x.subTo(this.m, x); + } + function montSqrTo(x, r) { + x.squareTo(r); + this.reduce(r); + } + function montMulTo(x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); + } + Montgomery.prototype.convert = montConvert; + Montgomery.prototype.revert = montRevert; + Montgomery.prototype.reduce = montReduce; + Montgomery.prototype.mulTo = montMulTo; + Montgomery.prototype.sqrTo = montSqrTo; + function bnpIsEven() { + return (this.t > 0 ? this.data[0] & 1 : this.s) == 0; + } + function bnpExp(e, z) { + if (e > 4294967295 || e < 1) return BigInteger.ONE; + var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e) - 1; + g.copyTo(r); + while (--i >= 0) { + z.sqrTo(r, r2); + if ((e & 1 << i) > 0) z.mulTo(r2, g, r); + else { + var t = r; + r = r2; + r2 = t; + } + } + return z.revert(r); + } + function bnModPowInt(e, m) { + var z; + if (e < 256 || m.isEven()) z = new Classic(m); + else z = new Montgomery(m); + return this.exp(e, z); + } + BigInteger.prototype.copyTo = bnpCopyTo; + BigInteger.prototype.fromInt = bnpFromInt; + BigInteger.prototype.fromString = bnpFromString; + BigInteger.prototype.clamp = bnpClamp; + BigInteger.prototype.dlShiftTo = bnpDLShiftTo; + BigInteger.prototype.drShiftTo = bnpDRShiftTo; + BigInteger.prototype.lShiftTo = bnpLShiftTo; + BigInteger.prototype.rShiftTo = bnpRShiftTo; + BigInteger.prototype.subTo = bnpSubTo; + BigInteger.prototype.multiplyTo = bnpMultiplyTo; + BigInteger.prototype.squareTo = bnpSquareTo; + BigInteger.prototype.divRemTo = bnpDivRemTo; + BigInteger.prototype.invDigit = bnpInvDigit; + BigInteger.prototype.isEven = bnpIsEven; + BigInteger.prototype.exp = bnpExp; + BigInteger.prototype.toString = bnToString; + BigInteger.prototype.negate = bnNegate; + BigInteger.prototype.abs = bnAbs; + BigInteger.prototype.compareTo = bnCompareTo; + BigInteger.prototype.bitLength = bnBitLength; + BigInteger.prototype.mod = bnMod; + BigInteger.prototype.modPowInt = bnModPowInt; + BigInteger.ZERO = nbv(0); + BigInteger.ONE = nbv(1); + function bnClone() { + var r = nbi(); + this.copyTo(r); + return r; + } + function bnIntValue() { + if (this.s < 0) { + if (this.t == 1) return this.data[0] - this.DV; + else if (this.t == 0) return -1; + } else if (this.t == 1) return this.data[0]; + else if (this.t == 0) return 0; + return (this.data[1] & (1 << 32 - this.DB) - 1) << this.DB | this.data[0]; + } + function bnByteValue() { + return this.t == 0 ? this.s : this.data[0] << 24 >> 24; + } + function bnShortValue() { + return this.t == 0 ? this.s : this.data[0] << 16 >> 16; + } + function bnpChunkSize(r) { + return Math.floor(Math.LN2 * this.DB / Math.log(r)); + } + function bnSigNum() { + if (this.s < 0) return -1; + else if (this.t <= 0 || this.t == 1 && this.data[0] <= 0) return 0; + else return 1; + } + function bnpToRadix(b) { + if (b == null) b = 10; + if (this.signum() == 0 || b < 2 || b > 36) return "0"; + var cs = this.chunkSize(b); + var a = Math.pow(b, cs); + var d = nbv(a), y = nbi(), z = nbi(), r = ""; + this.divRemTo(d, y, z); + while (y.signum() > 0) { + r = (a + z.intValue()).toString(b).substr(1) + r; + y.divRemTo(d, y, z); + } + return z.intValue().toString(b) + r; + } + function bnpFromRadix(s, b) { + this.fromInt(0); + if (b == null) b = 10; + var cs = this.chunkSize(b); + var d = Math.pow(b, cs), mi = false, j = 0, w = 0; + for (var i = 0; i < s.length; ++i) { + var x = intAt(s, i); + if (x < 0) { + if (s.charAt(i) == "-" && this.signum() == 0) mi = true; + continue; + } + w = b * w + x; + if (++j >= cs) { + this.dMultiply(d); + this.dAddOffset(w, 0); + j = 0; + w = 0; + } + } + if (j > 0) { + this.dMultiply(Math.pow(b, j)); + this.dAddOffset(w, 0); + } + if (mi) BigInteger.ZERO.subTo(this, this); + } + function bnpFromNumber(a, b, c) { + if ("number" == typeof b) { + if (a < 2) this.fromInt(1); + else { + this.fromNumber(a, c); + if (!this.testBit(a - 1)) + this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this); + if (this.isEven()) this.dAddOffset(1, 0); + while (!this.isProbablePrime(b)) { + this.dAddOffset(2, 0); + if (this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a - 1), this); + } + } + } else { + var x = new Array(), t = a & 7; + x.length = (a >> 3) + 1; + b.nextBytes(x); + if (t > 0) x[0] &= (1 << t) - 1; + else x[0] = 0; + this.fromString(x, 256); + } + } + function bnToByteArray() { + var i = this.t, r = new Array(); + r[0] = this.s; + var p = this.DB - i * this.DB % 8, d, k = 0; + if (i-- > 0) { + if (p < this.DB && (d = this.data[i] >> p) != (this.s & this.DM) >> p) + r[k++] = d | this.s << this.DB - p; + while (i >= 0) { + if (p < 8) { + d = (this.data[i] & (1 << p) - 1) << 8 - p; + d |= this.data[--i] >> (p += this.DB - 8); + } else { + d = this.data[i] >> (p -= 8) & 255; + if (p <= 0) { + p += this.DB; + --i; + } + } + if ((d & 128) != 0) d |= -256; + if (k == 0 && (this.s & 128) != (d & 128)) ++k; + if (k > 0 || d != this.s) r[k++] = d; + } + } + return r; + } + function bnEquals(a) { + return this.compareTo(a) == 0; + } + function bnMin(a) { + return this.compareTo(a) < 0 ? this : a; + } + function bnMax(a) { + return this.compareTo(a) > 0 ? this : a; + } + function bnpBitwiseTo(a, op, r) { + var i, f, m = Math.min(a.t, this.t); + for (i = 0; i < m; ++i) r.data[i] = op(this.data[i], a.data[i]); + if (a.t < this.t) { + f = a.s & this.DM; + for (i = m; i < this.t; ++i) r.data[i] = op(this.data[i], f); + r.t = this.t; + } else { + f = this.s & this.DM; + for (i = m; i < a.t; ++i) r.data[i] = op(f, a.data[i]); + r.t = a.t; + } + r.s = op(this.s, a.s); + r.clamp(); + } + function op_and(x, y) { + return x & y; + } + function bnAnd(a) { + var r = nbi(); + this.bitwiseTo(a, op_and, r); + return r; + } + function op_or(x, y) { + return x | y; + } + function bnOr(a) { + var r = nbi(); + this.bitwiseTo(a, op_or, r); + return r; + } + function op_xor(x, y) { + return x ^ y; + } + function bnXor(a) { + var r = nbi(); + this.bitwiseTo(a, op_xor, r); + return r; + } + function op_andnot(x, y) { + return x & ~y; + } + function bnAndNot(a) { + var r = nbi(); + this.bitwiseTo(a, op_andnot, r); + return r; + } + function bnNot() { + var r = nbi(); + for (var i = 0; i < this.t; ++i) r.data[i] = this.DM & ~this.data[i]; + r.t = this.t; + r.s = ~this.s; + return r; + } + function bnShiftLeft(n) { + var r = nbi(); + if (n < 0) this.rShiftTo(-n, r); + else this.lShiftTo(n, r); + return r; + } + function bnShiftRight(n) { + var r = nbi(); + if (n < 0) this.lShiftTo(-n, r); + else this.rShiftTo(n, r); + return r; + } + function lbit(x) { + if (x == 0) return -1; + var r = 0; + if ((x & 65535) == 0) { + x >>= 16; + r += 16; + } + if ((x & 255) == 0) { + x >>= 8; + r += 8; + } + if ((x & 15) == 0) { + x >>= 4; + r += 4; + } + if ((x & 3) == 0) { + x >>= 2; + r += 2; + } + if ((x & 1) == 0) ++r; + return r; + } + function bnGetLowestSetBit() { + for (var i = 0; i < this.t; ++i) + if (this.data[i] != 0) return i * this.DB + lbit(this.data[i]); + if (this.s < 0) return this.t * this.DB; + return -1; + } + function cbit(x) { + var r = 0; + while (x != 0) { + x &= x - 1; + ++r; + } + return r; + } + function bnBitCount() { + var r = 0, x = this.s & this.DM; + for (var i = 0; i < this.t; ++i) r += cbit(this.data[i] ^ x); + return r; + } + function bnTestBit(n) { + var j = Math.floor(n / this.DB); + if (j >= this.t) return this.s != 0; + return (this.data[j] & 1 << n % this.DB) != 0; + } + function bnpChangeBit(n, op) { + var r = BigInteger.ONE.shiftLeft(n); + this.bitwiseTo(r, op, r); + return r; + } + function bnSetBit(n) { + return this.changeBit(n, op_or); + } + function bnClearBit(n) { + return this.changeBit(n, op_andnot); + } + function bnFlipBit(n) { + return this.changeBit(n, op_xor); + } + function bnpAddTo(a, r) { + var i = 0, c = 0, m = Math.min(a.t, this.t); + while (i < m) { + c += this.data[i] + a.data[i]; + r.data[i++] = c & this.DM; + c >>= this.DB; + } + if (a.t < this.t) { + c += a.s; + while (i < this.t) { + c += this.data[i]; + r.data[i++] = c & this.DM; + c >>= this.DB; + } + c += this.s; + } else { + c += this.s; + while (i < a.t) { + c += a.data[i]; + r.data[i++] = c & this.DM; + c >>= this.DB; + } + c += a.s; + } + r.s = c < 0 ? -1 : 0; + if (c > 0) r.data[i++] = c; + else if (c < -1) r.data[i++] = this.DV + c; + r.t = i; + r.clamp(); + } + function bnAdd(a) { + var r = nbi(); + this.addTo(a, r); + return r; + } + function bnSubtract(a) { + var r = nbi(); + this.subTo(a, r); + return r; + } + function bnMultiply(a) { + var r = nbi(); + this.multiplyTo(a, r); + return r; + } + function bnSquare() { + var r = nbi(); + this.squareTo(r); + return r; + } + function bnDivide(a) { + var r = nbi(); + this.divRemTo(a, r, null); + return r; + } + function bnRemainder(a) { + var r = nbi(); + this.divRemTo(a, null, r); + return r; + } + function bnDivideAndRemainder(a) { + var q = nbi(), r = nbi(); + this.divRemTo(a, q, r); + return new Array(q, r); + } + function bnpDMultiply(n) { + this.data[this.t] = this.am(0, n - 1, this, 0, 0, this.t); + ++this.t; + this.clamp(); + } + function bnpDAddOffset(n, w) { + if (n == 0) return; + while (this.t <= w) this.data[this.t++] = 0; + this.data[w] += n; + while (this.data[w] >= this.DV) { + this.data[w] -= this.DV; + if (++w >= this.t) this.data[this.t++] = 0; + ++this.data[w]; + } + } + function NullExp() { + } + function nNop(x) { + return x; + } + function nMulTo(x, y, r) { + x.multiplyTo(y, r); + } + function nSqrTo(x, r) { + x.squareTo(r); + } + NullExp.prototype.convert = nNop; + NullExp.prototype.revert = nNop; + NullExp.prototype.mulTo = nMulTo; + NullExp.prototype.sqrTo = nSqrTo; + function bnPow(e) { + return this.exp(e, new NullExp()); + } + function bnpMultiplyLowerTo(a, n, r) { + var i = Math.min(this.t + a.t, n); + r.s = 0; + r.t = i; + while (i > 0) r.data[--i] = 0; + var j; + for (j = r.t - this.t; i < j; ++i) r.data[i + this.t] = this.am(0, a.data[i], r, i, 0, this.t); + for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a.data[i], r, i, 0, n - i); + r.clamp(); + } + function bnpMultiplyUpperTo(a, n, r) { + --n; + var i = r.t = this.t + a.t - n; + r.s = 0; + while (--i >= 0) r.data[i] = 0; + for (i = Math.max(n - this.t, 0); i < a.t; ++i) + r.data[this.t + i - n] = this.am(n - i, a.data[i], r, 0, 0, this.t + i - n); + r.clamp(); + r.drShiftTo(1, r); + } + function Barrett(m) { + this.r2 = nbi(); + this.q3 = nbi(); + BigInteger.ONE.dlShiftTo(2 * m.t, this.r2); + this.mu = this.r2.divide(m); + this.m = m; + } + function barrettConvert(x) { + if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m); + else if (x.compareTo(this.m) < 0) return x; + else { + var r = nbi(); + x.copyTo(r); + this.reduce(r); + return r; + } + } + function barrettRevert(x) { + return x; + } + function barrettReduce(x) { + x.drShiftTo(this.m.t - 1, this.r2); + if (x.t > this.m.t + 1) { + x.t = this.m.t + 1; + x.clamp(); + } + this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3); + this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2); + while (x.compareTo(this.r2) < 0) x.dAddOffset(1, this.m.t + 1); + x.subTo(this.r2, x); + while (x.compareTo(this.m) >= 0) x.subTo(this.m, x); + } + function barrettSqrTo(x, r) { + x.squareTo(r); + this.reduce(r); + } + function barrettMulTo(x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); + } + Barrett.prototype.convert = barrettConvert; + Barrett.prototype.revert = barrettRevert; + Barrett.prototype.reduce = barrettReduce; + Barrett.prototype.mulTo = barrettMulTo; + Barrett.prototype.sqrTo = barrettSqrTo; + function bnModPow(e, m) { + var i = e.bitLength(), k, r = nbv(1), z; + if (i <= 0) return r; + else if (i < 18) k = 1; + else if (i < 48) k = 3; + else if (i < 144) k = 4; + else if (i < 768) k = 5; + else k = 6; + if (i < 8) + z = new Classic(m); + else if (m.isEven()) + z = new Barrett(m); + else + z = new Montgomery(m); + var g = new Array(), n = 3, k1 = k - 1, km = (1 << k) - 1; + g[1] = z.convert(this); + if (k > 1) { + var g2 = nbi(); + z.sqrTo(g[1], g2); + while (n <= km) { + g[n] = nbi(); + z.mulTo(g2, g[n - 2], g[n]); + n += 2; + } + } + var j = e.t - 1, w, is1 = true, r2 = nbi(), t; + i = nbits(e.data[j]) - 1; + while (j >= 0) { + if (i >= k1) w = e.data[j] >> i - k1 & km; + else { + w = (e.data[j] & (1 << i + 1) - 1) << k1 - i; + if (j > 0) w |= e.data[j - 1] >> this.DB + i - k1; + } + n = k; + while ((w & 1) == 0) { + w >>= 1; + --n; + } + if ((i -= n) < 0) { + i += this.DB; + --j; + } + if (is1) { + g[w].copyTo(r); + is1 = false; + } else { + while (n > 1) { + z.sqrTo(r, r2); + z.sqrTo(r2, r); + n -= 2; + } + if (n > 0) z.sqrTo(r, r2); + else { + t = r; + r = r2; + r2 = t; + } + z.mulTo(r2, g[w], r); + } + while (j >= 0 && (e.data[j] & 1 << i) == 0) { + z.sqrTo(r, r2); + t = r; + r = r2; + r2 = t; + if (--i < 0) { + i = this.DB - 1; + --j; + } + } + } + return z.revert(r); + } + function bnGCD(a) { + var x = this.s < 0 ? this.negate() : this.clone(); + var y = a.s < 0 ? a.negate() : a.clone(); + if (x.compareTo(y) < 0) { + var t = x; + x = y; + y = t; + } + var i = x.getLowestSetBit(), g = y.getLowestSetBit(); + if (g < 0) return x; + if (i < g) g = i; + if (g > 0) { + x.rShiftTo(g, x); + y.rShiftTo(g, y); + } + while (x.signum() > 0) { + if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x); + if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y); + if (x.compareTo(y) >= 0) { + x.subTo(y, x); + x.rShiftTo(1, x); + } else { + y.subTo(x, y); + y.rShiftTo(1, y); + } + } + if (g > 0) y.lShiftTo(g, y); + return y; + } + function bnpModInt(n) { + if (n <= 0) return 0; + var d = this.DV % n, r = this.s < 0 ? n - 1 : 0; + if (this.t > 0) + if (d == 0) r = this.data[0] % n; + else for (var i = this.t - 1; i >= 0; --i) r = (d * r + this.data[i]) % n; + return r; + } + function bnModInverse(m) { + if (this.signum() == 0) { + return BigInteger.ZERO; + } + var ac = m.isEven(); + if (this.isEven() && ac || m.signum() == 0) return BigInteger.ZERO; + var u = m.clone(), v = this.clone(); + var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); + while (u.signum() != 0) { + while (u.isEven()) { + u.rShiftTo(1, u); + if (ac) { + if (!a.isEven() || !b.isEven()) { + a.addTo(this, a); + b.subTo(m, b); + } + a.rShiftTo(1, a); + } else if (!b.isEven()) b.subTo(m, b); + b.rShiftTo(1, b); + } + while (v.isEven()) { + v.rShiftTo(1, v); + if (ac) { + if (!c.isEven() || !d.isEven()) { + c.addTo(this, c); + d.subTo(m, d); + } + c.rShiftTo(1, c); + } else if (!d.isEven()) d.subTo(m, d); + d.rShiftTo(1, d); + } + if (u.compareTo(v) >= 0) { + u.subTo(v, u); + if (ac) a.subTo(c, a); + b.subTo(d, b); + } else { + v.subTo(u, v); + if (ac) c.subTo(a, c); + d.subTo(b, d); + } + } + if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; + if (d.compareTo(m) >= 0) return d.subtract(m); + if (d.signum() < 0) d.addTo(m, d); + else return d; + if (d.signum() < 0) return d.add(m); + else return d; + } + var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]; + var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]; + function bnIsProbablePrime(t) { + var i, x = this.abs(); + if (x.t == 1 && x.data[0] <= lowprimes[lowprimes.length - 1]) { + for (i = 0; i < lowprimes.length; ++i) + if (x.data[0] == lowprimes[i]) return true; + return false; + } + if (x.isEven()) return false; + i = 1; + while (i < lowprimes.length) { + var m = lowprimes[i], j = i + 1; + while (j < lowprimes.length && m < lplim) m *= lowprimes[j++]; + m = x.modInt(m); + while (i < j) if (m % lowprimes[i++] == 0) return false; + } + return x.millerRabin(t); + } + function bnpMillerRabin(t) { + var n1 = this.subtract(BigInteger.ONE); + var k = n1.getLowestSetBit(); + if (k <= 0) return false; + var r = n1.shiftRight(k); + var prng = bnGetPrng(); + var a; + for (var i = 0; i < t; ++i) { + do { + a = new BigInteger(this.bitLength(), prng); + } while (a.compareTo(BigInteger.ONE) <= 0 || a.compareTo(n1) >= 0); + var y = a.modPow(r, this); + if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { + var j = 1; + while (j++ < k && y.compareTo(n1) != 0) { + y = y.modPowInt(2, this); + if (y.compareTo(BigInteger.ONE) == 0) return false; + } + if (y.compareTo(n1) != 0) return false; + } + } + return true; + } + function bnGetPrng() { + return { + // x is an array to fill with bytes + nextBytes: function(x) { + for (var i = 0; i < x.length; ++i) { + x[i] = Math.floor(Math.random() * 256); + } + } + }; + } + BigInteger.prototype.chunkSize = bnpChunkSize; + BigInteger.prototype.toRadix = bnpToRadix; + BigInteger.prototype.fromRadix = bnpFromRadix; + BigInteger.prototype.fromNumber = bnpFromNumber; + BigInteger.prototype.bitwiseTo = bnpBitwiseTo; + BigInteger.prototype.changeBit = bnpChangeBit; + BigInteger.prototype.addTo = bnpAddTo; + BigInteger.prototype.dMultiply = bnpDMultiply; + BigInteger.prototype.dAddOffset = bnpDAddOffset; + BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; + BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; + BigInteger.prototype.modInt = bnpModInt; + BigInteger.prototype.millerRabin = bnpMillerRabin; + BigInteger.prototype.clone = bnClone; + BigInteger.prototype.intValue = bnIntValue; + BigInteger.prototype.byteValue = bnByteValue; + BigInteger.prototype.shortValue = bnShortValue; + BigInteger.prototype.signum = bnSigNum; + BigInteger.prototype.toByteArray = bnToByteArray; + BigInteger.prototype.equals = bnEquals; + BigInteger.prototype.min = bnMin; + BigInteger.prototype.max = bnMax; + BigInteger.prototype.and = bnAnd; + BigInteger.prototype.or = bnOr; + BigInteger.prototype.xor = bnXor; + BigInteger.prototype.andNot = bnAndNot; + BigInteger.prototype.not = bnNot; + BigInteger.prototype.shiftLeft = bnShiftLeft; + BigInteger.prototype.shiftRight = bnShiftRight; + BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; + BigInteger.prototype.bitCount = bnBitCount; + BigInteger.prototype.testBit = bnTestBit; + BigInteger.prototype.setBit = bnSetBit; + BigInteger.prototype.clearBit = bnClearBit; + BigInteger.prototype.flipBit = bnFlipBit; + BigInteger.prototype.add = bnAdd; + BigInteger.prototype.subtract = bnSubtract; + BigInteger.prototype.multiply = bnMultiply; + BigInteger.prototype.divide = bnDivide; + BigInteger.prototype.remainder = bnRemainder; + BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; + BigInteger.prototype.modPow = bnModPow; + BigInteger.prototype.modInverse = bnModInverse; + BigInteger.prototype.pow = bnPow; + BigInteger.prototype.gcd = bnGCD; + BigInteger.prototype.isProbablePrime = bnIsProbablePrime; + BigInteger.prototype.square = bnSquare; + } +}); + +// node_modules/node-forge/lib/sha1.js +var require_sha1 = __commonJS({ + "node_modules/node-forge/lib/sha1.js"(exports2, module2) { + var forge = require_forge(); + require_md(); + require_util13(); + var sha1 = module2.exports = forge.sha1 = forge.sha1 || {}; + forge.md.sha1 = forge.md.algorithms.sha1 = sha1; + sha1.create = function() { + if (!_initialized) { + _init(); + } + var _state = null; + var _input = forge.util.createBuffer(); + var _w = new Array(80); + var md2 = { + algorithm: "sha1", + blockLength: 64, + digestLength: 20, + // 56-bit length of message so far (does not including padding) + messageLength: 0, + // true message length + fullMessageLength: null, + // size of message length in bytes + messageLengthSize: 8 + }; + md2.start = function() { + md2.messageLength = 0; + md2.fullMessageLength = md2.messageLength64 = []; + var int32s = md2.messageLengthSize / 4; + for (var i = 0; i < int32s; ++i) { + md2.fullMessageLength.push(0); + } + _input = forge.util.createBuffer(); + _state = { + h0: 1732584193, + h1: 4023233417, + h2: 2562383102, + h3: 271733878, + h4: 3285377520 + }; + return md2; + }; + md2.start(); + md2.update = function(msg, encoding) { + if (encoding === "utf8") { + msg = forge.util.encodeUtf8(msg); + } + var len = msg.length; + md2.messageLength += len; + len = [len / 4294967296 >>> 0, len >>> 0]; + for (var i = md2.fullMessageLength.length - 1; i >= 0; --i) { + md2.fullMessageLength[i] += len[1]; + len[1] = len[0] + (md2.fullMessageLength[i] / 4294967296 >>> 0); + md2.fullMessageLength[i] = md2.fullMessageLength[i] >>> 0; + len[0] = len[1] / 4294967296 >>> 0; + } + _input.putBytes(msg); + _update(_state, _w, _input); + if (_input.read > 2048 || _input.length() === 0) { + _input.compact(); + } + return md2; + }; + md2.digest = function() { + var finalBlock = forge.util.createBuffer(); + finalBlock.putBytes(_input.bytes()); + var remaining = md2.fullMessageLength[md2.fullMessageLength.length - 1] + md2.messageLengthSize; + var overflow = remaining & md2.blockLength - 1; + finalBlock.putBytes(_padding.substr(0, md2.blockLength - overflow)); + var next, carry; + var bits = md2.fullMessageLength[0] * 8; + for (var i = 0; i < md2.fullMessageLength.length - 1; ++i) { + next = md2.fullMessageLength[i + 1] * 8; + carry = next / 4294967296 >>> 0; + bits += carry; + finalBlock.putInt32(bits >>> 0); + bits = next >>> 0; + } + finalBlock.putInt32(bits); + var s2 = { + h0: _state.h0, + h1: _state.h1, + h2: _state.h2, + h3: _state.h3, + h4: _state.h4 + }; + _update(s2, _w, finalBlock); + var rval = forge.util.createBuffer(); + rval.putInt32(s2.h0); + rval.putInt32(s2.h1); + rval.putInt32(s2.h2); + rval.putInt32(s2.h3); + rval.putInt32(s2.h4); + return rval; + }; + return md2; + }; + var _padding = null; + var _initialized = false; + function _init() { + _padding = String.fromCharCode(128); + _padding += forge.util.fillString(String.fromCharCode(0), 64); + _initialized = true; + } + function _update(s, w, bytes) { + var t, a, b, c, d, e, f, i; + var len = bytes.length(); + while (len >= 64) { + a = s.h0; + b = s.h1; + c = s.h2; + d = s.h3; + e = s.h4; + for (i = 0; i < 16; ++i) { + t = bytes.getInt32(); + w[i] = t; + f = d ^ b & (c ^ d); + t = (a << 5 | a >>> 27) + f + e + 1518500249 + t; + e = d; + d = c; + c = (b << 30 | b >>> 2) >>> 0; + b = a; + a = t; + } + for (; i < 20; ++i) { + t = w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]; + t = t << 1 | t >>> 31; + w[i] = t; + f = d ^ b & (c ^ d); + t = (a << 5 | a >>> 27) + f + e + 1518500249 + t; + e = d; + d = c; + c = (b << 30 | b >>> 2) >>> 0; + b = a; + a = t; + } + for (; i < 32; ++i) { + t = w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]; + t = t << 1 | t >>> 31; + w[i] = t; + f = b ^ c ^ d; + t = (a << 5 | a >>> 27) + f + e + 1859775393 + t; + e = d; + d = c; + c = (b << 30 | b >>> 2) >>> 0; + b = a; + a = t; + } + for (; i < 40; ++i) { + t = w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]; + t = t << 2 | t >>> 30; + w[i] = t; + f = b ^ c ^ d; + t = (a << 5 | a >>> 27) + f + e + 1859775393 + t; + e = d; + d = c; + c = (b << 30 | b >>> 2) >>> 0; + b = a; + a = t; + } + for (; i < 60; ++i) { + t = w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]; + t = t << 2 | t >>> 30; + w[i] = t; + f = b & c | d & (b ^ c); + t = (a << 5 | a >>> 27) + f + e + 2400959708 + t; + e = d; + d = c; + c = (b << 30 | b >>> 2) >>> 0; + b = a; + a = t; + } + for (; i < 80; ++i) { + t = w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]; + t = t << 2 | t >>> 30; + w[i] = t; + f = b ^ c ^ d; + t = (a << 5 | a >>> 27) + f + e + 3395469782 + t; + e = d; + d = c; + c = (b << 30 | b >>> 2) >>> 0; + b = a; + a = t; + } + s.h0 = s.h0 + a | 0; + s.h1 = s.h1 + b | 0; + s.h2 = s.h2 + c | 0; + s.h3 = s.h3 + d | 0; + s.h4 = s.h4 + e | 0; + len -= 64; + } + } + } +}); + +// node_modules/node-forge/lib/pkcs1.js +var require_pkcs1 = __commonJS({ + "node_modules/node-forge/lib/pkcs1.js"(exports2, module2) { + var forge = require_forge(); + require_util13(); + require_random(); + require_sha1(); + var pkcs1 = module2.exports = forge.pkcs1 = forge.pkcs1 || {}; + pkcs1.encode_rsa_oaep = function(key, message, options) { + var label; + var seed; + var md2; + var mgf1Md; + if (typeof options === "string") { + label = options; + seed = arguments[3] || void 0; + md2 = arguments[4] || void 0; + } else if (options) { + label = options.label || void 0; + seed = options.seed || void 0; + md2 = options.md || void 0; + if (options.mgf1 && options.mgf1.md) { + mgf1Md = options.mgf1.md; + } + } + if (!md2) { + md2 = forge.md.sha1.create(); + } else { + md2.start(); + } + if (!mgf1Md) { + mgf1Md = md2; + } + var keyLength = Math.ceil(key.n.bitLength() / 8); + var maxLength = keyLength - 2 * md2.digestLength - 2; + if (message.length > maxLength) { + var error2 = new Error("RSAES-OAEP input message length is too long."); + error2.length = message.length; + error2.maxLength = maxLength; + throw error2; + } + if (!label) { + label = ""; + } + md2.update(label, "raw"); + var lHash = md2.digest(); + var PS = ""; + var PS_length = maxLength - message.length; + for (var i = 0; i < PS_length; i++) { + PS += "\0"; + } + var DB = lHash.getBytes() + PS + "" + message; + if (!seed) { + seed = forge.random.getBytes(md2.digestLength); + } else if (seed.length !== md2.digestLength) { + var error2 = new Error("Invalid RSAES-OAEP seed. The seed length must match the digest length."); + error2.seedLength = seed.length; + error2.digestLength = md2.digestLength; + throw error2; + } + var dbMask = rsa_mgf1(seed, keyLength - md2.digestLength - 1, mgf1Md); + var maskedDB = forge.util.xorBytes(DB, dbMask, DB.length); + var seedMask = rsa_mgf1(maskedDB, md2.digestLength, mgf1Md); + var maskedSeed = forge.util.xorBytes(seed, seedMask, seed.length); + return "\0" + maskedSeed + maskedDB; + }; + pkcs1.decode_rsa_oaep = function(key, em, options) { + var label; + var md2; + var mgf1Md; + if (typeof options === "string") { + label = options; + md2 = arguments[3] || void 0; + } else if (options) { + label = options.label || void 0; + md2 = options.md || void 0; + if (options.mgf1 && options.mgf1.md) { + mgf1Md = options.mgf1.md; + } + } + var keyLength = Math.ceil(key.n.bitLength() / 8); + if (em.length !== keyLength) { + var error2 = new Error("RSAES-OAEP encoded message length is invalid."); + error2.length = em.length; + error2.expectedLength = keyLength; + throw error2; + } + if (md2 === void 0) { + md2 = forge.md.sha1.create(); + } else { + md2.start(); + } + if (!mgf1Md) { + mgf1Md = md2; + } + if (keyLength < 2 * md2.digestLength + 2) { + throw new Error("RSAES-OAEP key is too short for the hash function."); + } + if (!label) { + label = ""; + } + md2.update(label, "raw"); + var lHash = md2.digest().getBytes(); + var y = em.charAt(0); + var maskedSeed = em.substring(1, md2.digestLength + 1); + var maskedDB = em.substring(1 + md2.digestLength); + var seedMask = rsa_mgf1(maskedDB, md2.digestLength, mgf1Md); + var seed = forge.util.xorBytes(maskedSeed, seedMask, maskedSeed.length); + var dbMask = rsa_mgf1(seed, keyLength - md2.digestLength - 1, mgf1Md); + var db = forge.util.xorBytes(maskedDB, dbMask, maskedDB.length); + var lHashPrime = db.substring(0, md2.digestLength); + var error2 = y !== "\0"; + for (var i = 0; i < md2.digestLength; ++i) { + error2 |= lHash.charAt(i) !== lHashPrime.charAt(i); + } + var in_ps = 1; + var index = md2.digestLength; + for (var j = md2.digestLength; j < db.length; j++) { + var code = db.charCodeAt(j); + var is_0 = code & 1 ^ 1; + var error_mask = in_ps ? 65534 : 0; + error2 |= code & error_mask; + in_ps = in_ps & is_0; + index += in_ps; + } + if (error2 || db.charCodeAt(index) !== 1) { + throw new Error("Invalid RSAES-OAEP padding."); + } + return db.substring(index + 1); + }; + function rsa_mgf1(seed, maskLength, hash) { + if (!hash) { + hash = forge.md.sha1.create(); + } + var t = ""; + var count = Math.ceil(maskLength / hash.digestLength); + for (var i = 0; i < count; ++i) { + var c = String.fromCharCode( + i >> 24 & 255, + i >> 16 & 255, + i >> 8 & 255, + i & 255 + ); + hash.start(); + hash.update(seed + c); + t += hash.digest().getBytes(); + } + return t.substring(0, maskLength); + } + } +}); + +// node_modules/node-forge/lib/prime.js +var require_prime = __commonJS({ + "node_modules/node-forge/lib/prime.js"(exports2, module2) { + var forge = require_forge(); + require_util13(); + require_jsbn(); + require_random(); + (function() { + if (forge.prime) { + module2.exports = forge.prime; + return; + } + var prime = module2.exports = forge.prime = forge.prime || {}; + var BigInteger = forge.jsbn.BigInteger; + var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; + var THIRTY = new BigInteger(null); + THIRTY.fromInt(30); + var op_or = function(x, y) { + return x | y; + }; + prime.generateProbablePrime = function(bits, options, callback) { + if (typeof options === "function") { + callback = options; + options = {}; + } + options = options || {}; + var algorithm = options.algorithm || "PRIMEINC"; + if (typeof algorithm === "string") { + algorithm = { name: algorithm }; + } + algorithm.options = algorithm.options || {}; + var prng = options.prng || forge.random; + var rng = { + // x is an array to fill with bytes + nextBytes: function(x) { + var b = prng.getBytesSync(x.length); + for (var i = 0; i < x.length; ++i) { + x[i] = b.charCodeAt(i); + } + } + }; + if (algorithm.name === "PRIMEINC") { + return primeincFindPrime(bits, rng, algorithm.options, callback); + } + throw new Error("Invalid prime generation algorithm: " + algorithm.name); + }; + function primeincFindPrime(bits, rng, options, callback) { + if ("workers" in options) { + return primeincFindPrimeWithWorkers(bits, rng, options, callback); + } + return primeincFindPrimeWithoutWorkers(bits, rng, options, callback); + } + function primeincFindPrimeWithoutWorkers(bits, rng, options, callback) { + var num = generateRandom(bits, rng); + var deltaIdx = 0; + var mrTests = getMillerRabinTests(num.bitLength()); + if ("millerRabinTests" in options) { + mrTests = options.millerRabinTests; + } + var maxBlockTime = 10; + if ("maxBlockTime" in options) { + maxBlockTime = options.maxBlockTime; + } + _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback); + } + function _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback) { + var start = +/* @__PURE__ */ new Date(); + do { + if (num.bitLength() > bits) { + num = generateRandom(bits, rng); + } + if (num.isProbablePrime(mrTests)) { + return callback(null, num); + } + num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); + } while (maxBlockTime < 0 || +/* @__PURE__ */ new Date() - start < maxBlockTime); + forge.util.setImmediate(function() { + _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback); + }); + } + function primeincFindPrimeWithWorkers(bits, rng, options, callback) { + if (typeof Worker === "undefined") { + return primeincFindPrimeWithoutWorkers(bits, rng, options, callback); + } + var num = generateRandom(bits, rng); + var numWorkers = options.workers; + var workLoad = options.workLoad || 100; + var range = workLoad * 30 / 8; + var workerScript = options.workerScript || "forge/prime.worker.js"; + if (numWorkers === -1) { + return forge.util.estimateCores(function(err, cores) { + if (err) { + cores = 2; + } + numWorkers = cores - 1; + generate(); + }); + } + generate(); + function generate() { + numWorkers = Math.max(1, numWorkers); + var workers = []; + for (var i = 0; i < numWorkers; ++i) { + workers[i] = new Worker(workerScript); + } + var running = numWorkers; + for (var i = 0; i < numWorkers; ++i) { + workers[i].addEventListener("message", workerMessage); + } + var found = false; + function workerMessage(e) { + if (found) { + return; + } + --running; + var data = e.data; + if (data.found) { + for (var i2 = 0; i2 < workers.length; ++i2) { + workers[i2].terminate(); + } + found = true; + return callback(null, new BigInteger(data.prime, 16)); + } + if (num.bitLength() > bits) { + num = generateRandom(bits, rng); + } + var hex = num.toString(16); + e.target.postMessage({ + hex, + workLoad + }); + num.dAddOffset(range, 0); + } + } + } + function generateRandom(bits, rng) { + var num = new BigInteger(bits, rng); + var bits1 = bits - 1; + if (!num.testBit(bits1)) { + num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num); + } + num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0); + return num; + } + function getMillerRabinTests(bits) { + if (bits <= 100) return 27; + if (bits <= 150) return 18; + if (bits <= 200) return 15; + if (bits <= 250) return 12; + if (bits <= 300) return 9; + if (bits <= 350) return 8; + if (bits <= 400) return 7; + if (bits <= 500) return 6; + if (bits <= 600) return 5; + if (bits <= 800) return 4; + if (bits <= 1250) return 3; + return 2; + } + })(); + } +}); + +// node_modules/node-forge/lib/rsa.js +var require_rsa = __commonJS({ + "node_modules/node-forge/lib/rsa.js"(exports2, module2) { + var forge = require_forge(); + require_asn1(); + require_jsbn(); + require_oids(); + require_pkcs1(); + require_prime(); + require_random(); + require_util13(); + if (typeof BigInteger === "undefined") { + BigInteger = forge.jsbn.BigInteger; + } + var BigInteger; + var _crypto = forge.util.isNodejs ? require("crypto") : null; + var asn1 = forge.asn1; + var util = forge.util; + forge.pki = forge.pki || {}; + module2.exports = forge.pki.rsa = forge.rsa = forge.rsa || {}; + var pki2 = forge.pki; + var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; + var privateKeyValidator = { + // PrivateKeyInfo + name: "PrivateKeyInfo", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + // Version (INTEGER) + name: "PrivateKeyInfo.version", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "privateKeyVersion" + }, { + // privateKeyAlgorithm + name: "PrivateKeyInfo.privateKeyAlgorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "AlgorithmIdentifier.algorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "privateKeyOid" + }] + }, { + // PrivateKey + name: "PrivateKeyInfo", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: "privateKey" + }] + }; + var rsaPrivateKeyValidator = { + // RSAPrivateKey + name: "RSAPrivateKey", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + // Version (INTEGER) + name: "RSAPrivateKey.version", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "privateKeyVersion" + }, { + // modulus (n) + name: "RSAPrivateKey.modulus", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "privateKeyModulus" + }, { + // publicExponent (e) + name: "RSAPrivateKey.publicExponent", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "privateKeyPublicExponent" + }, { + // privateExponent (d) + name: "RSAPrivateKey.privateExponent", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "privateKeyPrivateExponent" + }, { + // prime1 (p) + name: "RSAPrivateKey.prime1", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "privateKeyPrime1" + }, { + // prime2 (q) + name: "RSAPrivateKey.prime2", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "privateKeyPrime2" + }, { + // exponent1 (d mod (p-1)) + name: "RSAPrivateKey.exponent1", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "privateKeyExponent1" + }, { + // exponent2 (d mod (q-1)) + name: "RSAPrivateKey.exponent2", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "privateKeyExponent2" + }, { + // coefficient ((inverse of q) mod p) + name: "RSAPrivateKey.coefficient", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "privateKeyCoefficient" + }] + }; + var rsaPublicKeyValidator = { + // RSAPublicKey + name: "RSAPublicKey", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + // modulus (n) + name: "RSAPublicKey.modulus", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "publicKeyModulus" + }, { + // publicExponent (e) + name: "RSAPublicKey.exponent", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "publicKeyExponent" + }] + }; + var publicKeyValidator = forge.pki.rsa.publicKeyValidator = { + name: "SubjectPublicKeyInfo", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: "subjectPublicKeyInfo", + value: [{ + name: "SubjectPublicKeyInfo.AlgorithmIdentifier", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "AlgorithmIdentifier.algorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "publicKeyOid" + }] + }, { + // subjectPublicKey + name: "SubjectPublicKeyInfo.subjectPublicKey", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + value: [{ + // RSAPublicKey + name: "SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + optional: true, + captureAsn1: "rsaPublicKey" + }] + }] + }; + var digestInfoValidator = { + name: "DigestInfo", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "DigestInfo.DigestAlgorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "DigestInfo.DigestAlgorithm.algorithmIdentifier", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "algorithmIdentifier" + }, { + // NULL parameters + name: "DigestInfo.DigestAlgorithm.parameters", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.NULL, + // captured only to check existence for md2 and md5 + capture: "parameters", + optional: true, + constructed: false + }] + }, { + // digest + name: "DigestInfo.digest", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: "digest" + }] + }; + var emsaPkcs1v15encode = function(md2) { + var oid; + if (md2.algorithm in pki2.oids) { + oid = pki2.oids[md2.algorithm]; + } else { + var error2 = new Error("Unknown message digest algorithm."); + error2.algorithm = md2.algorithm; + throw error2; + } + var oidBytes = asn1.oidToDer(oid).getBytes(); + var digestInfo = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SEQUENCE, + true, + [] + ); + var digestAlgorithm = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SEQUENCE, + true, + [] + ); + digestAlgorithm.value.push(asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + oidBytes + )); + digestAlgorithm.value.push(asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.NULL, + false, + "" + )); + var digest = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + md2.digest().getBytes() + ); + digestInfo.value.push(digestAlgorithm); + digestInfo.value.push(digest); + return asn1.toDer(digestInfo).getBytes(); + }; + var _modPow = function(x, key, pub) { + if (pub) { + return x.modPow(key.e, key.n); + } + if (!key.p || !key.q) { + return x.modPow(key.d, key.n); + } + if (!key.dP) { + key.dP = key.d.mod(key.p.subtract(BigInteger.ONE)); + } + if (!key.dQ) { + key.dQ = key.d.mod(key.q.subtract(BigInteger.ONE)); + } + if (!key.qInv) { + key.qInv = key.q.modInverse(key.p); + } + var r; + do { + r = new BigInteger( + forge.util.bytesToHex(forge.random.getBytes(key.n.bitLength() / 8)), + 16 + ); + } while (r.compareTo(key.n) >= 0 || !r.gcd(key.n).equals(BigInteger.ONE)); + x = x.multiply(r.modPow(key.e, key.n)).mod(key.n); + var xp = x.mod(key.p).modPow(key.dP, key.p); + var xq = x.mod(key.q).modPow(key.dQ, key.q); + while (xp.compareTo(xq) < 0) { + xp = xp.add(key.p); + } + var y = xp.subtract(xq).multiply(key.qInv).mod(key.p).multiply(key.q).add(xq); + y = y.multiply(r.modInverse(key.n)).mod(key.n); + return y; + }; + pki2.rsa.encrypt = function(m, key, bt) { + var pub = bt; + var eb; + var k = Math.ceil(key.n.bitLength() / 8); + if (bt !== false && bt !== true) { + pub = bt === 2; + eb = _encodePkcs1_v1_5(m, key, bt); + } else { + eb = forge.util.createBuffer(); + eb.putBytes(m); + } + var x = new BigInteger(eb.toHex(), 16); + var y = _modPow(x, key, pub); + var yhex = y.toString(16); + var ed = forge.util.createBuffer(); + var zeros = k - Math.ceil(yhex.length / 2); + while (zeros > 0) { + ed.putByte(0); + --zeros; + } + ed.putBytes(forge.util.hexToBytes(yhex)); + return ed.getBytes(); + }; + pki2.rsa.decrypt = function(ed, key, pub, ml) { + var k = Math.ceil(key.n.bitLength() / 8); + if (ed.length !== k) { + var error2 = new Error("Encrypted message length is invalid."); + error2.length = ed.length; + error2.expected = k; + throw error2; + } + var y = new BigInteger(forge.util.createBuffer(ed).toHex(), 16); + if (y.compareTo(key.n) >= 0) { + throw new Error("Encrypted message is invalid."); + } + var x = _modPow(y, key, pub); + var xhex = x.toString(16); + var eb = forge.util.createBuffer(); + var zeros = k - Math.ceil(xhex.length / 2); + while (zeros > 0) { + eb.putByte(0); + --zeros; + } + eb.putBytes(forge.util.hexToBytes(xhex)); + if (ml !== false) { + return _decodePkcs1_v1_5(eb.getBytes(), key, pub); + } + return eb.getBytes(); + }; + pki2.rsa.createKeyPairGenerationState = function(bits, e, options) { + if (typeof bits === "string") { + bits = parseInt(bits, 10); + } + bits = bits || 2048; + options = options || {}; + var prng = options.prng || forge.random; + var rng = { + // x is an array to fill with bytes + nextBytes: function(x) { + var b = prng.getBytesSync(x.length); + for (var i = 0; i < x.length; ++i) { + x[i] = b.charCodeAt(i); + } + } + }; + var algorithm = options.algorithm || "PRIMEINC"; + var rval; + if (algorithm === "PRIMEINC") { + rval = { + algorithm, + state: 0, + bits, + rng, + eInt: e || 65537, + e: new BigInteger(null), + p: null, + q: null, + qBits: bits >> 1, + pBits: bits - (bits >> 1), + pqState: 0, + num: null, + keys: null + }; + rval.e.fromInt(rval.eInt); + } else { + throw new Error("Invalid key generation algorithm: " + algorithm); + } + return rval; + }; + pki2.rsa.stepKeyPairGenerationState = function(state, n) { + if (!("algorithm" in state)) { + state.algorithm = "PRIMEINC"; + } + var THIRTY = new BigInteger(null); + THIRTY.fromInt(30); + var deltaIdx = 0; + var op_or = function(x, y) { + return x | y; + }; + var t1 = +/* @__PURE__ */ new Date(); + var t2; + var total = 0; + while (state.keys === null && (n <= 0 || total < n)) { + if (state.state === 0) { + var bits = state.p === null ? state.pBits : state.qBits; + var bits1 = bits - 1; + if (state.pqState === 0) { + state.num = new BigInteger(bits, state.rng); + if (!state.num.testBit(bits1)) { + state.num.bitwiseTo( + BigInteger.ONE.shiftLeft(bits1), + op_or, + state.num + ); + } + state.num.dAddOffset(31 - state.num.mod(THIRTY).byteValue(), 0); + deltaIdx = 0; + ++state.pqState; + } else if (state.pqState === 1) { + if (state.num.bitLength() > bits) { + state.pqState = 0; + } else if (state.num.isProbablePrime( + _getMillerRabinTests(state.num.bitLength()) + )) { + ++state.pqState; + } else { + state.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); + } + } else if (state.pqState === 2) { + state.pqState = state.num.subtract(BigInteger.ONE).gcd(state.e).compareTo(BigInteger.ONE) === 0 ? 3 : 0; + } else if (state.pqState === 3) { + state.pqState = 0; + if (state.p === null) { + state.p = state.num; + } else { + state.q = state.num; + } + if (state.p !== null && state.q !== null) { + ++state.state; + } + state.num = null; + } + } else if (state.state === 1) { + if (state.p.compareTo(state.q) < 0) { + state.num = state.p; + state.p = state.q; + state.q = state.num; + } + ++state.state; + } else if (state.state === 2) { + state.p1 = state.p.subtract(BigInteger.ONE); + state.q1 = state.q.subtract(BigInteger.ONE); + state.phi = state.p1.multiply(state.q1); + ++state.state; + } else if (state.state === 3) { + if (state.phi.gcd(state.e).compareTo(BigInteger.ONE) === 0) { + ++state.state; + } else { + state.p = null; + state.q = null; + state.state = 0; + } + } else if (state.state === 4) { + state.n = state.p.multiply(state.q); + if (state.n.bitLength() === state.bits) { + ++state.state; + } else { + state.q = null; + state.state = 0; + } + } else if (state.state === 5) { + var d = state.e.modInverse(state.phi); + state.keys = { + privateKey: pki2.rsa.setPrivateKey( + state.n, + state.e, + d, + state.p, + state.q, + d.mod(state.p1), + d.mod(state.q1), + state.q.modInverse(state.p) + ), + publicKey: pki2.rsa.setPublicKey(state.n, state.e) + }; + } + t2 = +/* @__PURE__ */ new Date(); + total += t2 - t1; + t1 = t2; + } + return state.keys !== null; + }; + pki2.rsa.generateKeyPair = function(bits, e, options, callback) { + if (arguments.length === 1) { + if (typeof bits === "object") { + options = bits; + bits = void 0; + } else if (typeof bits === "function") { + callback = bits; + bits = void 0; + } + } else if (arguments.length === 2) { + if (typeof bits === "number") { + if (typeof e === "function") { + callback = e; + e = void 0; + } else if (typeof e !== "number") { + options = e; + e = void 0; + } + } else { + options = bits; + callback = e; + bits = void 0; + e = void 0; + } + } else if (arguments.length === 3) { + if (typeof e === "number") { + if (typeof options === "function") { + callback = options; + options = void 0; + } + } else { + callback = options; + options = e; + e = void 0; + } + } + options = options || {}; + if (bits === void 0) { + bits = options.bits || 2048; + } + if (e === void 0) { + e = options.e || 65537; + } + if (!forge.options.usePureJavaScript && !options.prng && bits >= 256 && bits <= 16384 && (e === 65537 || e === 3)) { + if (callback) { + if (_detectNodeCrypto("generateKeyPair")) { + return _crypto.generateKeyPair("rsa", { + modulusLength: bits, + publicExponent: e, + publicKeyEncoding: { + type: "spki", + format: "pem" + }, + privateKeyEncoding: { + type: "pkcs8", + format: "pem" + } + }, function(err, pub, priv) { + if (err) { + return callback(err); + } + callback(null, { + privateKey: pki2.privateKeyFromPem(priv), + publicKey: pki2.publicKeyFromPem(pub) + }); + }); + } + if (_detectSubtleCrypto("generateKey") && _detectSubtleCrypto("exportKey")) { + return util.globalScope.crypto.subtle.generateKey({ + name: "RSASSA-PKCS1-v1_5", + modulusLength: bits, + publicExponent: _intToUint8Array(e), + hash: { name: "SHA-256" } + }, true, ["sign", "verify"]).then(function(pair) { + return util.globalScope.crypto.subtle.exportKey( + "pkcs8", + pair.privateKey + ); + }).then(void 0, function(err) { + callback(err); + }).then(function(pkcs8) { + if (pkcs8) { + var privateKey = pki2.privateKeyFromAsn1( + asn1.fromDer(forge.util.createBuffer(pkcs8)) + ); + callback(null, { + privateKey, + publicKey: pki2.setRsaPublicKey(privateKey.n, privateKey.e) + }); + } + }); + } + if (_detectSubtleMsCrypto("generateKey") && _detectSubtleMsCrypto("exportKey")) { + var genOp = util.globalScope.msCrypto.subtle.generateKey({ + name: "RSASSA-PKCS1-v1_5", + modulusLength: bits, + publicExponent: _intToUint8Array(e), + hash: { name: "SHA-256" } + }, true, ["sign", "verify"]); + genOp.oncomplete = function(e2) { + var pair = e2.target.result; + var exportOp = util.globalScope.msCrypto.subtle.exportKey( + "pkcs8", + pair.privateKey + ); + exportOp.oncomplete = function(e3) { + var pkcs8 = e3.target.result; + var privateKey = pki2.privateKeyFromAsn1( + asn1.fromDer(forge.util.createBuffer(pkcs8)) + ); + callback(null, { + privateKey, + publicKey: pki2.setRsaPublicKey(privateKey.n, privateKey.e) + }); + }; + exportOp.onerror = function(err) { + callback(err); + }; + }; + genOp.onerror = function(err) { + callback(err); + }; + return; + } + } else { + if (_detectNodeCrypto("generateKeyPairSync")) { + var keypair = _crypto.generateKeyPairSync("rsa", { + modulusLength: bits, + publicExponent: e, + publicKeyEncoding: { + type: "spki", + format: "pem" + }, + privateKeyEncoding: { + type: "pkcs8", + format: "pem" + } + }); + return { + privateKey: pki2.privateKeyFromPem(keypair.privateKey), + publicKey: pki2.publicKeyFromPem(keypair.publicKey) + }; + } + } + } + var state = pki2.rsa.createKeyPairGenerationState(bits, e, options); + if (!callback) { + pki2.rsa.stepKeyPairGenerationState(state, 0); + return state.keys; + } + _generateKeyPair(state, options, callback); + }; + pki2.setRsaPublicKey = pki2.rsa.setPublicKey = function(n, e) { + var key = { + n, + e + }; + key.encrypt = function(data, scheme, schemeOptions) { + if (typeof scheme === "string") { + scheme = scheme.toUpperCase(); + } else if (scheme === void 0) { + scheme = "RSAES-PKCS1-V1_5"; + } + if (scheme === "RSAES-PKCS1-V1_5") { + scheme = { + encode: function(m, key2, pub) { + return _encodePkcs1_v1_5(m, key2, 2).getBytes(); + } + }; + } else if (scheme === "RSA-OAEP" || scheme === "RSAES-OAEP") { + scheme = { + encode: function(m, key2) { + return forge.pkcs1.encode_rsa_oaep(key2, m, schemeOptions); + } + }; + } else if (["RAW", "NONE", "NULL", null].indexOf(scheme) !== -1) { + scheme = { encode: function(e3) { + return e3; + } }; + } else if (typeof scheme === "string") { + throw new Error('Unsupported encryption scheme: "' + scheme + '".'); + } + var e2 = scheme.encode(data, key, true); + return pki2.rsa.encrypt(e2, key, true); + }; + key.verify = function(digest, signature, scheme, options) { + if (typeof scheme === "string") { + scheme = scheme.toUpperCase(); + } else if (scheme === void 0) { + scheme = "RSASSA-PKCS1-V1_5"; + } + if (options === void 0) { + options = { + _parseAllDigestBytes: true, + _skipPaddingChecks: false + }; + } + if (!("_parseAllDigestBytes" in options)) { + options._parseAllDigestBytes = true; + } + if (!("_skipPaddingChecks" in options)) { + options._skipPaddingChecks = false; + } + if (scheme === "RSASSA-PKCS1-V1_5") { + scheme = { + verify: function(digest2, d2) { + d2 = _decodePkcs1_v1_5(d2, key, true, void 0, options); + var obj = asn1.fromDer(d2, { + parseAllBytes: options._parseAllDigestBytes + }); + var capture = {}; + var errors = []; + if (!asn1.validate(obj, digestInfoValidator, capture, errors) || obj.value.length !== 2) { + var error2 = new Error( + "ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value." + ); + error2.errors = errors; + throw error2; + } + var oid = asn1.derToOid(capture.algorithmIdentifier); + if (!(oid === forge.oids.md2 || oid === forge.oids.md5 || oid === forge.oids.sha1 || oid === forge.oids.sha224 || oid === forge.oids.sha256 || oid === forge.oids.sha384 || oid === forge.oids.sha512 || oid === forge.oids["sha512-224"] || oid === forge.oids["sha512-256"])) { + var error2 = new Error( + "Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier." + ); + error2.oid = oid; + throw error2; + } + if (oid === forge.oids.md2 || oid === forge.oids.md5) { + if (!("parameters" in capture)) { + throw new Error( + "ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifier NULL parameters." + ); + } + } + return digest2 === capture.digest; + } + }; + } else if (scheme === "NONE" || scheme === "NULL" || scheme === null) { + scheme = { + verify: function(digest2, d2) { + d2 = _decodePkcs1_v1_5(d2, key, true, void 0, options); + return digest2 === d2; + } + }; + } + var d = pki2.rsa.decrypt(signature, key, true, false); + return scheme.verify(digest, d, key.n.bitLength()); + }; + return key; + }; + pki2.setRsaPrivateKey = pki2.rsa.setPrivateKey = function(n, e, d, p, q, dP, dQ, qInv) { + var key = { + n, + e, + d, + p, + q, + dP, + dQ, + qInv + }; + key.decrypt = function(data, scheme, schemeOptions) { + if (typeof scheme === "string") { + scheme = scheme.toUpperCase(); + } else if (scheme === void 0) { + scheme = "RSAES-PKCS1-V1_5"; + } + var d2 = pki2.rsa.decrypt(data, key, false, false); + if (scheme === "RSAES-PKCS1-V1_5") { + scheme = { decode: _decodePkcs1_v1_5 }; + } else if (scheme === "RSA-OAEP" || scheme === "RSAES-OAEP") { + scheme = { + decode: function(d3, key2) { + return forge.pkcs1.decode_rsa_oaep(key2, d3, schemeOptions); + } + }; + } else if (["RAW", "NONE", "NULL", null].indexOf(scheme) !== -1) { + scheme = { decode: function(d3) { + return d3; + } }; + } else { + throw new Error('Unsupported encryption scheme: "' + scheme + '".'); + } + return scheme.decode(d2, key, false); + }; + key.sign = function(md2, scheme) { + var bt = false; + if (typeof scheme === "string") { + scheme = scheme.toUpperCase(); + } + if (scheme === void 0 || scheme === "RSASSA-PKCS1-V1_5") { + scheme = { encode: emsaPkcs1v15encode }; + bt = 1; + } else if (scheme === "NONE" || scheme === "NULL" || scheme === null) { + scheme = { encode: function() { + return md2; + } }; + bt = 1; + } + var d2 = scheme.encode(md2, key.n.bitLength()); + return pki2.rsa.encrypt(d2, key, bt); + }; + return key; + }; + pki2.wrapRsaPrivateKey = function(rsaKey) { + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // version (0) + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + asn1.integerToDer(0).getBytes() + ), + // privateKeyAlgorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(pki2.oids.rsaEncryption).getBytes() + ), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") + ]), + // PrivateKey + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + asn1.toDer(rsaKey).getBytes() + ) + ]); + }; + pki2.privateKeyFromAsn1 = function(obj) { + var capture = {}; + var errors = []; + if (asn1.validate(obj, privateKeyValidator, capture, errors)) { + obj = asn1.fromDer(forge.util.createBuffer(capture.privateKey)); + } + capture = {}; + errors = []; + if (!asn1.validate(obj, rsaPrivateKeyValidator, capture, errors)) { + var error2 = new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey."); + error2.errors = errors; + throw error2; + } + var n, e, d, p, q, dP, dQ, qInv; + n = forge.util.createBuffer(capture.privateKeyModulus).toHex(); + e = forge.util.createBuffer(capture.privateKeyPublicExponent).toHex(); + d = forge.util.createBuffer(capture.privateKeyPrivateExponent).toHex(); + p = forge.util.createBuffer(capture.privateKeyPrime1).toHex(); + q = forge.util.createBuffer(capture.privateKeyPrime2).toHex(); + dP = forge.util.createBuffer(capture.privateKeyExponent1).toHex(); + dQ = forge.util.createBuffer(capture.privateKeyExponent2).toHex(); + qInv = forge.util.createBuffer(capture.privateKeyCoefficient).toHex(); + return pki2.setRsaPrivateKey( + new BigInteger(n, 16), + new BigInteger(e, 16), + new BigInteger(d, 16), + new BigInteger(p, 16), + new BigInteger(q, 16), + new BigInteger(dP, 16), + new BigInteger(dQ, 16), + new BigInteger(qInv, 16) + ); + }; + pki2.privateKeyToAsn1 = pki2.privateKeyToRSAPrivateKey = function(key) { + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // version (0 = only 2 primes, 1 multiple primes) + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + asn1.integerToDer(0).getBytes() + ), + // modulus (n) + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + _bnToBytes(key.n) + ), + // publicExponent (e) + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + _bnToBytes(key.e) + ), + // privateExponent (d) + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + _bnToBytes(key.d) + ), + // privateKeyPrime1 (p) + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + _bnToBytes(key.p) + ), + // privateKeyPrime2 (q) + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + _bnToBytes(key.q) + ), + // privateKeyExponent1 (dP) + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + _bnToBytes(key.dP) + ), + // privateKeyExponent2 (dQ) + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + _bnToBytes(key.dQ) + ), + // coefficient (qInv) + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + _bnToBytes(key.qInv) + ) + ]); + }; + pki2.publicKeyFromAsn1 = function(obj) { + var capture = {}; + var errors = []; + if (asn1.validate(obj, publicKeyValidator, capture, errors)) { + var oid = asn1.derToOid(capture.publicKeyOid); + if (oid !== pki2.oids.rsaEncryption) { + var error2 = new Error("Cannot read public key. Unknown OID."); + error2.oid = oid; + throw error2; + } + obj = capture.rsaPublicKey; + } + errors = []; + if (!asn1.validate(obj, rsaPublicKeyValidator, capture, errors)) { + var error2 = new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey."); + error2.errors = errors; + throw error2; + } + var n = forge.util.createBuffer(capture.publicKeyModulus).toHex(); + var e = forge.util.createBuffer(capture.publicKeyExponent).toHex(); + return pki2.setRsaPublicKey( + new BigInteger(n, 16), + new BigInteger(e, 16) + ); + }; + pki2.publicKeyToAsn1 = pki2.publicKeyToSubjectPublicKeyInfo = function(key) { + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // AlgorithmIdentifier + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(pki2.oids.rsaEncryption).getBytes() + ), + // parameters (null) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") + ]), + // subjectPublicKey + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, [ + pki2.publicKeyToRSAPublicKey(key) + ]) + ]); + }; + pki2.publicKeyToRSAPublicKey = function(key) { + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // modulus (n) + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + _bnToBytes(key.n) + ), + // publicExponent (e) + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + _bnToBytes(key.e) + ) + ]); + }; + function _encodePkcs1_v1_5(m, key, bt) { + var eb = forge.util.createBuffer(); + var k = Math.ceil(key.n.bitLength() / 8); + if (m.length > k - 11) { + var error2 = new Error("Message is too long for PKCS#1 v1.5 padding."); + error2.length = m.length; + error2.max = k - 11; + throw error2; + } + eb.putByte(0); + eb.putByte(bt); + var padNum = k - 3 - m.length; + var padByte; + if (bt === 0 || bt === 1) { + padByte = bt === 0 ? 0 : 255; + for (var i = 0; i < padNum; ++i) { + eb.putByte(padByte); + } + } else { + while (padNum > 0) { + var numZeros = 0; + var padBytes = forge.random.getBytes(padNum); + for (var i = 0; i < padNum; ++i) { + padByte = padBytes.charCodeAt(i); + if (padByte === 0) { + ++numZeros; + } else { + eb.putByte(padByte); + } + } + padNum = numZeros; + } + } + eb.putByte(0); + eb.putBytes(m); + return eb; + } + function _decodePkcs1_v1_5(em, key, pub, ml, options) { + var k = Math.ceil(key.n.bitLength() / 8); + var eb = forge.util.createBuffer(em); + var first = eb.getByte(); + var bt = eb.getByte(); + if (first !== 0 || pub && bt !== 0 && bt !== 1 || !pub && bt !== 2 || pub && bt === 0 && typeof ml === "undefined") { + throw new Error("Encryption block is invalid."); + } + var padNum = 0; + if (bt === 0) { + padNum = k - 3 - ml; + for (var i = 0; i < padNum; ++i) { + if (eb.getByte() !== 0) { + throw new Error("Encryption block is invalid."); + } + } + } else if (bt === 1) { + padNum = 0; + while (eb.length() > 1) { + if (eb.getByte() !== 255) { + --eb.read; + break; + } + ++padNum; + } + if (padNum < 8 && !(options ? options._skipPaddingChecks : false)) { + throw new Error("Encryption block is invalid."); + } + } else if (bt === 2) { + padNum = 0; + while (eb.length() > 1) { + if (eb.getByte() === 0) { + --eb.read; + break; + } + ++padNum; + } + if (padNum < 8 && !(options ? options._skipPaddingChecks : false)) { + throw new Error("Encryption block is invalid."); + } + } + var zero = eb.getByte(); + if (zero !== 0 || padNum !== k - 3 - eb.length()) { + throw new Error("Encryption block is invalid."); + } + return eb.getBytes(); + } + function _generateKeyPair(state, options, callback) { + if (typeof options === "function") { + callback = options; + options = {}; + } + options = options || {}; + var opts = { + algorithm: { + name: options.algorithm || "PRIMEINC", + options: { + workers: options.workers || 2, + workLoad: options.workLoad || 100, + workerScript: options.workerScript + } + } + }; + if ("prng" in options) { + opts.prng = options.prng; + } + generate(); + function generate() { + getPrime(state.pBits, function(err, num) { + if (err) { + return callback(err); + } + state.p = num; + if (state.q !== null) { + return finish(err, state.q); + } + getPrime(state.qBits, finish); + }); + } + function getPrime(bits, callback2) { + forge.prime.generateProbablePrime(bits, opts, callback2); + } + function finish(err, num) { + if (err) { + return callback(err); + } + state.q = num; + if (state.p.compareTo(state.q) < 0) { + var tmp = state.p; + state.p = state.q; + state.q = tmp; + } + if (state.p.subtract(BigInteger.ONE).gcd(state.e).compareTo(BigInteger.ONE) !== 0) { + state.p = null; + generate(); + return; + } + if (state.q.subtract(BigInteger.ONE).gcd(state.e).compareTo(BigInteger.ONE) !== 0) { + state.q = null; + getPrime(state.qBits, finish); + return; + } + state.p1 = state.p.subtract(BigInteger.ONE); + state.q1 = state.q.subtract(BigInteger.ONE); + state.phi = state.p1.multiply(state.q1); + if (state.phi.gcd(state.e).compareTo(BigInteger.ONE) !== 0) { + state.p = state.q = null; + generate(); + return; + } + state.n = state.p.multiply(state.q); + if (state.n.bitLength() !== state.bits) { + state.q = null; + getPrime(state.qBits, finish); + return; + } + var d = state.e.modInverse(state.phi); + state.keys = { + privateKey: pki2.rsa.setPrivateKey( + state.n, + state.e, + d, + state.p, + state.q, + d.mod(state.p1), + d.mod(state.q1), + state.q.modInverse(state.p) + ), + publicKey: pki2.rsa.setPublicKey(state.n, state.e) + }; + callback(null, state.keys); + } + } + function _bnToBytes(b) { + var hex = b.toString(16); + if (hex[0] >= "8") { + hex = "00" + hex; + } + var bytes = forge.util.hexToBytes(hex); + if (bytes.length > 1 && // leading 0x00 for positive integer + (bytes.charCodeAt(0) === 0 && (bytes.charCodeAt(1) & 128) === 0 || // leading 0xFF for negative integer + bytes.charCodeAt(0) === 255 && (bytes.charCodeAt(1) & 128) === 128)) { + return bytes.substr(1); + } + return bytes; + } + function _getMillerRabinTests(bits) { + if (bits <= 100) return 27; + if (bits <= 150) return 18; + if (bits <= 200) return 15; + if (bits <= 250) return 12; + if (bits <= 300) return 9; + if (bits <= 350) return 8; + if (bits <= 400) return 7; + if (bits <= 500) return 6; + if (bits <= 600) return 5; + if (bits <= 800) return 4; + if (bits <= 1250) return 3; + return 2; + } + function _detectNodeCrypto(fn) { + return forge.util.isNodejs && typeof _crypto[fn] === "function"; + } + function _detectSubtleCrypto(fn) { + return typeof util.globalScope !== "undefined" && typeof util.globalScope.crypto === "object" && typeof util.globalScope.crypto.subtle === "object" && typeof util.globalScope.crypto.subtle[fn] === "function"; + } + function _detectSubtleMsCrypto(fn) { + return typeof util.globalScope !== "undefined" && typeof util.globalScope.msCrypto === "object" && typeof util.globalScope.msCrypto.subtle === "object" && typeof util.globalScope.msCrypto.subtle[fn] === "function"; + } + function _intToUint8Array(x) { + var bytes = forge.util.hexToBytes(x.toString(16)); + var buffer = new Uint8Array(bytes.length); + for (var i = 0; i < bytes.length; ++i) { + buffer[i] = bytes.charCodeAt(i); + } + return buffer; + } + } +}); + +// node_modules/node-forge/lib/pbe.js +var require_pbe = __commonJS({ + "node_modules/node-forge/lib/pbe.js"(exports2, module2) { + var forge = require_forge(); + require_aes(); + require_asn1(); + require_des(); + require_md(); + require_oids(); + require_pbkdf2(); + require_pem(); + require_random(); + require_rc2(); + require_rsa(); + require_util13(); + if (typeof BigInteger === "undefined") { + BigInteger = forge.jsbn.BigInteger; + } + var BigInteger; + var asn1 = forge.asn1; + var pki2 = forge.pki = forge.pki || {}; + module2.exports = pki2.pbe = forge.pbe = forge.pbe || {}; + var oids = pki2.oids; + var encryptedPrivateKeyValidator = { + name: "EncryptedPrivateKeyInfo", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "EncryptedPrivateKeyInfo.encryptionAlgorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "AlgorithmIdentifier.algorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "encryptionOid" + }, { + name: "AlgorithmIdentifier.parameters", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: "encryptionParams" + }] + }, { + // encryptedData + name: "EncryptedPrivateKeyInfo.encryptedData", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: "encryptedData" + }] + }; + var PBES2AlgorithmsValidator = { + name: "PBES2Algorithms", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "PBES2Algorithms.keyDerivationFunc", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "PBES2Algorithms.keyDerivationFunc.oid", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "kdfOid" + }, { + name: "PBES2Algorithms.params", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "PBES2Algorithms.params.salt", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: "kdfSalt" + }, { + name: "PBES2Algorithms.params.iterationCount", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "kdfIterationCount" + }, { + name: "PBES2Algorithms.params.keyLength", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + optional: true, + capture: "keyLength" + }, { + // prf + name: "PBES2Algorithms.params.prf", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + optional: true, + value: [{ + name: "PBES2Algorithms.params.prf.algorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "prfOid" + }] + }] + }] + }, { + name: "PBES2Algorithms.encryptionScheme", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "PBES2Algorithms.encryptionScheme.oid", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "encOid" + }, { + name: "PBES2Algorithms.encryptionScheme.iv", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: "encIv" + }] + }] + }; + var pkcs12PbeParamsValidator = { + name: "pkcs-12PbeParams", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "pkcs-12PbeParams.salt", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: "salt" + }, { + name: "pkcs-12PbeParams.iterations", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "iterations" + }] + }; + pki2.encryptPrivateKeyInfo = function(obj, password, options) { + options = options || {}; + options.saltSize = options.saltSize || 8; + options.count = options.count || 2048; + options.algorithm = options.algorithm || "aes128"; + options.prfAlgorithm = options.prfAlgorithm || "sha1"; + var salt = forge.random.getBytesSync(options.saltSize); + var count = options.count; + var countBytes = asn1.integerToDer(count); + var dkLen; + var encryptionAlgorithm; + var encryptedData; + if (options.algorithm.indexOf("aes") === 0 || options.algorithm === "des") { + var ivLen, encOid, cipherFn; + switch (options.algorithm) { + case "aes128": + dkLen = 16; + ivLen = 16; + encOid = oids["aes128-CBC"]; + cipherFn = forge.aes.createEncryptionCipher; + break; + case "aes192": + dkLen = 24; + ivLen = 16; + encOid = oids["aes192-CBC"]; + cipherFn = forge.aes.createEncryptionCipher; + break; + case "aes256": + dkLen = 32; + ivLen = 16; + encOid = oids["aes256-CBC"]; + cipherFn = forge.aes.createEncryptionCipher; + break; + case "des": + dkLen = 8; + ivLen = 8; + encOid = oids["desCBC"]; + cipherFn = forge.des.createEncryptionCipher; + break; + default: + var error2 = new Error("Cannot encrypt private key. Unknown encryption algorithm."); + error2.algorithm = options.algorithm; + throw error2; + } + var prfAlgorithm = "hmacWith" + options.prfAlgorithm.toUpperCase(); + var md2 = prfAlgorithmToMessageDigest(prfAlgorithm); + var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md2); + var iv = forge.random.getBytesSync(ivLen); + var cipher = cipherFn(dk); + cipher.start(iv); + cipher.update(asn1.toDer(obj)); + cipher.finish(); + encryptedData = cipher.output.getBytes(); + var params = createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm); + encryptionAlgorithm = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SEQUENCE, + true, + [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(oids["pkcs5PBES2"]).getBytes() + ), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // keyDerivationFunc + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(oids["pkcs5PBKDF2"]).getBytes() + ), + // PBKDF2-params + params + ]), + // encryptionScheme + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(encOid).getBytes() + ), + // iv + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + iv + ) + ]) + ]) + ] + ); + } else if (options.algorithm === "3des") { + dkLen = 24; + var saltBytes = new forge.util.ByteBuffer(salt); + var dk = pki2.pbe.generatePkcs12Key(password, saltBytes, 1, count, dkLen); + var iv = pki2.pbe.generatePkcs12Key(password, saltBytes, 2, count, dkLen); + var cipher = forge.des.createEncryptionCipher(dk); + cipher.start(iv); + cipher.update(asn1.toDer(obj)); + cipher.finish(); + encryptedData = cipher.output.getBytes(); + encryptionAlgorithm = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SEQUENCE, + true, + [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes() + ), + // pkcs-12PbeParams + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // salt + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt), + // iteration count + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + countBytes.getBytes() + ) + ]) + ] + ); + } else { + var error2 = new Error("Cannot encrypt private key. Unknown encryption algorithm."); + error2.algorithm = options.algorithm; + throw error2; + } + var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // encryptionAlgorithm + encryptionAlgorithm, + // encryptedData + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + encryptedData + ) + ]); + return rval; + }; + pki2.decryptPrivateKeyInfo = function(obj, password) { + var rval = null; + var capture = {}; + var errors = []; + if (!asn1.validate(obj, encryptedPrivateKeyValidator, capture, errors)) { + var error2 = new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo."); + error2.errors = errors; + throw error2; + } + var oid = asn1.derToOid(capture.encryptionOid); + var cipher = pki2.pbe.getCipher(oid, capture.encryptionParams, password); + var encrypted = forge.util.createBuffer(capture.encryptedData); + cipher.update(encrypted); + if (cipher.finish()) { + rval = asn1.fromDer(cipher.output); + } + return rval; + }; + pki2.encryptedPrivateKeyToPem = function(epki, maxline) { + var msg = { + type: "ENCRYPTED PRIVATE KEY", + body: asn1.toDer(epki).getBytes() + }; + return forge.pem.encode(msg, { maxline }); + }; + pki2.encryptedPrivateKeyFromPem = function(pem) { + var msg = forge.pem.decode(pem)[0]; + if (msg.type !== "ENCRYPTED PRIVATE KEY") { + var error2 = new Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".'); + error2.headerType = msg.type; + throw error2; + } + if (msg.procType && msg.procType.type === "ENCRYPTED") { + throw new Error("Could not convert encrypted private key from PEM; PEM is encrypted."); + } + return asn1.fromDer(msg.body); + }; + pki2.encryptRsaPrivateKey = function(rsaKey, password, options) { + options = options || {}; + if (!options.legacy) { + var rval = pki2.wrapRsaPrivateKey(pki2.privateKeyToAsn1(rsaKey)); + rval = pki2.encryptPrivateKeyInfo(rval, password, options); + return pki2.encryptedPrivateKeyToPem(rval); + } + var algorithm; + var iv; + var dkLen; + var cipherFn; + switch (options.algorithm) { + case "aes128": + algorithm = "AES-128-CBC"; + dkLen = 16; + iv = forge.random.getBytesSync(16); + cipherFn = forge.aes.createEncryptionCipher; + break; + case "aes192": + algorithm = "AES-192-CBC"; + dkLen = 24; + iv = forge.random.getBytesSync(16); + cipherFn = forge.aes.createEncryptionCipher; + break; + case "aes256": + algorithm = "AES-256-CBC"; + dkLen = 32; + iv = forge.random.getBytesSync(16); + cipherFn = forge.aes.createEncryptionCipher; + break; + case "3des": + algorithm = "DES-EDE3-CBC"; + dkLen = 24; + iv = forge.random.getBytesSync(8); + cipherFn = forge.des.createEncryptionCipher; + break; + case "des": + algorithm = "DES-CBC"; + dkLen = 8; + iv = forge.random.getBytesSync(8); + cipherFn = forge.des.createEncryptionCipher; + break; + default: + var error2 = new Error('Could not encrypt RSA private key; unsupported encryption algorithm "' + options.algorithm + '".'); + error2.algorithm = options.algorithm; + throw error2; + } + var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen); + var cipher = cipherFn(dk); + cipher.start(iv); + cipher.update(asn1.toDer(pki2.privateKeyToAsn1(rsaKey))); + cipher.finish(); + var msg = { + type: "RSA PRIVATE KEY", + procType: { + version: "4", + type: "ENCRYPTED" + }, + dekInfo: { + algorithm, + parameters: forge.util.bytesToHex(iv).toUpperCase() + }, + body: cipher.output.getBytes() + }; + return forge.pem.encode(msg); + }; + pki2.decryptRsaPrivateKey = function(pem, password) { + var rval = null; + var msg = forge.pem.decode(pem)[0]; + if (msg.type !== "ENCRYPTED PRIVATE KEY" && msg.type !== "PRIVATE KEY" && msg.type !== "RSA PRIVATE KEY") { + var error2 = new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".'); + error2.headerType = error2; + throw error2; + } + if (msg.procType && msg.procType.type === "ENCRYPTED") { + var dkLen; + var cipherFn; + switch (msg.dekInfo.algorithm) { + case "DES-CBC": + dkLen = 8; + cipherFn = forge.des.createDecryptionCipher; + break; + case "DES-EDE3-CBC": + dkLen = 24; + cipherFn = forge.des.createDecryptionCipher; + break; + case "AES-128-CBC": + dkLen = 16; + cipherFn = forge.aes.createDecryptionCipher; + break; + case "AES-192-CBC": + dkLen = 24; + cipherFn = forge.aes.createDecryptionCipher; + break; + case "AES-256-CBC": + dkLen = 32; + cipherFn = forge.aes.createDecryptionCipher; + break; + case "RC2-40-CBC": + dkLen = 5; + cipherFn = function(key) { + return forge.rc2.createDecryptionCipher(key, 40); + }; + break; + case "RC2-64-CBC": + dkLen = 8; + cipherFn = function(key) { + return forge.rc2.createDecryptionCipher(key, 64); + }; + break; + case "RC2-128-CBC": + dkLen = 16; + cipherFn = function(key) { + return forge.rc2.createDecryptionCipher(key, 128); + }; + break; + default: + var error2 = new Error('Could not decrypt private key; unsupported encryption algorithm "' + msg.dekInfo.algorithm + '".'); + error2.algorithm = msg.dekInfo.algorithm; + throw error2; + } + var iv = forge.util.hexToBytes(msg.dekInfo.parameters); + var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen); + var cipher = cipherFn(dk); + cipher.start(iv); + cipher.update(forge.util.createBuffer(msg.body)); + if (cipher.finish()) { + rval = cipher.output.getBytes(); + } else { + return rval; + } + } else { + rval = msg.body; + } + if (msg.type === "ENCRYPTED PRIVATE KEY") { + rval = pki2.decryptPrivateKeyInfo(asn1.fromDer(rval), password); + } else { + rval = asn1.fromDer(rval); + } + if (rval !== null) { + rval = pki2.privateKeyFromAsn1(rval); + } + return rval; + }; + pki2.pbe.generatePkcs12Key = function(password, salt, id, iter, n, md2) { + var j, l; + if (typeof md2 === "undefined" || md2 === null) { + if (!("sha1" in forge.md)) { + throw new Error('"sha1" hash algorithm unavailable.'); + } + md2 = forge.md.sha1.create(); + } + var u = md2.digestLength; + var v = md2.blockLength; + var result = new forge.util.ByteBuffer(); + var passBuf = new forge.util.ByteBuffer(); + if (password !== null && password !== void 0) { + for (l = 0; l < password.length; l++) { + passBuf.putInt16(password.charCodeAt(l)); + } + passBuf.putInt16(0); + } + var p = passBuf.length(); + var s = salt.length(); + var D = new forge.util.ByteBuffer(); + D.fillWithByte(id, v); + var Slen = v * Math.ceil(s / v); + var S = new forge.util.ByteBuffer(); + for (l = 0; l < Slen; l++) { + S.putByte(salt.at(l % s)); + } + var Plen = v * Math.ceil(p / v); + var P = new forge.util.ByteBuffer(); + for (l = 0; l < Plen; l++) { + P.putByte(passBuf.at(l % p)); + } + var I = S; + I.putBuffer(P); + var c = Math.ceil(n / u); + for (var i = 1; i <= c; i++) { + var buf = new forge.util.ByteBuffer(); + buf.putBytes(D.bytes()); + buf.putBytes(I.bytes()); + for (var round = 0; round < iter; round++) { + md2.start(); + md2.update(buf.getBytes()); + buf = md2.digest(); + } + var B = new forge.util.ByteBuffer(); + for (l = 0; l < v; l++) { + B.putByte(buf.at(l % u)); + } + var k = Math.ceil(s / v) + Math.ceil(p / v); + var Inew = new forge.util.ByteBuffer(); + for (j = 0; j < k; j++) { + var chunk = new forge.util.ByteBuffer(I.getBytes(v)); + var x = 511; + for (l = B.length() - 1; l >= 0; l--) { + x = x >> 8; + x += B.at(l) + chunk.at(l); + chunk.setAt(l, x & 255); + } + Inew.putBuffer(chunk); + } + I = Inew; + result.putBuffer(buf); + } + result.truncate(result.length() - n); + return result; + }; + pki2.pbe.getCipher = function(oid, params, password) { + switch (oid) { + case pki2.oids["pkcs5PBES2"]: + return pki2.pbe.getCipherForPBES2(oid, params, password); + case pki2.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]: + case pki2.oids["pbewithSHAAnd40BitRC2-CBC"]: + return pki2.pbe.getCipherForPKCS12PBE(oid, params, password); + default: + var error2 = new Error("Cannot read encrypted PBE data block. Unsupported OID."); + error2.oid = oid; + error2.supportedOids = [ + "pkcs5PBES2", + "pbeWithSHAAnd3-KeyTripleDES-CBC", + "pbewithSHAAnd40BitRC2-CBC" + ]; + throw error2; + } + }; + pki2.pbe.getCipherForPBES2 = function(oid, params, password) { + var capture = {}; + var errors = []; + if (!asn1.validate(params, PBES2AlgorithmsValidator, capture, errors)) { + var error2 = new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo."); + error2.errors = errors; + throw error2; + } + oid = asn1.derToOid(capture.kdfOid); + if (oid !== pki2.oids["pkcs5PBKDF2"]) { + var error2 = new Error("Cannot read encrypted private key. Unsupported key derivation function OID."); + error2.oid = oid; + error2.supportedOids = ["pkcs5PBKDF2"]; + throw error2; + } + oid = asn1.derToOid(capture.encOid); + if (oid !== pki2.oids["aes128-CBC"] && oid !== pki2.oids["aes192-CBC"] && oid !== pki2.oids["aes256-CBC"] && oid !== pki2.oids["des-EDE3-CBC"] && oid !== pki2.oids["desCBC"]) { + var error2 = new Error("Cannot read encrypted private key. Unsupported encryption scheme OID."); + error2.oid = oid; + error2.supportedOids = [ + "aes128-CBC", + "aes192-CBC", + "aes256-CBC", + "des-EDE3-CBC", + "desCBC" + ]; + throw error2; + } + var salt = capture.kdfSalt; + var count = forge.util.createBuffer(capture.kdfIterationCount); + count = count.getInt(count.length() << 3); + var dkLen; + var cipherFn; + switch (pki2.oids[oid]) { + case "aes128-CBC": + dkLen = 16; + cipherFn = forge.aes.createDecryptionCipher; + break; + case "aes192-CBC": + dkLen = 24; + cipherFn = forge.aes.createDecryptionCipher; + break; + case "aes256-CBC": + dkLen = 32; + cipherFn = forge.aes.createDecryptionCipher; + break; + case "des-EDE3-CBC": + dkLen = 24; + cipherFn = forge.des.createDecryptionCipher; + break; + case "desCBC": + dkLen = 8; + cipherFn = forge.des.createDecryptionCipher; + break; + } + var md2 = prfOidToMessageDigest(capture.prfOid); + var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md2); + var iv = capture.encIv; + var cipher = cipherFn(dk); + cipher.start(iv); + return cipher; + }; + pki2.pbe.getCipherForPKCS12PBE = function(oid, params, password) { + var capture = {}; + var errors = []; + if (!asn1.validate(params, pkcs12PbeParamsValidator, capture, errors)) { + var error2 = new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo."); + error2.errors = errors; + throw error2; + } + var salt = forge.util.createBuffer(capture.salt); + var count = forge.util.createBuffer(capture.iterations); + count = count.getInt(count.length() << 3); + var dkLen, dIvLen, cipherFn; + switch (oid) { + case pki2.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]: + dkLen = 24; + dIvLen = 8; + cipherFn = forge.des.startDecrypting; + break; + case pki2.oids["pbewithSHAAnd40BitRC2-CBC"]: + dkLen = 5; + dIvLen = 8; + cipherFn = function(key2, iv2) { + var cipher = forge.rc2.createDecryptionCipher(key2, 40); + cipher.start(iv2, null); + return cipher; + }; + break; + default: + var error2 = new Error("Cannot read PKCS #12 PBE data block. Unsupported OID."); + error2.oid = oid; + throw error2; + } + var md2 = prfOidToMessageDigest(capture.prfOid); + var key = pki2.pbe.generatePkcs12Key(password, salt, 1, count, dkLen, md2); + md2.start(); + var iv = pki2.pbe.generatePkcs12Key(password, salt, 2, count, dIvLen, md2); + return cipherFn(key, iv); + }; + pki2.pbe.opensslDeriveBytes = function(password, salt, dkLen, md2) { + if (typeof md2 === "undefined" || md2 === null) { + if (!("md5" in forge.md)) { + throw new Error('"md5" hash algorithm unavailable.'); + } + md2 = forge.md.md5.create(); + } + if (salt === null) { + salt = ""; + } + var digests = [hash(md2, password + salt)]; + for (var length = 16, i = 1; length < dkLen; ++i, length += 16) { + digests.push(hash(md2, digests[i - 1] + password + salt)); + } + return digests.join("").substr(0, dkLen); + }; + function hash(md2, bytes) { + return md2.start().update(bytes).digest().getBytes(); + } + function prfOidToMessageDigest(prfOid) { + var prfAlgorithm; + if (!prfOid) { + prfAlgorithm = "hmacWithSHA1"; + } else { + prfAlgorithm = pki2.oids[asn1.derToOid(prfOid)]; + if (!prfAlgorithm) { + var error2 = new Error("Unsupported PRF OID."); + error2.oid = prfOid; + error2.supported = [ + "hmacWithSHA1", + "hmacWithSHA224", + "hmacWithSHA256", + "hmacWithSHA384", + "hmacWithSHA512" + ]; + throw error2; + } + } + return prfAlgorithmToMessageDigest(prfAlgorithm); + } + function prfAlgorithmToMessageDigest(prfAlgorithm) { + var factory = forge.md; + switch (prfAlgorithm) { + case "hmacWithSHA224": + factory = forge.md.sha512; + case "hmacWithSHA1": + case "hmacWithSHA256": + case "hmacWithSHA384": + case "hmacWithSHA512": + prfAlgorithm = prfAlgorithm.substr(8).toLowerCase(); + break; + default: + var error2 = new Error("Unsupported PRF algorithm."); + error2.algorithm = prfAlgorithm; + error2.supported = [ + "hmacWithSHA1", + "hmacWithSHA224", + "hmacWithSHA256", + "hmacWithSHA384", + "hmacWithSHA512" + ]; + throw error2; + } + if (!factory || !(prfAlgorithm in factory)) { + throw new Error("Unknown hash algorithm: " + prfAlgorithm); + } + return factory[prfAlgorithm].create(); + } + function createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm) { + var params = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // salt + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + salt + ), + // iteration count + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + countBytes.getBytes() + ) + ]); + if (prfAlgorithm !== "hmacWithSHA1") { + params.value.push( + // key length + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + forge.util.hexToBytes(dkLen.toString(16)) + ), + // AlgorithmIdentifier + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(pki2.oids[prfAlgorithm]).getBytes() + ), + // parameters (null) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") + ]) + ); + } + return params; + } + } +}); + +// node_modules/node-forge/lib/pkcs7asn1.js +var require_pkcs7asn1 = __commonJS({ + "node_modules/node-forge/lib/pkcs7asn1.js"(exports2, module2) { + var forge = require_forge(); + require_asn1(); + require_util13(); + var asn1 = forge.asn1; + var p7v = module2.exports = forge.pkcs7asn1 = forge.pkcs7asn1 || {}; + forge.pkcs7 = forge.pkcs7 || {}; + forge.pkcs7.asn1 = p7v; + var contentInfoValidator = { + name: "ContentInfo", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "ContentInfo.ContentType", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "contentType" + }, { + name: "ContentInfo.content", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + optional: true, + captureAsn1: "content" + }] + }; + p7v.contentInfoValidator = contentInfoValidator; + var encryptedContentInfoValidator = { + name: "EncryptedContentInfo", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "EncryptedContentInfo.contentType", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "contentType" + }, { + name: "EncryptedContentInfo.contentEncryptionAlgorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "EncryptedContentInfo.contentEncryptionAlgorithm.algorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "encAlgorithm" + }, { + name: "EncryptedContentInfo.contentEncryptionAlgorithm.parameter", + tagClass: asn1.Class.UNIVERSAL, + captureAsn1: "encParameter" + }] + }, { + name: "EncryptedContentInfo.encryptedContent", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + /* The PKCS#7 structure output by OpenSSL somewhat differs from what + * other implementations do generate. + * + * OpenSSL generates a structure like this: + * SEQUENCE { + * ... + * [0] + * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38 + * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45 + * ... + * } + * + * Whereas other implementations (and this PKCS#7 module) generate: + * SEQUENCE { + * ... + * [0] { + * OCTET STRING + * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38 + * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45 + * ... + * } + * } + * + * In order to support both, we just capture the context specific + * field here. The OCTET STRING bit is removed below. + */ + capture: "encryptedContent", + captureAsn1: "encryptedContentAsn1" + }] + }; + p7v.envelopedDataValidator = { + name: "EnvelopedData", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "EnvelopedData.Version", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "version" + }, { + name: "EnvelopedData.RecipientInfos", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + constructed: true, + captureAsn1: "recipientInfos" + }].concat(encryptedContentInfoValidator) + }; + p7v.encryptedDataValidator = { + name: "EncryptedData", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "EncryptedData.Version", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "version" + }].concat(encryptedContentInfoValidator) + }; + var signerValidator = { + name: "SignerInfo", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "SignerInfo.version", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false + }, { + name: "SignerInfo.issuerAndSerialNumber", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "SignerInfo.issuerAndSerialNumber.issuer", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: "issuer" + }, { + name: "SignerInfo.issuerAndSerialNumber.serialNumber", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "serial" + }] + }, { + name: "SignerInfo.digestAlgorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "SignerInfo.digestAlgorithm.algorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "digestAlgorithm" + }, { + name: "SignerInfo.digestAlgorithm.parameter", + tagClass: asn1.Class.UNIVERSAL, + constructed: false, + captureAsn1: "digestParameter", + optional: true + }] + }, { + name: "SignerInfo.authenticatedAttributes", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + optional: true, + capture: "authenticatedAttributes" + }, { + name: "SignerInfo.digestEncryptionAlgorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + capture: "signatureAlgorithm" + }, { + name: "SignerInfo.encryptedDigest", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: "signature" + }, { + name: "SignerInfo.unauthenticatedAttributes", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 1, + constructed: true, + optional: true, + capture: "unauthenticatedAttributes" + }] + }; + p7v.signedDataValidator = { + name: "SignedData", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: "SignedData.Version", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "version" + }, + { + name: "SignedData.DigestAlgorithms", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + constructed: true, + captureAsn1: "digestAlgorithms" + }, + contentInfoValidator, + { + name: "SignedData.Certificates", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + optional: true, + captureAsn1: "certificates" + }, + { + name: "SignedData.CertificateRevocationLists", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 1, + optional: true, + captureAsn1: "crls" + }, + { + name: "SignedData.SignerInfos", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + capture: "signerInfos", + optional: true, + value: [signerValidator] + } + ] + }; + p7v.recipientInfoValidator = { + name: "RecipientInfo", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "RecipientInfo.version", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "version" + }, { + name: "RecipientInfo.issuerAndSerial", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "RecipientInfo.issuerAndSerial.issuer", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: "issuer" + }, { + name: "RecipientInfo.issuerAndSerial.serialNumber", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "serial" + }] + }, { + name: "RecipientInfo.keyEncryptionAlgorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "RecipientInfo.keyEncryptionAlgorithm.algorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "encAlgorithm" + }, { + name: "RecipientInfo.keyEncryptionAlgorithm.parameter", + tagClass: asn1.Class.UNIVERSAL, + constructed: false, + captureAsn1: "encParameter", + optional: true + }] + }, { + name: "RecipientInfo.encryptedKey", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: "encKey" + }] + }; + } +}); + +// node_modules/node-forge/lib/mgf1.js +var require_mgf1 = __commonJS({ + "node_modules/node-forge/lib/mgf1.js"(exports2, module2) { + var forge = require_forge(); + require_util13(); + forge.mgf = forge.mgf || {}; + var mgf1 = module2.exports = forge.mgf.mgf1 = forge.mgf1 = forge.mgf1 || {}; + mgf1.create = function(md2) { + var mgf = { + /** + * Generate mask of specified length. + * + * @param {String} seed The seed for mask generation. + * @param maskLen Number of bytes to generate. + * @return {String} The generated mask. + */ + generate: function(seed, maskLen) { + var t = new forge.util.ByteBuffer(); + var len = Math.ceil(maskLen / md2.digestLength); + for (var i = 0; i < len; i++) { + var c = new forge.util.ByteBuffer(); + c.putInt32(i); + md2.start(); + md2.update(seed + c.getBytes()); + t.putBuffer(md2.digest()); + } + t.truncate(t.length() - maskLen); + return t.getBytes(); + } + }; + return mgf; + }; + } +}); + +// node_modules/node-forge/lib/mgf.js +var require_mgf = __commonJS({ + "node_modules/node-forge/lib/mgf.js"(exports2, module2) { + var forge = require_forge(); + require_mgf1(); + module2.exports = forge.mgf = forge.mgf || {}; + forge.mgf.mgf1 = forge.mgf1; + } +}); + +// node_modules/node-forge/lib/pss.js +var require_pss = __commonJS({ + "node_modules/node-forge/lib/pss.js"(exports2, module2) { + var forge = require_forge(); + require_random(); + require_util13(); + var pss = module2.exports = forge.pss = forge.pss || {}; + pss.create = function(options) { + if (arguments.length === 3) { + options = { + md: arguments[0], + mgf: arguments[1], + saltLength: arguments[2] + }; + } + var hash = options.md; + var mgf = options.mgf; + var hLen = hash.digestLength; + var salt_ = options.salt || null; + if (typeof salt_ === "string") { + salt_ = forge.util.createBuffer(salt_); + } + var sLen; + if ("saltLength" in options) { + sLen = options.saltLength; + } else if (salt_ !== null) { + sLen = salt_.length(); + } else { + throw new Error("Salt length not specified or specific salt not given."); + } + if (salt_ !== null && salt_.length() !== sLen) { + throw new Error("Given salt length does not match length of given salt."); + } + var prng = options.prng || forge.random; + var pssobj = {}; + pssobj.encode = function(md2, modBits) { + var i; + var emBits = modBits - 1; + var emLen = Math.ceil(emBits / 8); + var mHash = md2.digest().getBytes(); + if (emLen < hLen + sLen + 2) { + throw new Error("Message is too long to encrypt."); + } + var salt; + if (salt_ === null) { + salt = prng.getBytesSync(sLen); + } else { + salt = salt_.bytes(); + } + var m_ = new forge.util.ByteBuffer(); + m_.fillWithByte(0, 8); + m_.putBytes(mHash); + m_.putBytes(salt); + hash.start(); + hash.update(m_.getBytes()); + var h = hash.digest().getBytes(); + var ps = new forge.util.ByteBuffer(); + ps.fillWithByte(0, emLen - sLen - hLen - 2); + ps.putByte(1); + ps.putBytes(salt); + var db = ps.getBytes(); + var maskLen = emLen - hLen - 1; + var dbMask = mgf.generate(h, maskLen); + var maskedDB = ""; + for (i = 0; i < maskLen; i++) { + maskedDB += String.fromCharCode(db.charCodeAt(i) ^ dbMask.charCodeAt(i)); + } + var mask = 65280 >> 8 * emLen - emBits & 255; + maskedDB = String.fromCharCode(maskedDB.charCodeAt(0) & ~mask) + maskedDB.substr(1); + return maskedDB + h + String.fromCharCode(188); + }; + pssobj.verify = function(mHash, em, modBits) { + var i; + var emBits = modBits - 1; + var emLen = Math.ceil(emBits / 8); + em = em.substr(-emLen); + if (emLen < hLen + sLen + 2) { + throw new Error("Inconsistent parameters to PSS signature verification."); + } + if (em.charCodeAt(emLen - 1) !== 188) { + throw new Error("Encoded message does not end in 0xBC."); + } + var maskLen = emLen - hLen - 1; + var maskedDB = em.substr(0, maskLen); + var h = em.substr(maskLen, hLen); + var mask = 65280 >> 8 * emLen - emBits & 255; + if ((maskedDB.charCodeAt(0) & mask) !== 0) { + throw new Error("Bits beyond keysize not zero as expected."); + } + var dbMask = mgf.generate(h, maskLen); + var db = ""; + for (i = 0; i < maskLen; i++) { + db += String.fromCharCode(maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i)); + } + db = String.fromCharCode(db.charCodeAt(0) & ~mask) + db.substr(1); + var checkLen = emLen - hLen - sLen - 2; + for (i = 0; i < checkLen; i++) { + if (db.charCodeAt(i) !== 0) { + throw new Error("Leftmost octets not zero as expected"); + } + } + if (db.charCodeAt(checkLen) !== 1) { + throw new Error("Inconsistent PSS signature, 0x01 marker not found"); + } + var salt = db.substr(-sLen); + var m_ = new forge.util.ByteBuffer(); + m_.fillWithByte(0, 8); + m_.putBytes(mHash); + m_.putBytes(salt); + hash.start(); + hash.update(m_.getBytes()); + var h_ = hash.digest().getBytes(); + return h === h_; + }; + return pssobj; + }; + } +}); + +// node_modules/node-forge/lib/x509.js +var require_x509 = __commonJS({ + "node_modules/node-forge/lib/x509.js"(exports2, module2) { + var forge = require_forge(); + require_aes(); + require_asn1(); + require_des(); + require_md(); + require_mgf(); + require_oids(); + require_pem(); + require_pss(); + require_rsa(); + require_util13(); + var asn1 = forge.asn1; + var pki2 = module2.exports = forge.pki = forge.pki || {}; + var oids = pki2.oids; + var _shortNames = {}; + _shortNames["CN"] = oids["commonName"]; + _shortNames["commonName"] = "CN"; + _shortNames["C"] = oids["countryName"]; + _shortNames["countryName"] = "C"; + _shortNames["L"] = oids["localityName"]; + _shortNames["localityName"] = "L"; + _shortNames["ST"] = oids["stateOrProvinceName"]; + _shortNames["stateOrProvinceName"] = "ST"; + _shortNames["O"] = oids["organizationName"]; + _shortNames["organizationName"] = "O"; + _shortNames["OU"] = oids["organizationalUnitName"]; + _shortNames["organizationalUnitName"] = "OU"; + _shortNames["E"] = oids["emailAddress"]; + _shortNames["emailAddress"] = "E"; + var publicKeyValidator = forge.pki.rsa.publicKeyValidator; + var x509CertificateValidator = { + name: "Certificate", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "Certificate.TBSCertificate", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: "tbsCertificate", + value: [ + { + name: "Certificate.TBSCertificate.version", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + optional: true, + value: [{ + name: "Certificate.TBSCertificate.version.integer", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "certVersion" + }] + }, + { + name: "Certificate.TBSCertificate.serialNumber", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "certSerialNumber" + }, + { + name: "Certificate.TBSCertificate.signature", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "Certificate.TBSCertificate.signature.algorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "certinfoSignatureOid" + }, { + name: "Certificate.TBSCertificate.signature.parameters", + tagClass: asn1.Class.UNIVERSAL, + optional: true, + captureAsn1: "certinfoSignatureParams" + }] + }, + { + name: "Certificate.TBSCertificate.issuer", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: "certIssuer" + }, + { + name: "Certificate.TBSCertificate.validity", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + // Note: UTC and generalized times may both appear so the capture + // names are based on their detected order, the names used below + // are only for the common case, which validity time really means + // "notBefore" and which means "notAfter" will be determined by order + value: [{ + // notBefore (Time) (UTC time case) + name: "Certificate.TBSCertificate.validity.notBefore (utc)", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.UTCTIME, + constructed: false, + optional: true, + capture: "certValidity1UTCTime" + }, { + // notBefore (Time) (generalized time case) + name: "Certificate.TBSCertificate.validity.notBefore (generalized)", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.GENERALIZEDTIME, + constructed: false, + optional: true, + capture: "certValidity2GeneralizedTime" + }, { + // notAfter (Time) (only UTC time is supported) + name: "Certificate.TBSCertificate.validity.notAfter (utc)", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.UTCTIME, + constructed: false, + optional: true, + capture: "certValidity3UTCTime" + }, { + // notAfter (Time) (only UTC time is supported) + name: "Certificate.TBSCertificate.validity.notAfter (generalized)", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.GENERALIZEDTIME, + constructed: false, + optional: true, + capture: "certValidity4GeneralizedTime" + }] + }, + { + // Name (subject) (RDNSequence) + name: "Certificate.TBSCertificate.subject", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: "certSubject" + }, + // SubjectPublicKeyInfo + publicKeyValidator, + { + // issuerUniqueID (optional) + name: "Certificate.TBSCertificate.issuerUniqueID", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 1, + constructed: true, + optional: true, + value: [{ + name: "Certificate.TBSCertificate.issuerUniqueID.id", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + // TODO: support arbitrary bit length ids + captureBitStringValue: "certIssuerUniqueId" + }] + }, + { + // subjectUniqueID (optional) + name: "Certificate.TBSCertificate.subjectUniqueID", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 2, + constructed: true, + optional: true, + value: [{ + name: "Certificate.TBSCertificate.subjectUniqueID.id", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + // TODO: support arbitrary bit length ids + captureBitStringValue: "certSubjectUniqueId" + }] + }, + { + // Extensions (optional) + name: "Certificate.TBSCertificate.extensions", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 3, + constructed: true, + captureAsn1: "certExtensions", + optional: true + } + ] + }, { + // AlgorithmIdentifier (signature algorithm) + name: "Certificate.signatureAlgorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + // algorithm + name: "Certificate.signatureAlgorithm.algorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "certSignatureOid" + }, { + name: "Certificate.TBSCertificate.signature.parameters", + tagClass: asn1.Class.UNIVERSAL, + optional: true, + captureAsn1: "certSignatureParams" + }] + }, { + // SignatureValue + name: "Certificate.signatureValue", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + captureBitStringValue: "certSignature" + }] + }; + var rsassaPssParameterValidator = { + name: "rsapss", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "rsapss.hashAlgorithm", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + value: [{ + name: "rsapss.hashAlgorithm.AlgorithmIdentifier", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Class.SEQUENCE, + constructed: true, + optional: true, + value: [{ + name: "rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "hashOid" + /* parameter block omitted, for SHA1 NULL anyhow. */ + }] + }] + }, { + name: "rsapss.maskGenAlgorithm", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 1, + constructed: true, + value: [{ + name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Class.SEQUENCE, + constructed: true, + optional: true, + value: [{ + name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "maskGenOid" + }, { + name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier.params", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "maskGenHashOid" + /* parameter block omitted, for SHA1 NULL anyhow. */ + }] + }] + }] + }, { + name: "rsapss.saltLength", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 2, + optional: true, + value: [{ + name: "rsapss.saltLength.saltLength", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Class.INTEGER, + constructed: false, + capture: "saltLength" + }] + }, { + name: "rsapss.trailerField", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 3, + optional: true, + value: [{ + name: "rsapss.trailer.trailer", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Class.INTEGER, + constructed: false, + capture: "trailer" + }] + }] + }; + var certificationRequestInfoValidator = { + name: "CertificationRequestInfo", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: "certificationRequestInfo", + value: [ + { + name: "CertificationRequestInfo.integer", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "certificationRequestInfoVersion" + }, + { + // Name (subject) (RDNSequence) + name: "CertificationRequestInfo.subject", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: "certificationRequestInfoSubject" + }, + // SubjectPublicKeyInfo + publicKeyValidator, + { + name: "CertificationRequestInfo.attributes", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + optional: true, + capture: "certificationRequestInfoAttributes", + value: [{ + name: "CertificationRequestInfo.attributes", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "CertificationRequestInfo.attributes.type", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false + }, { + name: "CertificationRequestInfo.attributes.value", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + constructed: true + }] + }] + } + ] + }; + var certificationRequestValidator = { + name: "CertificationRequest", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: "csr", + value: [ + certificationRequestInfoValidator, + { + // AlgorithmIdentifier (signature algorithm) + name: "CertificationRequest.signatureAlgorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + // algorithm + name: "CertificationRequest.signatureAlgorithm.algorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "csrSignatureOid" + }, { + name: "CertificationRequest.signatureAlgorithm.parameters", + tagClass: asn1.Class.UNIVERSAL, + optional: true, + captureAsn1: "csrSignatureParams" + }] + }, + { + // signature + name: "CertificationRequest.signature", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + captureBitStringValue: "csrSignature" + } + ] + }; + pki2.RDNAttributesAsArray = function(rdn, md2) { + var rval = []; + var set, attr, obj; + for (var si = 0; si < rdn.value.length; ++si) { + set = rdn.value[si]; + for (var i = 0; i < set.value.length; ++i) { + obj = {}; + attr = set.value[i]; + obj.type = asn1.derToOid(attr.value[0].value); + obj.value = attr.value[1].value; + obj.valueTagClass = attr.value[1].type; + if (obj.type in oids) { + obj.name = oids[obj.type]; + if (obj.name in _shortNames) { + obj.shortName = _shortNames[obj.name]; + } + } + if (md2) { + md2.update(obj.type); + md2.update(obj.value); + } + rval.push(obj); + } + } + return rval; + }; + pki2.CRIAttributesAsArray = function(attributes) { + var rval = []; + for (var si = 0; si < attributes.length; ++si) { + var seq = attributes[si]; + var type = asn1.derToOid(seq.value[0].value); + var values = seq.value[1].value; + for (var vi = 0; vi < values.length; ++vi) { + var obj = {}; + obj.type = type; + obj.value = values[vi].value; + obj.valueTagClass = values[vi].type; + if (obj.type in oids) { + obj.name = oids[obj.type]; + if (obj.name in _shortNames) { + obj.shortName = _shortNames[obj.name]; + } + } + if (obj.type === oids.extensionRequest) { + obj.extensions = []; + for (var ei = 0; ei < obj.value.length; ++ei) { + obj.extensions.push(pki2.certificateExtensionFromAsn1(obj.value[ei])); + } + } + rval.push(obj); + } + } + return rval; + }; + function _getAttribute(obj, options) { + if (typeof options === "string") { + options = { shortName: options }; + } + var rval = null; + var attr; + for (var i = 0; rval === null && i < obj.attributes.length; ++i) { + attr = obj.attributes[i]; + if (options.type && options.type === attr.type) { + rval = attr; + } else if (options.name && options.name === attr.name) { + rval = attr; + } else if (options.shortName && options.shortName === attr.shortName) { + rval = attr; + } + } + return rval; + } + var _readSignatureParameters = function(oid, obj, fillDefaults) { + var params = {}; + if (oid !== oids["RSASSA-PSS"]) { + return params; + } + if (fillDefaults) { + params = { + hash: { + algorithmOid: oids["sha1"] + }, + mgf: { + algorithmOid: oids["mgf1"], + hash: { + algorithmOid: oids["sha1"] + } + }, + saltLength: 20 + }; + } + var capture = {}; + var errors = []; + if (!asn1.validate(obj, rsassaPssParameterValidator, capture, errors)) { + var error2 = new Error("Cannot read RSASSA-PSS parameter block."); + error2.errors = errors; + throw error2; + } + if (capture.hashOid !== void 0) { + params.hash = params.hash || {}; + params.hash.algorithmOid = asn1.derToOid(capture.hashOid); + } + if (capture.maskGenOid !== void 0) { + params.mgf = params.mgf || {}; + params.mgf.algorithmOid = asn1.derToOid(capture.maskGenOid); + params.mgf.hash = params.mgf.hash || {}; + params.mgf.hash.algorithmOid = asn1.derToOid(capture.maskGenHashOid); + } + if (capture.saltLength !== void 0) { + params.saltLength = capture.saltLength.charCodeAt(0); + } + return params; + }; + var _createSignatureDigest = function(options) { + switch (oids[options.signatureOid]) { + case "sha1WithRSAEncryption": + // deprecated alias + case "sha1WithRSASignature": + return forge.md.sha1.create(); + case "md5WithRSAEncryption": + return forge.md.md5.create(); + case "sha256WithRSAEncryption": + return forge.md.sha256.create(); + case "sha384WithRSAEncryption": + return forge.md.sha384.create(); + case "sha512WithRSAEncryption": + return forge.md.sha512.create(); + case "RSASSA-PSS": + return forge.md.sha256.create(); + default: + var error2 = new Error( + "Could not compute " + options.type + " digest. Unknown signature OID." + ); + error2.signatureOid = options.signatureOid; + throw error2; + } + }; + var _verifySignature = function(options) { + var cert = options.certificate; + var scheme; + switch (cert.signatureOid) { + case oids.sha1WithRSAEncryption: + // deprecated alias + case oids.sha1WithRSASignature: + break; + case oids["RSASSA-PSS"]: + var hash, mgf; + hash = oids[cert.signatureParameters.mgf.hash.algorithmOid]; + if (hash === void 0 || forge.md[hash] === void 0) { + var error2 = new Error("Unsupported MGF hash function."); + error2.oid = cert.signatureParameters.mgf.hash.algorithmOid; + error2.name = hash; + throw error2; + } + mgf = oids[cert.signatureParameters.mgf.algorithmOid]; + if (mgf === void 0 || forge.mgf[mgf] === void 0) { + var error2 = new Error("Unsupported MGF function."); + error2.oid = cert.signatureParameters.mgf.algorithmOid; + error2.name = mgf; + throw error2; + } + mgf = forge.mgf[mgf].create(forge.md[hash].create()); + hash = oids[cert.signatureParameters.hash.algorithmOid]; + if (hash === void 0 || forge.md[hash] === void 0) { + var error2 = new Error("Unsupported RSASSA-PSS hash function."); + error2.oid = cert.signatureParameters.hash.algorithmOid; + error2.name = hash; + throw error2; + } + scheme = forge.pss.create( + forge.md[hash].create(), + mgf, + cert.signatureParameters.saltLength + ); + break; + } + return cert.publicKey.verify( + options.md.digest().getBytes(), + options.signature, + scheme + ); + }; + pki2.certificateFromPem = function(pem, computeHash, strict) { + var msg = forge.pem.decode(pem)[0]; + if (msg.type !== "CERTIFICATE" && msg.type !== "X509 CERTIFICATE" && msg.type !== "TRUSTED CERTIFICATE") { + var error2 = new Error( + 'Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".' + ); + error2.headerType = msg.type; + throw error2; + } + if (msg.procType && msg.procType.type === "ENCRYPTED") { + throw new Error( + "Could not convert certificate from PEM; PEM is encrypted." + ); + } + var obj = asn1.fromDer(msg.body, strict); + return pki2.certificateFromAsn1(obj, computeHash); + }; + pki2.certificateToPem = function(cert, maxline) { + var msg = { + type: "CERTIFICATE", + body: asn1.toDer(pki2.certificateToAsn1(cert)).getBytes() + }; + return forge.pem.encode(msg, { maxline }); + }; + pki2.publicKeyFromPem = function(pem) { + var msg = forge.pem.decode(pem)[0]; + if (msg.type !== "PUBLIC KEY" && msg.type !== "RSA PUBLIC KEY") { + var error2 = new Error('Could not convert public key from PEM; PEM header type is not "PUBLIC KEY" or "RSA PUBLIC KEY".'); + error2.headerType = msg.type; + throw error2; + } + if (msg.procType && msg.procType.type === "ENCRYPTED") { + throw new Error("Could not convert public key from PEM; PEM is encrypted."); + } + var obj = asn1.fromDer(msg.body); + return pki2.publicKeyFromAsn1(obj); + }; + pki2.publicKeyToPem = function(key, maxline) { + var msg = { + type: "PUBLIC KEY", + body: asn1.toDer(pki2.publicKeyToAsn1(key)).getBytes() + }; + return forge.pem.encode(msg, { maxline }); + }; + pki2.publicKeyToRSAPublicKeyPem = function(key, maxline) { + var msg = { + type: "RSA PUBLIC KEY", + body: asn1.toDer(pki2.publicKeyToRSAPublicKey(key)).getBytes() + }; + return forge.pem.encode(msg, { maxline }); + }; + pki2.getPublicKeyFingerprint = function(key, options) { + options = options || {}; + var md2 = options.md || forge.md.sha1.create(); + var type = options.type || "RSAPublicKey"; + var bytes; + switch (type) { + case "RSAPublicKey": + bytes = asn1.toDer(pki2.publicKeyToRSAPublicKey(key)).getBytes(); + break; + case "SubjectPublicKeyInfo": + bytes = asn1.toDer(pki2.publicKeyToAsn1(key)).getBytes(); + break; + default: + throw new Error('Unknown fingerprint type "' + options.type + '".'); + } + md2.start(); + md2.update(bytes); + var digest = md2.digest(); + if (options.encoding === "hex") { + var hex = digest.toHex(); + if (options.delimiter) { + return hex.match(/.{2}/g).join(options.delimiter); + } + return hex; + } else if (options.encoding === "binary") { + return digest.getBytes(); + } else if (options.encoding) { + throw new Error('Unknown encoding "' + options.encoding + '".'); + } + return digest; + }; + pki2.certificationRequestFromPem = function(pem, computeHash, strict) { + var msg = forge.pem.decode(pem)[0]; + if (msg.type !== "CERTIFICATE REQUEST") { + var error2 = new Error('Could not convert certification request from PEM; PEM header type is not "CERTIFICATE REQUEST".'); + error2.headerType = msg.type; + throw error2; + } + if (msg.procType && msg.procType.type === "ENCRYPTED") { + throw new Error("Could not convert certification request from PEM; PEM is encrypted."); + } + var obj = asn1.fromDer(msg.body, strict); + return pki2.certificationRequestFromAsn1(obj, computeHash); + }; + pki2.certificationRequestToPem = function(csr, maxline) { + var msg = { + type: "CERTIFICATE REQUEST", + body: asn1.toDer(pki2.certificationRequestToAsn1(csr)).getBytes() + }; + return forge.pem.encode(msg, { maxline }); + }; + pki2.createCertificate = function() { + var cert = {}; + cert.version = 2; + cert.serialNumber = "00"; + cert.signatureOid = null; + cert.signature = null; + cert.siginfo = {}; + cert.siginfo.algorithmOid = null; + cert.validity = {}; + cert.validity.notBefore = /* @__PURE__ */ new Date(); + cert.validity.notAfter = /* @__PURE__ */ new Date(); + cert.issuer = {}; + cert.issuer.getField = function(sn) { + return _getAttribute(cert.issuer, sn); + }; + cert.issuer.addField = function(attr) { + _fillMissingFields([attr]); + cert.issuer.attributes.push(attr); + }; + cert.issuer.attributes = []; + cert.issuer.hash = null; + cert.subject = {}; + cert.subject.getField = function(sn) { + return _getAttribute(cert.subject, sn); + }; + cert.subject.addField = function(attr) { + _fillMissingFields([attr]); + cert.subject.attributes.push(attr); + }; + cert.subject.attributes = []; + cert.subject.hash = null; + cert.extensions = []; + cert.publicKey = null; + cert.md = null; + cert.setSubject = function(attrs, uniqueId) { + _fillMissingFields(attrs); + cert.subject.attributes = attrs; + delete cert.subject.uniqueId; + if (uniqueId) { + cert.subject.uniqueId = uniqueId; + } + cert.subject.hash = null; + }; + cert.setIssuer = function(attrs, uniqueId) { + _fillMissingFields(attrs); + cert.issuer.attributes = attrs; + delete cert.issuer.uniqueId; + if (uniqueId) { + cert.issuer.uniqueId = uniqueId; + } + cert.issuer.hash = null; + }; + cert.setExtensions = function(exts) { + for (var i = 0; i < exts.length; ++i) { + _fillMissingExtensionFields(exts[i], { cert }); + } + cert.extensions = exts; + }; + cert.getExtension = function(options) { + if (typeof options === "string") { + options = { name: options }; + } + var rval = null; + var ext; + for (var i = 0; rval === null && i < cert.extensions.length; ++i) { + ext = cert.extensions[i]; + if (options.id && ext.id === options.id) { + rval = ext; + } else if (options.name && ext.name === options.name) { + rval = ext; + } + } + return rval; + }; + cert.sign = function(key, md2) { + cert.md = md2 || forge.md.sha1.create(); + var algorithmOid = oids[cert.md.algorithm + "WithRSAEncryption"]; + if (!algorithmOid) { + var error2 = new Error("Could not compute certificate digest. Unknown message digest algorithm OID."); + error2.algorithm = cert.md.algorithm; + throw error2; + } + cert.signatureOid = cert.siginfo.algorithmOid = algorithmOid; + cert.tbsCertificate = pki2.getTBSCertificate(cert); + var bytes = asn1.toDer(cert.tbsCertificate); + cert.md.update(bytes.getBytes()); + cert.signature = key.sign(cert.md); + }; + cert.verify = function(child) { + var rval = false; + if (!cert.issued(child)) { + var issuer = child.issuer; + var subject = cert.subject; + var error2 = new Error( + "The parent certificate did not issue the given child certificate; the child certificate's issuer does not match the parent's subject." + ); + error2.expectedIssuer = subject.attributes; + error2.actualIssuer = issuer.attributes; + throw error2; + } + var md2 = child.md; + if (md2 === null) { + md2 = _createSignatureDigest({ + signatureOid: child.signatureOid, + type: "certificate" + }); + var tbsCertificate = child.tbsCertificate || pki2.getTBSCertificate(child); + var bytes = asn1.toDer(tbsCertificate); + md2.update(bytes.getBytes()); + } + if (md2 !== null) { + rval = _verifySignature({ + certificate: cert, + md: md2, + signature: child.signature + }); + } + return rval; + }; + cert.isIssuer = function(parent) { + var rval = false; + var i = cert.issuer; + var s = parent.subject; + if (i.hash && s.hash) { + rval = i.hash === s.hash; + } else if (i.attributes.length === s.attributes.length) { + rval = true; + var iattr, sattr; + for (var n = 0; rval && n < i.attributes.length; ++n) { + iattr = i.attributes[n]; + sattr = s.attributes[n]; + if (iattr.type !== sattr.type || iattr.value !== sattr.value) { + rval = false; + } + } + } + return rval; + }; + cert.issued = function(child) { + return child.isIssuer(cert); + }; + cert.generateSubjectKeyIdentifier = function() { + return pki2.getPublicKeyFingerprint(cert.publicKey, { type: "RSAPublicKey" }); + }; + cert.verifySubjectKeyIdentifier = function() { + var oid = oids["subjectKeyIdentifier"]; + for (var i = 0; i < cert.extensions.length; ++i) { + var ext = cert.extensions[i]; + if (ext.id === oid) { + var ski = cert.generateSubjectKeyIdentifier().getBytes(); + return forge.util.hexToBytes(ext.subjectKeyIdentifier) === ski; + } + } + return false; + }; + return cert; + }; + pki2.certificateFromAsn1 = function(obj, computeHash) { + var capture = {}; + var errors = []; + if (!asn1.validate(obj, x509CertificateValidator, capture, errors)) { + var error2 = new Error("Cannot read X.509 certificate. ASN.1 object is not an X509v3 Certificate."); + error2.errors = errors; + throw error2; + } + var oid = asn1.derToOid(capture.publicKeyOid); + if (oid !== pki2.oids.rsaEncryption) { + throw new Error("Cannot read public key. OID is not RSA."); + } + var cert = pki2.createCertificate(); + cert.version = capture.certVersion ? capture.certVersion.charCodeAt(0) : 0; + var serial = forge.util.createBuffer(capture.certSerialNumber); + cert.serialNumber = serial.toHex(); + cert.signatureOid = forge.asn1.derToOid(capture.certSignatureOid); + cert.signatureParameters = _readSignatureParameters( + cert.signatureOid, + capture.certSignatureParams, + true + ); + cert.siginfo.algorithmOid = forge.asn1.derToOid(capture.certinfoSignatureOid); + cert.siginfo.parameters = _readSignatureParameters( + cert.siginfo.algorithmOid, + capture.certinfoSignatureParams, + false + ); + cert.signature = capture.certSignature; + var validity = []; + if (capture.certValidity1UTCTime !== void 0) { + validity.push(asn1.utcTimeToDate(capture.certValidity1UTCTime)); + } + if (capture.certValidity2GeneralizedTime !== void 0) { + validity.push(asn1.generalizedTimeToDate( + capture.certValidity2GeneralizedTime + )); + } + if (capture.certValidity3UTCTime !== void 0) { + validity.push(asn1.utcTimeToDate(capture.certValidity3UTCTime)); + } + if (capture.certValidity4GeneralizedTime !== void 0) { + validity.push(asn1.generalizedTimeToDate( + capture.certValidity4GeneralizedTime + )); + } + if (validity.length > 2) { + throw new Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate."); + } + if (validity.length < 2) { + throw new Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime."); + } + cert.validity.notBefore = validity[0]; + cert.validity.notAfter = validity[1]; + cert.tbsCertificate = capture.tbsCertificate; + if (computeHash) { + cert.md = _createSignatureDigest({ + signatureOid: cert.signatureOid, + type: "certificate" + }); + var bytes = asn1.toDer(cert.tbsCertificate); + cert.md.update(bytes.getBytes()); + } + var imd = forge.md.sha1.create(); + var ibytes = asn1.toDer(capture.certIssuer); + imd.update(ibytes.getBytes()); + cert.issuer.getField = function(sn) { + return _getAttribute(cert.issuer, sn); + }; + cert.issuer.addField = function(attr) { + _fillMissingFields([attr]); + cert.issuer.attributes.push(attr); + }; + cert.issuer.attributes = pki2.RDNAttributesAsArray(capture.certIssuer); + if (capture.certIssuerUniqueId) { + cert.issuer.uniqueId = capture.certIssuerUniqueId; + } + cert.issuer.hash = imd.digest().toHex(); + var smd = forge.md.sha1.create(); + var sbytes = asn1.toDer(capture.certSubject); + smd.update(sbytes.getBytes()); + cert.subject.getField = function(sn) { + return _getAttribute(cert.subject, sn); + }; + cert.subject.addField = function(attr) { + _fillMissingFields([attr]); + cert.subject.attributes.push(attr); + }; + cert.subject.attributes = pki2.RDNAttributesAsArray(capture.certSubject); + if (capture.certSubjectUniqueId) { + cert.subject.uniqueId = capture.certSubjectUniqueId; + } + cert.subject.hash = smd.digest().toHex(); + if (capture.certExtensions) { + cert.extensions = pki2.certificateExtensionsFromAsn1(capture.certExtensions); + } else { + cert.extensions = []; + } + cert.publicKey = pki2.publicKeyFromAsn1(capture.subjectPublicKeyInfo); + return cert; + }; + pki2.certificateExtensionsFromAsn1 = function(exts) { + var rval = []; + for (var i = 0; i < exts.value.length; ++i) { + var extseq = exts.value[i]; + for (var ei = 0; ei < extseq.value.length; ++ei) { + rval.push(pki2.certificateExtensionFromAsn1(extseq.value[ei])); + } + } + return rval; + }; + pki2.certificateExtensionFromAsn1 = function(ext) { + var e = {}; + e.id = asn1.derToOid(ext.value[0].value); + e.critical = false; + if (ext.value[1].type === asn1.Type.BOOLEAN) { + e.critical = ext.value[1].value.charCodeAt(0) !== 0; + e.value = ext.value[2].value; + } else { + e.value = ext.value[1].value; + } + if (e.id in oids) { + e.name = oids[e.id]; + if (e.name === "keyUsage") { + var ev = asn1.fromDer(e.value); + var b2 = 0; + var b3 = 0; + if (ev.value.length > 1) { + b2 = ev.value.charCodeAt(1); + b3 = ev.value.length > 2 ? ev.value.charCodeAt(2) : 0; + } + e.digitalSignature = (b2 & 128) === 128; + e.nonRepudiation = (b2 & 64) === 64; + e.keyEncipherment = (b2 & 32) === 32; + e.dataEncipherment = (b2 & 16) === 16; + e.keyAgreement = (b2 & 8) === 8; + e.keyCertSign = (b2 & 4) === 4; + e.cRLSign = (b2 & 2) === 2; + e.encipherOnly = (b2 & 1) === 1; + e.decipherOnly = (b3 & 128) === 128; + } else if (e.name === "basicConstraints") { + var ev = asn1.fromDer(e.value); + if (ev.value.length > 0 && ev.value[0].type === asn1.Type.BOOLEAN) { + e.cA = ev.value[0].value.charCodeAt(0) !== 0; + } else { + e.cA = false; + } + var value = null; + if (ev.value.length > 0 && ev.value[0].type === asn1.Type.INTEGER) { + value = ev.value[0].value; + } else if (ev.value.length > 1) { + value = ev.value[1].value; + } + if (value !== null) { + e.pathLenConstraint = asn1.derToInteger(value); + } + } else if (e.name === "extKeyUsage") { + var ev = asn1.fromDer(e.value); + for (var vi = 0; vi < ev.value.length; ++vi) { + var oid = asn1.derToOid(ev.value[vi].value); + if (oid in oids) { + e[oids[oid]] = true; + } else { + e[oid] = true; + } + } + } else if (e.name === "nsCertType") { + var ev = asn1.fromDer(e.value); + var b2 = 0; + if (ev.value.length > 1) { + b2 = ev.value.charCodeAt(1); + } + e.client = (b2 & 128) === 128; + e.server = (b2 & 64) === 64; + e.email = (b2 & 32) === 32; + e.objsign = (b2 & 16) === 16; + e.reserved = (b2 & 8) === 8; + e.sslCA = (b2 & 4) === 4; + e.emailCA = (b2 & 2) === 2; + e.objCA = (b2 & 1) === 1; + } else if (e.name === "subjectAltName" || e.name === "issuerAltName") { + e.altNames = []; + var gn; + var ev = asn1.fromDer(e.value); + for (var n = 0; n < ev.value.length; ++n) { + gn = ev.value[n]; + var altName = { + type: gn.type, + value: gn.value + }; + e.altNames.push(altName); + switch (gn.type) { + // rfc822Name + case 1: + // dNSName + case 2: + // uniformResourceIdentifier (URI) + case 6: + break; + // IPAddress + case 7: + altName.ip = forge.util.bytesToIP(gn.value); + break; + // registeredID + case 8: + altName.oid = asn1.derToOid(gn.value); + break; + default: + } + } + } else if (e.name === "subjectKeyIdentifier") { + var ev = asn1.fromDer(e.value); + e.subjectKeyIdentifier = forge.util.bytesToHex(ev.value); + } + } + return e; + }; + pki2.certificationRequestFromAsn1 = function(obj, computeHash) { + var capture = {}; + var errors = []; + if (!asn1.validate(obj, certificationRequestValidator, capture, errors)) { + var error2 = new Error("Cannot read PKCS#10 certificate request. ASN.1 object is not a PKCS#10 CertificationRequest."); + error2.errors = errors; + throw error2; + } + var oid = asn1.derToOid(capture.publicKeyOid); + if (oid !== pki2.oids.rsaEncryption) { + throw new Error("Cannot read public key. OID is not RSA."); + } + var csr = pki2.createCertificationRequest(); + csr.version = capture.csrVersion ? capture.csrVersion.charCodeAt(0) : 0; + csr.signatureOid = forge.asn1.derToOid(capture.csrSignatureOid); + csr.signatureParameters = _readSignatureParameters( + csr.signatureOid, + capture.csrSignatureParams, + true + ); + csr.siginfo.algorithmOid = forge.asn1.derToOid(capture.csrSignatureOid); + csr.siginfo.parameters = _readSignatureParameters( + csr.siginfo.algorithmOid, + capture.csrSignatureParams, + false + ); + csr.signature = capture.csrSignature; + csr.certificationRequestInfo = capture.certificationRequestInfo; + if (computeHash) { + csr.md = _createSignatureDigest({ + signatureOid: csr.signatureOid, + type: "certification request" + }); + var bytes = asn1.toDer(csr.certificationRequestInfo); + csr.md.update(bytes.getBytes()); + } + var smd = forge.md.sha1.create(); + csr.subject.getField = function(sn) { + return _getAttribute(csr.subject, sn); + }; + csr.subject.addField = function(attr) { + _fillMissingFields([attr]); + csr.subject.attributes.push(attr); + }; + csr.subject.attributes = pki2.RDNAttributesAsArray( + capture.certificationRequestInfoSubject, + smd + ); + csr.subject.hash = smd.digest().toHex(); + csr.publicKey = pki2.publicKeyFromAsn1(capture.subjectPublicKeyInfo); + csr.getAttribute = function(sn) { + return _getAttribute(csr, sn); + }; + csr.addAttribute = function(attr) { + _fillMissingFields([attr]); + csr.attributes.push(attr); + }; + csr.attributes = pki2.CRIAttributesAsArray( + capture.certificationRequestInfoAttributes || [] + ); + return csr; + }; + pki2.createCertificationRequest = function() { + var csr = {}; + csr.version = 0; + csr.signatureOid = null; + csr.signature = null; + csr.siginfo = {}; + csr.siginfo.algorithmOid = null; + csr.subject = {}; + csr.subject.getField = function(sn) { + return _getAttribute(csr.subject, sn); + }; + csr.subject.addField = function(attr) { + _fillMissingFields([attr]); + csr.subject.attributes.push(attr); + }; + csr.subject.attributes = []; + csr.subject.hash = null; + csr.publicKey = null; + csr.attributes = []; + csr.getAttribute = function(sn) { + return _getAttribute(csr, sn); + }; + csr.addAttribute = function(attr) { + _fillMissingFields([attr]); + csr.attributes.push(attr); + }; + csr.md = null; + csr.setSubject = function(attrs) { + _fillMissingFields(attrs); + csr.subject.attributes = attrs; + csr.subject.hash = null; + }; + csr.setAttributes = function(attrs) { + _fillMissingFields(attrs); + csr.attributes = attrs; + }; + csr.sign = function(key, md2) { + csr.md = md2 || forge.md.sha1.create(); + var algorithmOid = oids[csr.md.algorithm + "WithRSAEncryption"]; + if (!algorithmOid) { + var error2 = new Error("Could not compute certification request digest. Unknown message digest algorithm OID."); + error2.algorithm = csr.md.algorithm; + throw error2; + } + csr.signatureOid = csr.siginfo.algorithmOid = algorithmOid; + csr.certificationRequestInfo = pki2.getCertificationRequestInfo(csr); + var bytes = asn1.toDer(csr.certificationRequestInfo); + csr.md.update(bytes.getBytes()); + csr.signature = key.sign(csr.md); + }; + csr.verify = function() { + var rval = false; + var md2 = csr.md; + if (md2 === null) { + md2 = _createSignatureDigest({ + signatureOid: csr.signatureOid, + type: "certification request" + }); + var cri = csr.certificationRequestInfo || pki2.getCertificationRequestInfo(csr); + var bytes = asn1.toDer(cri); + md2.update(bytes.getBytes()); + } + if (md2 !== null) { + rval = _verifySignature({ + certificate: csr, + md: md2, + signature: csr.signature + }); + } + return rval; + }; + return csr; + }; + function _dnToAsn1(obj) { + var rval = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SEQUENCE, + true, + [] + ); + var attr, set; + var attrs = obj.attributes; + for (var i = 0; i < attrs.length; ++i) { + attr = attrs[i]; + var value = attr.value; + var valueTagClass = asn1.Type.PRINTABLESTRING; + if ("valueTagClass" in attr) { + valueTagClass = attr.valueTagClass; + if (valueTagClass === asn1.Type.UTF8) { + value = forge.util.encodeUtf8(value); + } + } + set = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // AttributeType + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(attr.type).getBytes() + ), + // AttributeValue + asn1.create(asn1.Class.UNIVERSAL, valueTagClass, false, value) + ]) + ]); + rval.value.push(set); + } + return rval; + } + function _fillMissingFields(attrs) { + var attr; + for (var i = 0; i < attrs.length; ++i) { + attr = attrs[i]; + if (typeof attr.name === "undefined") { + if (attr.type && attr.type in pki2.oids) { + attr.name = pki2.oids[attr.type]; + } else if (attr.shortName && attr.shortName in _shortNames) { + attr.name = pki2.oids[_shortNames[attr.shortName]]; + } + } + if (typeof attr.type === "undefined") { + if (attr.name && attr.name in pki2.oids) { + attr.type = pki2.oids[attr.name]; + } else { + var error2 = new Error("Attribute type not specified."); + error2.attribute = attr; + throw error2; + } + } + if (typeof attr.shortName === "undefined") { + if (attr.name && attr.name in _shortNames) { + attr.shortName = _shortNames[attr.name]; + } + } + if (attr.type === oids.extensionRequest) { + attr.valueConstructed = true; + attr.valueTagClass = asn1.Type.SEQUENCE; + if (!attr.value && attr.extensions) { + attr.value = []; + for (var ei = 0; ei < attr.extensions.length; ++ei) { + attr.value.push(pki2.certificateExtensionToAsn1( + _fillMissingExtensionFields(attr.extensions[ei]) + )); + } + } + } + if (typeof attr.value === "undefined") { + var error2 = new Error("Attribute value not specified."); + error2.attribute = attr; + throw error2; + } + } + } + function _fillMissingExtensionFields(e, options) { + options = options || {}; + if (typeof e.name === "undefined") { + if (e.id && e.id in pki2.oids) { + e.name = pki2.oids[e.id]; + } + } + if (typeof e.id === "undefined") { + if (e.name && e.name in pki2.oids) { + e.id = pki2.oids[e.name]; + } else { + var error2 = new Error("Extension ID not specified."); + error2.extension = e; + throw error2; + } + } + if (typeof e.value !== "undefined") { + return e; + } + if (e.name === "keyUsage") { + var unused = 0; + var b2 = 0; + var b3 = 0; + if (e.digitalSignature) { + b2 |= 128; + unused = 7; + } + if (e.nonRepudiation) { + b2 |= 64; + unused = 6; + } + if (e.keyEncipherment) { + b2 |= 32; + unused = 5; + } + if (e.dataEncipherment) { + b2 |= 16; + unused = 4; + } + if (e.keyAgreement) { + b2 |= 8; + unused = 3; + } + if (e.keyCertSign) { + b2 |= 4; + unused = 2; + } + if (e.cRLSign) { + b2 |= 2; + unused = 1; + } + if (e.encipherOnly) { + b2 |= 1; + unused = 0; + } + if (e.decipherOnly) { + b3 |= 128; + unused = 7; + } + var value = String.fromCharCode(unused); + if (b3 !== 0) { + value += String.fromCharCode(b2) + String.fromCharCode(b3); + } else if (b2 !== 0) { + value += String.fromCharCode(b2); + } + e.value = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.BITSTRING, + false, + value + ); + } else if (e.name === "basicConstraints") { + e.value = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SEQUENCE, + true, + [] + ); + if (e.cA) { + e.value.value.push(asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.BOOLEAN, + false, + String.fromCharCode(255) + )); + } + if ("pathLenConstraint" in e) { + e.value.value.push(asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + asn1.integerToDer(e.pathLenConstraint).getBytes() + )); + } + } else if (e.name === "extKeyUsage") { + e.value = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SEQUENCE, + true, + [] + ); + var seq = e.value.value; + for (var key in e) { + if (e[key] !== true) { + continue; + } + if (key in oids) { + seq.push(asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(oids[key]).getBytes() + )); + } else if (key.indexOf(".") !== -1) { + seq.push(asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(key).getBytes() + )); + } + } + } else if (e.name === "nsCertType") { + var unused = 0; + var b2 = 0; + if (e.client) { + b2 |= 128; + unused = 7; + } + if (e.server) { + b2 |= 64; + unused = 6; + } + if (e.email) { + b2 |= 32; + unused = 5; + } + if (e.objsign) { + b2 |= 16; + unused = 4; + } + if (e.reserved) { + b2 |= 8; + unused = 3; + } + if (e.sslCA) { + b2 |= 4; + unused = 2; + } + if (e.emailCA) { + b2 |= 2; + unused = 1; + } + if (e.objCA) { + b2 |= 1; + unused = 0; + } + var value = String.fromCharCode(unused); + if (b2 !== 0) { + value += String.fromCharCode(b2); + } + e.value = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.BITSTRING, + false, + value + ); + } else if (e.name === "subjectAltName" || e.name === "issuerAltName") { + e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + var altName; + for (var n = 0; n < e.altNames.length; ++n) { + altName = e.altNames[n]; + var value = altName.value; + if (altName.type === 7 && altName.ip) { + value = forge.util.bytesFromIP(altName.ip); + if (value === null) { + var error2 = new Error( + 'Extension "ip" value is not a valid IPv4 or IPv6 address.' + ); + error2.extension = e; + throw error2; + } + } else if (altName.type === 8) { + if (altName.oid) { + value = asn1.oidToDer(asn1.oidToDer(altName.oid)); + } else { + value = asn1.oidToDer(value); + } + } + e.value.value.push(asn1.create( + asn1.Class.CONTEXT_SPECIFIC, + altName.type, + false, + value + )); + } + } else if (e.name === "nsComment" && options.cert) { + if (!/^[\x00-\x7F]*$/.test(e.comment) || e.comment.length < 1 || e.comment.length > 128) { + throw new Error('Invalid "nsComment" content.'); + } + e.value = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.IA5STRING, + false, + e.comment + ); + } else if (e.name === "subjectKeyIdentifier" && options.cert) { + var ski = options.cert.generateSubjectKeyIdentifier(); + e.subjectKeyIdentifier = ski.toHex(); + e.value = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + ski.getBytes() + ); + } else if (e.name === "authorityKeyIdentifier" && options.cert) { + e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + var seq = e.value.value; + if (e.keyIdentifier) { + var keyIdentifier = e.keyIdentifier === true ? options.cert.generateSubjectKeyIdentifier().getBytes() : e.keyIdentifier; + seq.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, false, keyIdentifier) + ); + } + if (e.authorityCertIssuer) { + var authorityCertIssuer = [ + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 4, true, [ + _dnToAsn1(e.authorityCertIssuer === true ? options.cert.issuer : e.authorityCertIssuer) + ]) + ]; + seq.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, authorityCertIssuer) + ); + } + if (e.serialNumber) { + var serialNumber = forge.util.hexToBytes(e.serialNumber === true ? options.cert.serialNumber : e.serialNumber); + seq.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, false, serialNumber) + ); + } + } else if (e.name === "cRLDistributionPoints") { + e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + var seq = e.value.value; + var subSeq = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SEQUENCE, + true, + [] + ); + var fullNameGeneralNames = asn1.create( + asn1.Class.CONTEXT_SPECIFIC, + 0, + true, + [] + ); + var altName; + for (var n = 0; n < e.altNames.length; ++n) { + altName = e.altNames[n]; + var value = altName.value; + if (altName.type === 7 && altName.ip) { + value = forge.util.bytesFromIP(altName.ip); + if (value === null) { + var error2 = new Error( + 'Extension "ip" value is not a valid IPv4 or IPv6 address.' + ); + error2.extension = e; + throw error2; + } + } else if (altName.type === 8) { + if (altName.oid) { + value = asn1.oidToDer(asn1.oidToDer(altName.oid)); + } else { + value = asn1.oidToDer(value); + } + } + fullNameGeneralNames.value.push(asn1.create( + asn1.Class.CONTEXT_SPECIFIC, + altName.type, + false, + value + )); + } + subSeq.value.push(asn1.create( + asn1.Class.CONTEXT_SPECIFIC, + 0, + true, + [fullNameGeneralNames] + )); + seq.push(subSeq); + } + if (typeof e.value === "undefined") { + var error2 = new Error("Extension value not specified."); + error2.extension = e; + throw error2; + } + return e; + } + function _signatureParametersToAsn1(oid, params) { + switch (oid) { + case oids["RSASSA-PSS"]: + var parts = []; + if (params.hash.algorithmOid !== void 0) { + parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(params.hash.algorithmOid).getBytes() + ), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") + ]) + ])); + } + if (params.mgf.algorithmOid !== void 0) { + parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(params.mgf.algorithmOid).getBytes() + ), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(params.mgf.hash.algorithmOid).getBytes() + ), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") + ]) + ]) + ])); + } + if (params.saltLength !== void 0) { + parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + asn1.integerToDer(params.saltLength).getBytes() + ) + ])); + } + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, parts); + default: + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, ""); + } + } + function _CRIAttributesToAsn1(csr) { + var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []); + if (csr.attributes.length === 0) { + return rval; + } + var attrs = csr.attributes; + for (var i = 0; i < attrs.length; ++i) { + var attr = attrs[i]; + var value = attr.value; + var valueTagClass = asn1.Type.UTF8; + if ("valueTagClass" in attr) { + valueTagClass = attr.valueTagClass; + } + if (valueTagClass === asn1.Type.UTF8) { + value = forge.util.encodeUtf8(value); + } + var valueConstructed = false; + if ("valueConstructed" in attr) { + valueConstructed = attr.valueConstructed; + } + var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // AttributeType + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(attr.type).getBytes() + ), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ + // AttributeValue + asn1.create( + asn1.Class.UNIVERSAL, + valueTagClass, + valueConstructed, + value + ) + ]) + ]); + rval.value.push(seq); + } + return rval; + } + var jan_1_1950 = /* @__PURE__ */ new Date("1950-01-01T00:00:00Z"); + var jan_1_2050 = /* @__PURE__ */ new Date("2050-01-01T00:00:00Z"); + function _dateToAsn1(date) { + if (date >= jan_1_1950 && date < jan_1_2050) { + return asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.UTCTIME, + false, + asn1.dateToUtcTime(date) + ); + } else { + return asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.GENERALIZEDTIME, + false, + asn1.dateToGeneralizedTime(date) + ); + } + } + pki2.getTBSCertificate = function(cert) { + var notBefore = _dateToAsn1(cert.validity.notBefore); + var notAfter = _dateToAsn1(cert.validity.notAfter); + var tbs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // version + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + // integer + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + asn1.integerToDer(cert.version).getBytes() + ) + ]), + // serialNumber + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + forge.util.hexToBytes(cert.serialNumber) + ), + // signature + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(cert.siginfo.algorithmOid).getBytes() + ), + // parameters + _signatureParametersToAsn1( + cert.siginfo.algorithmOid, + cert.siginfo.parameters + ) + ]), + // issuer + _dnToAsn1(cert.issuer), + // validity + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + notBefore, + notAfter + ]), + // subject + _dnToAsn1(cert.subject), + // SubjectPublicKeyInfo + pki2.publicKeyToAsn1(cert.publicKey) + ]); + if (cert.issuer.uniqueId) { + tbs.value.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.BITSTRING, + false, + // TODO: support arbitrary bit length ids + String.fromCharCode(0) + cert.issuer.uniqueId + ) + ]) + ); + } + if (cert.subject.uniqueId) { + tbs.value.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.BITSTRING, + false, + // TODO: support arbitrary bit length ids + String.fromCharCode(0) + cert.subject.uniqueId + ) + ]) + ); + } + if (cert.extensions.length > 0) { + tbs.value.push(pki2.certificateExtensionsToAsn1(cert.extensions)); + } + return tbs; + }; + pki2.getCertificationRequestInfo = function(csr) { + var cri = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // version + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + asn1.integerToDer(csr.version).getBytes() + ), + // subject + _dnToAsn1(csr.subject), + // SubjectPublicKeyInfo + pki2.publicKeyToAsn1(csr.publicKey), + // attributes + _CRIAttributesToAsn1(csr) + ]); + return cri; + }; + pki2.distinguishedNameToAsn1 = function(dn) { + return _dnToAsn1(dn); + }; + pki2.certificateToAsn1 = function(cert) { + var tbsCertificate = cert.tbsCertificate || pki2.getTBSCertificate(cert); + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // TBSCertificate + tbsCertificate, + // AlgorithmIdentifier (signature algorithm) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(cert.signatureOid).getBytes() + ), + // parameters + _signatureParametersToAsn1(cert.signatureOid, cert.signatureParameters) + ]), + // SignatureValue + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.BITSTRING, + false, + String.fromCharCode(0) + cert.signature + ) + ]); + }; + pki2.certificateExtensionsToAsn1 = function(exts) { + var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 3, true, []); + var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + rval.value.push(seq); + for (var i = 0; i < exts.length; ++i) { + seq.value.push(pki2.certificateExtensionToAsn1(exts[i])); + } + return rval; + }; + pki2.certificateExtensionToAsn1 = function(ext) { + var extseq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + extseq.value.push(asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(ext.id).getBytes() + )); + if (ext.critical) { + extseq.value.push(asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.BOOLEAN, + false, + String.fromCharCode(255) + )); + } + var value = ext.value; + if (typeof ext.value !== "string") { + value = asn1.toDer(value).getBytes(); + } + extseq.value.push(asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + value + )); + return extseq; + }; + pki2.certificationRequestToAsn1 = function(csr) { + var cri = csr.certificationRequestInfo || pki2.getCertificationRequestInfo(csr); + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // CertificationRequestInfo + cri, + // AlgorithmIdentifier (signature algorithm) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(csr.signatureOid).getBytes() + ), + // parameters + _signatureParametersToAsn1(csr.signatureOid, csr.signatureParameters) + ]), + // signature + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.BITSTRING, + false, + String.fromCharCode(0) + csr.signature + ) + ]); + }; + pki2.createCaStore = function(certs) { + var caStore = { + // stored certificates + certs: {} + }; + caStore.getIssuer = function(cert2) { + var rval = getBySubject(cert2.issuer); + return rval; + }; + caStore.addCertificate = function(cert2) { + if (typeof cert2 === "string") { + cert2 = forge.pki.certificateFromPem(cert2); + } + ensureSubjectHasHash(cert2.subject); + if (!caStore.hasCertificate(cert2)) { + if (cert2.subject.hash in caStore.certs) { + var tmp = caStore.certs[cert2.subject.hash]; + if (!forge.util.isArray(tmp)) { + tmp = [tmp]; + } + tmp.push(cert2); + caStore.certs[cert2.subject.hash] = tmp; + } else { + caStore.certs[cert2.subject.hash] = cert2; + } + } + }; + caStore.hasCertificate = function(cert2) { + if (typeof cert2 === "string") { + cert2 = forge.pki.certificateFromPem(cert2); + } + var match = getBySubject(cert2.subject); + if (!match) { + return false; + } + if (!forge.util.isArray(match)) { + match = [match]; + } + var der1 = asn1.toDer(pki2.certificateToAsn1(cert2)).getBytes(); + for (var i2 = 0; i2 < match.length; ++i2) { + var der2 = asn1.toDer(pki2.certificateToAsn1(match[i2])).getBytes(); + if (der1 === der2) { + return true; + } + } + return false; + }; + caStore.listAllCertificates = function() { + var certList = []; + for (var hash in caStore.certs) { + if (caStore.certs.hasOwnProperty(hash)) { + var value = caStore.certs[hash]; + if (!forge.util.isArray(value)) { + certList.push(value); + } else { + for (var i2 = 0; i2 < value.length; ++i2) { + certList.push(value[i2]); + } + } + } + } + return certList; + }; + caStore.removeCertificate = function(cert2) { + var result; + if (typeof cert2 === "string") { + cert2 = forge.pki.certificateFromPem(cert2); + } + ensureSubjectHasHash(cert2.subject); + if (!caStore.hasCertificate(cert2)) { + return null; + } + var match = getBySubject(cert2.subject); + if (!forge.util.isArray(match)) { + result = caStore.certs[cert2.subject.hash]; + delete caStore.certs[cert2.subject.hash]; + return result; + } + var der1 = asn1.toDer(pki2.certificateToAsn1(cert2)).getBytes(); + for (var i2 = 0; i2 < match.length; ++i2) { + var der2 = asn1.toDer(pki2.certificateToAsn1(match[i2])).getBytes(); + if (der1 === der2) { + result = match[i2]; + match.splice(i2, 1); + } + } + if (match.length === 0) { + delete caStore.certs[cert2.subject.hash]; + } + return result; + }; + function getBySubject(subject) { + ensureSubjectHasHash(subject); + return caStore.certs[subject.hash] || null; + } + function ensureSubjectHasHash(subject) { + if (!subject.hash) { + var md2 = forge.md.sha1.create(); + subject.attributes = pki2.RDNAttributesAsArray(_dnToAsn1(subject), md2); + subject.hash = md2.digest().toHex(); + } + } + if (certs) { + for (var i = 0; i < certs.length; ++i) { + var cert = certs[i]; + caStore.addCertificate(cert); + } + } + return caStore; + }; + pki2.certificateError = { + bad_certificate: "forge.pki.BadCertificate", + unsupported_certificate: "forge.pki.UnsupportedCertificate", + certificate_revoked: "forge.pki.CertificateRevoked", + certificate_expired: "forge.pki.CertificateExpired", + certificate_unknown: "forge.pki.CertificateUnknown", + unknown_ca: "forge.pki.UnknownCertificateAuthority" + }; + pki2.verifyCertificateChain = function(caStore, chain, options) { + if (typeof options === "function") { + options = { verify: options }; + } + options = options || {}; + chain = chain.slice(0); + var certs = chain.slice(0); + var validityCheckDate = options.validityCheckDate; + if (typeof validityCheckDate === "undefined") { + validityCheckDate = /* @__PURE__ */ new Date(); + } + var first = true; + var error2 = null; + var depth = 0; + do { + var cert = chain.shift(); + var parent = null; + var selfSigned = false; + if (validityCheckDate) { + if (validityCheckDate < cert.validity.notBefore || validityCheckDate > cert.validity.notAfter) { + error2 = { + message: "Certificate is not valid yet or has expired.", + error: pki2.certificateError.certificate_expired, + notBefore: cert.validity.notBefore, + notAfter: cert.validity.notAfter, + // TODO: we might want to reconsider renaming 'now' to + // 'validityCheckDate' should this API be changed in the future. + now: validityCheckDate + }; + } + } + if (error2 === null) { + parent = chain[0] || caStore.getIssuer(cert); + if (parent === null) { + if (cert.isIssuer(cert)) { + selfSigned = true; + parent = cert; + } + } + if (parent) { + var parents = parent; + if (!forge.util.isArray(parents)) { + parents = [parents]; + } + var verified = false; + while (!verified && parents.length > 0) { + parent = parents.shift(); + try { + verified = parent.verify(cert); + } catch (ex) { + } + } + if (!verified) { + error2 = { + message: "Certificate signature is invalid.", + error: pki2.certificateError.bad_certificate + }; + } + } + if (error2 === null && (!parent || selfSigned) && !caStore.hasCertificate(cert)) { + error2 = { + message: "Certificate is not trusted.", + error: pki2.certificateError.unknown_ca + }; + } + } + if (error2 === null && parent && !cert.isIssuer(parent)) { + error2 = { + message: "Certificate issuer is invalid.", + error: pki2.certificateError.bad_certificate + }; + } + if (error2 === null) { + var se = { + keyUsage: true, + basicConstraints: true + }; + for (var i = 0; error2 === null && i < cert.extensions.length; ++i) { + var ext = cert.extensions[i]; + if (ext.critical && !(ext.name in se)) { + error2 = { + message: "Certificate has an unsupported critical extension.", + error: pki2.certificateError.unsupported_certificate + }; + } + } + } + if (error2 === null && (!first || chain.length === 0 && (!parent || selfSigned))) { + var bcExt = cert.getExtension("basicConstraints"); + var keyUsageExt = cert.getExtension("keyUsage"); + if (keyUsageExt !== null) { + if (!keyUsageExt.keyCertSign || bcExt === null) { + error2 = { + message: "Certificate keyUsage or basicConstraints conflict or indicate that the certificate is not a CA. If the certificate is the only one in the chain or isn't the first then the certificate must be a valid CA.", + error: pki2.certificateError.bad_certificate + }; + } + } + if (error2 === null && bcExt === null) { + error2 = { + message: "Certificate is missing basicConstraints extension and cannot be used as a CA.", + error: pki2.certificateError.bad_certificate + }; + } + if (error2 === null && bcExt !== null && !bcExt.cA) { + error2 = { + message: "Certificate basicConstraints indicates the certificate is not a CA.", + error: pki2.certificateError.bad_certificate + }; + } + if (error2 === null && keyUsageExt !== null && "pathLenConstraint" in bcExt) { + var pathLen = depth - 1; + if (pathLen > bcExt.pathLenConstraint) { + error2 = { + message: "Certificate basicConstraints pathLenConstraint violated.", + error: pki2.certificateError.bad_certificate + }; + } + } + } + var vfd = error2 === null ? true : error2.error; + var ret = options.verify ? options.verify(vfd, depth, certs) : vfd; + if (ret === true) { + error2 = null; + } else { + if (vfd === true) { + error2 = { + message: "The application rejected the certificate.", + error: pki2.certificateError.bad_certificate + }; + } + if (ret || ret === 0) { + if (typeof ret === "object" && !forge.util.isArray(ret)) { + if (ret.message) { + error2.message = ret.message; + } + if (ret.error) { + error2.error = ret.error; + } + } else if (typeof ret === "string") { + error2.error = ret; + } + } + throw error2; + } + first = false; + ++depth; + } while (chain.length > 0); + return true; + }; + } +}); + +// node_modules/node-forge/lib/pkcs12.js +var require_pkcs12 = __commonJS({ + "node_modules/node-forge/lib/pkcs12.js"(exports2, module2) { + var forge = require_forge(); + require_asn1(); + require_hmac(); + require_oids(); + require_pkcs7asn1(); + require_pbe(); + require_random(); + require_rsa(); + require_sha1(); + require_util13(); + require_x509(); + var asn1 = forge.asn1; + var pki2 = forge.pki; + var p12 = module2.exports = forge.pkcs12 = forge.pkcs12 || {}; + var contentInfoValidator = { + name: "ContentInfo", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + // a ContentInfo + constructed: true, + value: [{ + name: "ContentInfo.contentType", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "contentType" + }, { + name: "ContentInfo.content", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + constructed: true, + captureAsn1: "content" + }] + }; + var pfxValidator = { + name: "PFX", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: "PFX.version", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "version" + }, + contentInfoValidator, + { + name: "PFX.macData", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + optional: true, + captureAsn1: "mac", + value: [{ + name: "PFX.macData.mac", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + // DigestInfo + constructed: true, + value: [{ + name: "PFX.macData.mac.digestAlgorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + // DigestAlgorithmIdentifier + constructed: true, + value: [{ + name: "PFX.macData.mac.digestAlgorithm.algorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "macAlgorithm" + }, { + name: "PFX.macData.mac.digestAlgorithm.parameters", + optional: true, + tagClass: asn1.Class.UNIVERSAL, + captureAsn1: "macAlgorithmParameters" + }] + }, { + name: "PFX.macData.mac.digest", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: "macDigest" + }] + }, { + name: "PFX.macData.macSalt", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: "macSalt" + }, { + name: "PFX.macData.iterations", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + optional: true, + capture: "macIterations" + }] + } + ] + }; + var safeBagValidator = { + name: "SafeBag", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "SafeBag.bagId", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "bagId" + }, { + name: "SafeBag.bagValue", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + constructed: true, + captureAsn1: "bagValue" + }, { + name: "SafeBag.bagAttributes", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + constructed: true, + optional: true, + capture: "bagAttributes" + }] + }; + var attributeValidator = { + name: "Attribute", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "Attribute.attrId", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "oid" + }, { + name: "Attribute.attrValues", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + constructed: true, + capture: "values" + }] + }; + var certBagValidator = { + name: "CertBag", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "CertBag.certId", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "certId" + }, { + name: "CertBag.certValue", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + constructed: true, + /* So far we only support X.509 certificates (which are wrapped in + an OCTET STRING, hence hard code that here). */ + value: [{ + name: "CertBag.certValue[0]", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Class.OCTETSTRING, + constructed: false, + capture: "cert" + }] + }] + }; + function _getBagsByAttribute(safeContents, attrName, attrValue, bagType) { + var result = []; + for (var i = 0; i < safeContents.length; i++) { + for (var j = 0; j < safeContents[i].safeBags.length; j++) { + var bag = safeContents[i].safeBags[j]; + if (bagType !== void 0 && bag.type !== bagType) { + continue; + } + if (attrName === null) { + result.push(bag); + continue; + } + if (bag.attributes[attrName] !== void 0 && bag.attributes[attrName].indexOf(attrValue) >= 0) { + result.push(bag); + } + } + } + return result; + } + p12.pkcs12FromAsn1 = function(obj, strict, password) { + if (typeof strict === "string") { + password = strict; + strict = true; + } else if (strict === void 0) { + strict = true; + } + var capture = {}; + var errors = []; + if (!asn1.validate(obj, pfxValidator, capture, errors)) { + var error2 = new Error("Cannot read PKCS#12 PFX. ASN.1 object is not an PKCS#12 PFX."); + error2.errors = error2; + throw error2; + } + var pfx = { + version: capture.version.charCodeAt(0), + safeContents: [], + /** + * Gets bags with matching attributes. + * + * @param filter the attributes to filter by: + * [localKeyId] the localKeyId to search for. + * [localKeyIdHex] the localKeyId in hex to search for. + * [friendlyName] the friendly name to search for. + * [bagType] bag type to narrow each attribute search by. + * + * @return a map of attribute type to an array of matching bags or, if no + * attribute was given but a bag type, the map key will be the + * bag type. + */ + getBags: function(filter) { + var rval = {}; + var localKeyId; + if ("localKeyId" in filter) { + localKeyId = filter.localKeyId; + } else if ("localKeyIdHex" in filter) { + localKeyId = forge.util.hexToBytes(filter.localKeyIdHex); + } + if (localKeyId === void 0 && !("friendlyName" in filter) && "bagType" in filter) { + rval[filter.bagType] = _getBagsByAttribute( + pfx.safeContents, + null, + null, + filter.bagType + ); + } + if (localKeyId !== void 0) { + rval.localKeyId = _getBagsByAttribute( + pfx.safeContents, + "localKeyId", + localKeyId, + filter.bagType + ); + } + if ("friendlyName" in filter) { + rval.friendlyName = _getBagsByAttribute( + pfx.safeContents, + "friendlyName", + filter.friendlyName, + filter.bagType + ); + } + return rval; + }, + /** + * DEPRECATED: use getBags() instead. + * + * Get bags with matching friendlyName attribute. + * + * @param friendlyName the friendly name to search for. + * @param [bagType] bag type to narrow search by. + * + * @return an array of bags with matching friendlyName attribute. + */ + getBagsByFriendlyName: function(friendlyName, bagType) { + return _getBagsByAttribute( + pfx.safeContents, + "friendlyName", + friendlyName, + bagType + ); + }, + /** + * DEPRECATED: use getBags() instead. + * + * Get bags with matching localKeyId attribute. + * + * @param localKeyId the localKeyId to search for. + * @param [bagType] bag type to narrow search by. + * + * @return an array of bags with matching localKeyId attribute. + */ + getBagsByLocalKeyId: function(localKeyId, bagType) { + return _getBagsByAttribute( + pfx.safeContents, + "localKeyId", + localKeyId, + bagType + ); + } + }; + if (capture.version.charCodeAt(0) !== 3) { + var error2 = new Error("PKCS#12 PFX of version other than 3 not supported."); + error2.version = capture.version.charCodeAt(0); + throw error2; + } + if (asn1.derToOid(capture.contentType) !== pki2.oids.data) { + var error2 = new Error("Only PKCS#12 PFX in password integrity mode supported."); + error2.oid = asn1.derToOid(capture.contentType); + throw error2; + } + var data = capture.content.value[0]; + if (data.tagClass !== asn1.Class.UNIVERSAL || data.type !== asn1.Type.OCTETSTRING) { + throw new Error("PKCS#12 authSafe content data is not an OCTET STRING."); + } + data = _decodePkcs7Data(data); + if (capture.mac) { + var md2 = null; + var macKeyBytes = 0; + var macAlgorithm = asn1.derToOid(capture.macAlgorithm); + switch (macAlgorithm) { + case pki2.oids.sha1: + md2 = forge.md.sha1.create(); + macKeyBytes = 20; + break; + case pki2.oids.sha256: + md2 = forge.md.sha256.create(); + macKeyBytes = 32; + break; + case pki2.oids.sha384: + md2 = forge.md.sha384.create(); + macKeyBytes = 48; + break; + case pki2.oids.sha512: + md2 = forge.md.sha512.create(); + macKeyBytes = 64; + break; + case pki2.oids.md5: + md2 = forge.md.md5.create(); + macKeyBytes = 16; + break; + } + if (md2 === null) { + throw new Error("PKCS#12 uses unsupported MAC algorithm: " + macAlgorithm); + } + var macSalt = new forge.util.ByteBuffer(capture.macSalt); + var macIterations = "macIterations" in capture ? parseInt(forge.util.bytesToHex(capture.macIterations), 16) : 1; + var macKey = p12.generateKey( + password, + macSalt, + 3, + macIterations, + macKeyBytes, + md2 + ); + var mac = forge.hmac.create(); + mac.start(md2, macKey); + mac.update(data.value); + var macValue = mac.getMac(); + if (macValue.getBytes() !== capture.macDigest) { + throw new Error("PKCS#12 MAC could not be verified. Invalid password?"); + } + } else if (Array.isArray(obj.value) && obj.value.length > 2) { + throw new Error("Invalid PKCS#12. macData field present but MAC was not validated."); + } + _decodeAuthenticatedSafe(pfx, data.value, strict, password); + return pfx; + }; + function _decodePkcs7Data(data) { + if (data.composed || data.constructed) { + var value = forge.util.createBuffer(); + for (var i = 0; i < data.value.length; ++i) { + value.putBytes(data.value[i].value); + } + data.composed = data.constructed = false; + data.value = value.getBytes(); + } + return data; + } + function _decodeAuthenticatedSafe(pfx, authSafe, strict, password) { + authSafe = asn1.fromDer(authSafe, strict); + if (authSafe.tagClass !== asn1.Class.UNIVERSAL || authSafe.type !== asn1.Type.SEQUENCE || authSafe.constructed !== true) { + throw new Error("PKCS#12 AuthenticatedSafe expected to be a SEQUENCE OF ContentInfo"); + } + for (var i = 0; i < authSafe.value.length; i++) { + var contentInfo = authSafe.value[i]; + var capture = {}; + var errors = []; + if (!asn1.validate(contentInfo, contentInfoValidator, capture, errors)) { + var error2 = new Error("Cannot read ContentInfo."); + error2.errors = errors; + throw error2; + } + var obj = { + encrypted: false + }; + var safeContents = null; + var data = capture.content.value[0]; + switch (asn1.derToOid(capture.contentType)) { + case pki2.oids.data: + if (data.tagClass !== asn1.Class.UNIVERSAL || data.type !== asn1.Type.OCTETSTRING) { + throw new Error("PKCS#12 SafeContents Data is not an OCTET STRING."); + } + safeContents = _decodePkcs7Data(data).value; + break; + case pki2.oids.encryptedData: + safeContents = _decryptSafeContents(data, password); + obj.encrypted = true; + break; + default: + var error2 = new Error("Unsupported PKCS#12 contentType."); + error2.contentType = asn1.derToOid(capture.contentType); + throw error2; + } + obj.safeBags = _decodeSafeContents(safeContents, strict, password); + pfx.safeContents.push(obj); + } + } + function _decryptSafeContents(data, password) { + var capture = {}; + var errors = []; + if (!asn1.validate( + data, + forge.pkcs7.asn1.encryptedDataValidator, + capture, + errors + )) { + var error2 = new Error("Cannot read EncryptedContentInfo."); + error2.errors = errors; + throw error2; + } + var oid = asn1.derToOid(capture.contentType); + if (oid !== pki2.oids.data) { + var error2 = new Error( + "PKCS#12 EncryptedContentInfo ContentType is not Data." + ); + error2.oid = oid; + throw error2; + } + oid = asn1.derToOid(capture.encAlgorithm); + var cipher = pki2.pbe.getCipher(oid, capture.encParameter, password); + var encryptedContentAsn1 = _decodePkcs7Data(capture.encryptedContentAsn1); + var encrypted = forge.util.createBuffer(encryptedContentAsn1.value); + cipher.update(encrypted); + if (!cipher.finish()) { + throw new Error("Failed to decrypt PKCS#12 SafeContents."); + } + return cipher.output.getBytes(); + } + function _decodeSafeContents(safeContents, strict, password) { + if (!strict && safeContents.length === 0) { + return []; + } + safeContents = asn1.fromDer(safeContents, strict); + if (safeContents.tagClass !== asn1.Class.UNIVERSAL || safeContents.type !== asn1.Type.SEQUENCE || safeContents.constructed !== true) { + throw new Error( + "PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag." + ); + } + var res = []; + for (var i = 0; i < safeContents.value.length; i++) { + var safeBag = safeContents.value[i]; + var capture = {}; + var errors = []; + if (!asn1.validate(safeBag, safeBagValidator, capture, errors)) { + var error2 = new Error("Cannot read SafeBag."); + error2.errors = errors; + throw error2; + } + var bag = { + type: asn1.derToOid(capture.bagId), + attributes: _decodeBagAttributes(capture.bagAttributes) + }; + res.push(bag); + var validator, decoder; + var bagAsn1 = capture.bagValue.value[0]; + switch (bag.type) { + case pki2.oids.pkcs8ShroudedKeyBag: + bagAsn1 = pki2.decryptPrivateKeyInfo(bagAsn1, password); + if (bagAsn1 === null) { + throw new Error( + "Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?" + ); + } + /* fall through */ + case pki2.oids.keyBag: + try { + bag.key = pki2.privateKeyFromAsn1(bagAsn1); + } catch (e) { + bag.key = null; + bag.asn1 = bagAsn1; + } + continue; + /* Nothing more to do. */ + case pki2.oids.certBag: + validator = certBagValidator; + decoder = function() { + if (asn1.derToOid(capture.certId) !== pki2.oids.x509Certificate) { + var error3 = new Error( + "Unsupported certificate type, only X.509 supported." + ); + error3.oid = asn1.derToOid(capture.certId); + throw error3; + } + var certAsn1 = asn1.fromDer(capture.cert, strict); + try { + bag.cert = pki2.certificateFromAsn1(certAsn1, true); + } catch (e) { + bag.cert = null; + bag.asn1 = certAsn1; + } + }; + break; + default: + var error2 = new Error("Unsupported PKCS#12 SafeBag type."); + error2.oid = bag.type; + throw error2; + } + if (validator !== void 0 && !asn1.validate(bagAsn1, validator, capture, errors)) { + var error2 = new Error("Cannot read PKCS#12 " + validator.name); + error2.errors = errors; + throw error2; + } + decoder(); + } + return res; + } + function _decodeBagAttributes(attributes) { + var decodedAttrs = {}; + if (attributes !== void 0) { + for (var i = 0; i < attributes.length; ++i) { + var capture = {}; + var errors = []; + if (!asn1.validate(attributes[i], attributeValidator, capture, errors)) { + var error2 = new Error("Cannot read PKCS#12 BagAttribute."); + error2.errors = errors; + throw error2; + } + var oid = asn1.derToOid(capture.oid); + if (pki2.oids[oid] === void 0) { + continue; + } + decodedAttrs[pki2.oids[oid]] = []; + for (var j = 0; j < capture.values.length; ++j) { + decodedAttrs[pki2.oids[oid]].push(capture.values[j].value); + } + } + } + return decodedAttrs; + } + p12.toPkcs12Asn1 = function(key, cert, password, options) { + options = options || {}; + options.saltSize = options.saltSize || 8; + options.count = options.count || 2048; + options.algorithm = options.algorithm || options.encAlgorithm || "aes128"; + if (!("useMac" in options)) { + options.useMac = true; + } + if (!("localKeyId" in options)) { + options.localKeyId = null; + } + if (!("generateLocalKeyId" in options)) { + options.generateLocalKeyId = true; + } + var localKeyId = options.localKeyId; + var bagAttrs; + if (localKeyId !== null) { + localKeyId = forge.util.hexToBytes(localKeyId); + } else if (options.generateLocalKeyId) { + if (cert) { + var pairedCert = forge.util.isArray(cert) ? cert[0] : cert; + if (typeof pairedCert === "string") { + pairedCert = pki2.certificateFromPem(pairedCert); + } + var sha1 = forge.md.sha1.create(); + sha1.update(asn1.toDer(pki2.certificateToAsn1(pairedCert)).getBytes()); + localKeyId = sha1.digest().getBytes(); + } else { + localKeyId = forge.random.getBytes(20); + } + } + var attrs = []; + if (localKeyId !== null) { + attrs.push( + // localKeyID + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // attrId + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(pki2.oids.localKeyId).getBytes() + ), + // attrValues + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + localKeyId + ) + ]) + ]) + ); + } + if ("friendlyName" in options) { + attrs.push( + // friendlyName + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // attrId + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(pki2.oids.friendlyName).getBytes() + ), + // attrValues + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.BMPSTRING, + false, + options.friendlyName + ) + ]) + ]) + ); + } + if (attrs.length > 0) { + bagAttrs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, attrs); + } + var contents = []; + var chain = []; + if (cert !== null) { + if (forge.util.isArray(cert)) { + chain = cert; + } else { + chain = [cert]; + } + } + var certSafeBags = []; + for (var i = 0; i < chain.length; ++i) { + cert = chain[i]; + if (typeof cert === "string") { + cert = pki2.certificateFromPem(cert); + } + var certBagAttrs = i === 0 ? bagAttrs : void 0; + var certAsn1 = pki2.certificateToAsn1(cert); + var certSafeBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // bagId + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(pki2.oids.certBag).getBytes() + ), + // bagValue + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + // CertBag + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // certId + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(pki2.oids.x509Certificate).getBytes() + ), + // certValue (x509Certificate) + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + asn1.toDer(certAsn1).getBytes() + ) + ]) + ]) + ]), + // bagAttributes (OPTIONAL) + certBagAttrs + ]); + certSafeBags.push(certSafeBag); + } + if (certSafeBags.length > 0) { + var certSafeContents = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SEQUENCE, + true, + certSafeBags + ); + var certCI = ( + // PKCS#7 ContentInfo + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // contentType + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + // OID for the content type is 'data' + asn1.oidToDer(pki2.oids.data).getBytes() + ), + // content + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + asn1.toDer(certSafeContents).getBytes() + ) + ]) + ]) + ); + contents.push(certCI); + } + var keyBag = null; + if (key !== null) { + var pkAsn1 = pki2.wrapRsaPrivateKey(pki2.privateKeyToAsn1(key)); + if (password === null) { + keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // bagId + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(pki2.oids.keyBag).getBytes() + ), + // bagValue + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + // PrivateKeyInfo + pkAsn1 + ]), + // bagAttributes (OPTIONAL) + bagAttrs + ]); + } else { + keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // bagId + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(pki2.oids.pkcs8ShroudedKeyBag).getBytes() + ), + // bagValue + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + // EncryptedPrivateKeyInfo + pki2.encryptPrivateKeyInfo(pkAsn1, password, options) + ]), + // bagAttributes (OPTIONAL) + bagAttrs + ]); + } + var keySafeContents = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [keyBag]); + var keyCI = ( + // PKCS#7 ContentInfo + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // contentType + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + // OID for the content type is 'data' + asn1.oidToDer(pki2.oids.data).getBytes() + ), + // content + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + asn1.toDer(keySafeContents).getBytes() + ) + ]) + ]) + ); + contents.push(keyCI); + } + var safe = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SEQUENCE, + true, + contents + ); + var macData; + if (options.useMac) { + var sha1 = forge.md.sha1.create(); + var macSalt = new forge.util.ByteBuffer( + forge.random.getBytes(options.saltSize) + ); + var count = options.count; + var key = p12.generateKey(password, macSalt, 3, count, 20); + var mac = forge.hmac.create(); + mac.start(sha1, key); + mac.update(asn1.toDer(safe).getBytes()); + var macValue = mac.getMac(); + macData = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // mac DigestInfo + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // digestAlgorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm = SHA-1 + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(pki2.oids.sha1).getBytes() + ), + // parameters = Null + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") + ]), + // digest + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + macValue.getBytes() + ) + ]), + // macSalt OCTET STRING + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + macSalt.getBytes() + ), + // iterations INTEGER (XXX: Only support count < 65536) + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + asn1.integerToDer(count).getBytes() + ) + ]); + } + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // version (3) + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + asn1.integerToDer(3).getBytes() + ), + // PKCS#7 ContentInfo + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // contentType + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + // OID for the content type is 'data' + asn1.oidToDer(pki2.oids.data).getBytes() + ), + // content + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + asn1.toDer(safe).getBytes() + ) + ]) + ]), + macData + ]); + }; + p12.generateKey = forge.pbe.generatePkcs12Key; + } +}); + +// node_modules/node-forge/lib/pki.js +var require_pki = __commonJS({ + "node_modules/node-forge/lib/pki.js"(exports2, module2) { + var forge = require_forge(); + require_asn1(); + require_oids(); + require_pbe(); + require_pem(); + require_pbkdf2(); + require_pkcs12(); + require_pss(); + require_rsa(); + require_util13(); + require_x509(); + var asn1 = forge.asn1; + var pki2 = module2.exports = forge.pki = forge.pki || {}; + pki2.pemToDer = function(pem) { + var msg = forge.pem.decode(pem)[0]; + if (msg.procType && msg.procType.type === "ENCRYPTED") { + throw new Error("Could not convert PEM to DER; PEM is encrypted."); + } + return forge.util.createBuffer(msg.body); + }; + pki2.privateKeyFromPem = function(pem) { + var msg = forge.pem.decode(pem)[0]; + if (msg.type !== "PRIVATE KEY" && msg.type !== "RSA PRIVATE KEY") { + var error2 = new Error('Could not convert private key from PEM; PEM header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".'); + error2.headerType = msg.type; + throw error2; + } + if (msg.procType && msg.procType.type === "ENCRYPTED") { + throw new Error("Could not convert private key from PEM; PEM is encrypted."); + } + var obj = asn1.fromDer(msg.body); + return pki2.privateKeyFromAsn1(obj); + }; + pki2.privateKeyToPem = function(key, maxline) { + var msg = { + type: "RSA PRIVATE KEY", + body: asn1.toDer(pki2.privateKeyToAsn1(key)).getBytes() + }; + return forge.pem.encode(msg, { maxline }); + }; + pki2.privateKeyInfoToPem = function(pki3, maxline) { + var msg = { + type: "PRIVATE KEY", + body: asn1.toDer(pki3).getBytes() + }; + return forge.pem.encode(msg, { maxline }); + }; + } +}); + +// node_modules/node-forge/lib/tls.js +var require_tls = __commonJS({ + "node_modules/node-forge/lib/tls.js"(exports2, module2) { + var forge = require_forge(); + require_asn1(); + require_hmac(); + require_md5(); + require_pem(); + require_pki(); + require_random(); + require_sha1(); + require_util13(); + var prf_TLS1 = function(secret, label, seed, length) { + var rval = forge.util.createBuffer(); + var idx = secret.length >> 1; + var slen = idx + (secret.length & 1); + var s1 = secret.substr(0, slen); + var s2 = secret.substr(idx, slen); + var ai = forge.util.createBuffer(); + var hmac = forge.hmac.create(); + seed = label + seed; + var md5itr = Math.ceil(length / 16); + var sha1itr = Math.ceil(length / 20); + hmac.start("MD5", s1); + var md5bytes = forge.util.createBuffer(); + ai.putBytes(seed); + for (var i = 0; i < md5itr; ++i) { + hmac.start(null, null); + hmac.update(ai.getBytes()); + ai.putBuffer(hmac.digest()); + hmac.start(null, null); + hmac.update(ai.bytes() + seed); + md5bytes.putBuffer(hmac.digest()); + } + hmac.start("SHA1", s2); + var sha1bytes = forge.util.createBuffer(); + ai.clear(); + ai.putBytes(seed); + for (var i = 0; i < sha1itr; ++i) { + hmac.start(null, null); + hmac.update(ai.getBytes()); + ai.putBuffer(hmac.digest()); + hmac.start(null, null); + hmac.update(ai.bytes() + seed); + sha1bytes.putBuffer(hmac.digest()); + } + rval.putBytes(forge.util.xorBytes( + md5bytes.getBytes(), + sha1bytes.getBytes(), + length + )); + return rval; + }; + var hmac_sha1 = function(key2, seqNum, record) { + var hmac = forge.hmac.create(); + hmac.start("SHA1", key2); + var b = forge.util.createBuffer(); + b.putInt32(seqNum[0]); + b.putInt32(seqNum[1]); + b.putByte(record.type); + b.putByte(record.version.major); + b.putByte(record.version.minor); + b.putInt16(record.length); + b.putBytes(record.fragment.bytes()); + hmac.update(b.getBytes()); + return hmac.digest().getBytes(); + }; + var deflate = function(c, record, s) { + var rval = false; + try { + var bytes = c.deflate(record.fragment.getBytes()); + record.fragment = forge.util.createBuffer(bytes); + record.length = bytes.length; + rval = true; + } catch (ex) { + } + return rval; + }; + var inflate = function(c, record, s) { + var rval = false; + try { + var bytes = c.inflate(record.fragment.getBytes()); + record.fragment = forge.util.createBuffer(bytes); + record.length = bytes.length; + rval = true; + } catch (ex) { + } + return rval; + }; + var readVector = function(b, lenBytes) { + var len = 0; + switch (lenBytes) { + case 1: + len = b.getByte(); + break; + case 2: + len = b.getInt16(); + break; + case 3: + len = b.getInt24(); + break; + case 4: + len = b.getInt32(); + break; + } + return forge.util.createBuffer(b.getBytes(len)); + }; + var writeVector = function(b, lenBytes, v) { + b.putInt(v.length(), lenBytes << 3); + b.putBuffer(v); + }; + var tls = {}; + tls.Versions = { + TLS_1_0: { major: 3, minor: 1 }, + TLS_1_1: { major: 3, minor: 2 }, + TLS_1_2: { major: 3, minor: 3 } + }; + tls.SupportedVersions = [ + tls.Versions.TLS_1_1, + tls.Versions.TLS_1_0 + ]; + tls.Version = tls.SupportedVersions[0]; + tls.MaxFragment = 16384 - 1024; + tls.ConnectionEnd = { + server: 0, + client: 1 + }; + tls.PRFAlgorithm = { + tls_prf_sha256: 0 + }; + tls.BulkCipherAlgorithm = { + none: null, + rc4: 0, + des3: 1, + aes: 2 + }; + tls.CipherType = { + stream: 0, + block: 1, + aead: 2 + }; + tls.MACAlgorithm = { + none: null, + hmac_md5: 0, + hmac_sha1: 1, + hmac_sha256: 2, + hmac_sha384: 3, + hmac_sha512: 4 + }; + tls.CompressionMethod = { + none: 0, + deflate: 1 + }; + tls.ContentType = { + change_cipher_spec: 20, + alert: 21, + handshake: 22, + application_data: 23, + heartbeat: 24 + }; + tls.HandshakeType = { + hello_request: 0, + client_hello: 1, + server_hello: 2, + certificate: 11, + server_key_exchange: 12, + certificate_request: 13, + server_hello_done: 14, + certificate_verify: 15, + client_key_exchange: 16, + finished: 20 + }; + tls.Alert = {}; + tls.Alert.Level = { + warning: 1, + fatal: 2 + }; + tls.Alert.Description = { + close_notify: 0, + unexpected_message: 10, + bad_record_mac: 20, + decryption_failed: 21, + record_overflow: 22, + decompression_failure: 30, + handshake_failure: 40, + bad_certificate: 42, + unsupported_certificate: 43, + certificate_revoked: 44, + certificate_expired: 45, + certificate_unknown: 46, + illegal_parameter: 47, + unknown_ca: 48, + access_denied: 49, + decode_error: 50, + decrypt_error: 51, + export_restriction: 60, + protocol_version: 70, + insufficient_security: 71, + internal_error: 80, + user_canceled: 90, + no_renegotiation: 100 + }; + tls.HeartbeatMessageType = { + heartbeat_request: 1, + heartbeat_response: 2 + }; + tls.CipherSuites = {}; + tls.getCipherSuite = function(twoBytes) { + var rval = null; + for (var key2 in tls.CipherSuites) { + var cs = tls.CipherSuites[key2]; + if (cs.id[0] === twoBytes.charCodeAt(0) && cs.id[1] === twoBytes.charCodeAt(1)) { + rval = cs; + break; + } + } + return rval; + }; + tls.handleUnexpected = function(c, record) { + var ignore = !c.open && c.entity === tls.ConnectionEnd.client; + if (!ignore) { + c.error(c, { + message: "Unexpected message. Received TLS record out of order.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.unexpected_message + } + }); + } + }; + tls.handleHelloRequest = function(c, record, length) { + if (!c.handshaking && c.handshakes > 0) { + tls.queue(c, tls.createAlert(c, { + level: tls.Alert.Level.warning, + description: tls.Alert.Description.no_renegotiation + })); + tls.flush(c); + } + c.process(); + }; + tls.parseHelloMessage = function(c, record, length) { + var msg = null; + var client = c.entity === tls.ConnectionEnd.client; + if (length < 38) { + c.error(c, { + message: client ? "Invalid ServerHello message. Message too short." : "Invalid ClientHello message. Message too short.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } else { + var b = record.fragment; + var remaining = b.length(); + msg = { + version: { + major: b.getByte(), + minor: b.getByte() + }, + random: forge.util.createBuffer(b.getBytes(32)), + session_id: readVector(b, 1), + extensions: [] + }; + if (client) { + msg.cipher_suite = b.getBytes(2); + msg.compression_method = b.getByte(); + } else { + msg.cipher_suites = readVector(b, 2); + msg.compression_methods = readVector(b, 1); + } + remaining = length - (remaining - b.length()); + if (remaining > 0) { + var exts = readVector(b, 2); + while (exts.length() > 0) { + msg.extensions.push({ + type: [exts.getByte(), exts.getByte()], + data: readVector(exts, 2) + }); + } + if (!client) { + for (var i = 0; i < msg.extensions.length; ++i) { + var ext = msg.extensions[i]; + if (ext.type[0] === 0 && ext.type[1] === 0) { + var snl = readVector(ext.data, 2); + while (snl.length() > 0) { + var snType = snl.getByte(); + if (snType !== 0) { + break; + } + c.session.extensions.server_name.serverNameList.push( + readVector(snl, 2).getBytes() + ); + } + } + } + } + } + if (c.session.version) { + if (msg.version.major !== c.session.version.major || msg.version.minor !== c.session.version.minor) { + return c.error(c, { + message: "TLS version change is disallowed during renegotiation.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.protocol_version + } + }); + } + } + if (client) { + c.session.cipherSuite = tls.getCipherSuite(msg.cipher_suite); + } else { + var tmp = forge.util.createBuffer(msg.cipher_suites.bytes()); + while (tmp.length() > 0) { + c.session.cipherSuite = tls.getCipherSuite(tmp.getBytes(2)); + if (c.session.cipherSuite !== null) { + break; + } + } + } + if (c.session.cipherSuite === null) { + return c.error(c, { + message: "No cipher suites in common.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.handshake_failure + }, + cipherSuite: forge.util.bytesToHex(msg.cipher_suite) + }); + } + if (client) { + c.session.compressionMethod = msg.compression_method; + } else { + c.session.compressionMethod = tls.CompressionMethod.none; + } + } + return msg; + }; + tls.createSecurityParameters = function(c, msg) { + var client = c.entity === tls.ConnectionEnd.client; + var msgRandom = msg.random.bytes(); + var cRandom = client ? c.session.sp.client_random : msgRandom; + var sRandom = client ? msgRandom : tls.createRandom().getBytes(); + c.session.sp = { + entity: c.entity, + prf_algorithm: tls.PRFAlgorithm.tls_prf_sha256, + bulk_cipher_algorithm: null, + cipher_type: null, + enc_key_length: null, + block_length: null, + fixed_iv_length: null, + record_iv_length: null, + mac_algorithm: null, + mac_length: null, + mac_key_length: null, + compression_algorithm: c.session.compressionMethod, + pre_master_secret: null, + master_secret: null, + client_random: cRandom, + server_random: sRandom + }; + }; + tls.handleServerHello = function(c, record, length) { + var msg = tls.parseHelloMessage(c, record, length); + if (c.fail) { + return; + } + if (msg.version.minor <= c.version.minor) { + c.version.minor = msg.version.minor; + } else { + return c.error(c, { + message: "Incompatible TLS version.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.protocol_version + } + }); + } + c.session.version = c.version; + var sessionId = msg.session_id.bytes(); + if (sessionId.length > 0 && sessionId === c.session.id) { + c.expect = SCC; + c.session.resuming = true; + c.session.sp.server_random = msg.random.bytes(); + } else { + c.expect = SCE; + c.session.resuming = false; + tls.createSecurityParameters(c, msg); + } + c.session.id = sessionId; + c.process(); + }; + tls.handleClientHello = function(c, record, length) { + var msg = tls.parseHelloMessage(c, record, length); + if (c.fail) { + return; + } + var sessionId = msg.session_id.bytes(); + var session = null; + if (c.sessionCache) { + session = c.sessionCache.getSession(sessionId); + if (session === null) { + sessionId = ""; + } else if (session.version.major !== msg.version.major || session.version.minor > msg.version.minor) { + session = null; + sessionId = ""; + } + } + if (sessionId.length === 0) { + sessionId = forge.random.getBytes(32); + } + c.session.id = sessionId; + c.session.clientHelloVersion = msg.version; + c.session.sp = {}; + if (session) { + c.version = c.session.version = session.version; + c.session.sp = session.sp; + } else { + var version; + for (var i = 1; i < tls.SupportedVersions.length; ++i) { + version = tls.SupportedVersions[i]; + if (version.minor <= msg.version.minor) { + break; + } + } + c.version = { major: version.major, minor: version.minor }; + c.session.version = c.version; + } + if (session !== null) { + c.expect = CCC; + c.session.resuming = true; + c.session.sp.client_random = msg.random.bytes(); + } else { + c.expect = c.verifyClient !== false ? CCE : CKE; + c.session.resuming = false; + tls.createSecurityParameters(c, msg); + } + c.open = true; + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createServerHello(c) + })); + if (c.session.resuming) { + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.change_cipher_spec, + data: tls.createChangeCipherSpec() + })); + c.state.pending = tls.createConnectionState(c); + c.state.current.write = c.state.pending.write; + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createFinished(c) + })); + } else { + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createCertificate(c) + })); + if (!c.fail) { + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createServerKeyExchange(c) + })); + if (c.verifyClient !== false) { + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createCertificateRequest(c) + })); + } + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createServerHelloDone(c) + })); + } + } + tls.flush(c); + c.process(); + }; + tls.handleCertificate = function(c, record, length) { + if (length < 3) { + return c.error(c, { + message: "Invalid Certificate message. Message too short.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } + var b = record.fragment; + var msg = { + certificate_list: readVector(b, 3) + }; + var cert, asn1; + var certs = []; + try { + while (msg.certificate_list.length() > 0) { + cert = readVector(msg.certificate_list, 3); + asn1 = forge.asn1.fromDer(cert); + cert = forge.pki.certificateFromAsn1(asn1, true); + certs.push(cert); + } + } catch (ex) { + return c.error(c, { + message: "Could not parse certificate list.", + cause: ex, + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.bad_certificate + } + }); + } + var client = c.entity === tls.ConnectionEnd.client; + if ((client || c.verifyClient === true) && certs.length === 0) { + c.error(c, { + message: client ? "No server certificate provided." : "No client certificate provided.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } else if (certs.length === 0) { + c.expect = client ? SKE : CKE; + } else { + if (client) { + c.session.serverCertificate = certs[0]; + } else { + c.session.clientCertificate = certs[0]; + } + if (tls.verifyCertificateChain(c, certs)) { + c.expect = client ? SKE : CKE; + } + } + c.process(); + }; + tls.handleServerKeyExchange = function(c, record, length) { + if (length > 0) { + return c.error(c, { + message: "Invalid key parameters. Only RSA is supported.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.unsupported_certificate + } + }); + } + c.expect = SCR; + c.process(); + }; + tls.handleClientKeyExchange = function(c, record, length) { + if (length < 48) { + return c.error(c, { + message: "Invalid key parameters. Only RSA is supported.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.unsupported_certificate + } + }); + } + var b = record.fragment; + var msg = { + enc_pre_master_secret: readVector(b, 2).getBytes() + }; + var privateKey = null; + if (c.getPrivateKey) { + try { + privateKey = c.getPrivateKey(c, c.session.serverCertificate); + privateKey = forge.pki.privateKeyFromPem(privateKey); + } catch (ex) { + c.error(c, { + message: "Could not get private key.", + cause: ex, + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } + } + if (privateKey === null) { + return c.error(c, { + message: "No private key set.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } + try { + var sp = c.session.sp; + sp.pre_master_secret = privateKey.decrypt(msg.enc_pre_master_secret); + var version = c.session.clientHelloVersion; + if (version.major !== sp.pre_master_secret.charCodeAt(0) || version.minor !== sp.pre_master_secret.charCodeAt(1)) { + throw new Error("TLS version rollback attack detected."); + } + } catch (ex) { + sp.pre_master_secret = forge.random.getBytes(48); + } + c.expect = CCC; + if (c.session.clientCertificate !== null) { + c.expect = CCV; + } + c.process(); + }; + tls.handleCertificateRequest = function(c, record, length) { + if (length < 3) { + return c.error(c, { + message: "Invalid CertificateRequest. Message too short.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } + var b = record.fragment; + var msg = { + certificate_types: readVector(b, 1), + certificate_authorities: readVector(b, 2) + }; + c.session.certificateRequest = msg; + c.expect = SHD; + c.process(); + }; + tls.handleCertificateVerify = function(c, record, length) { + if (length < 2) { + return c.error(c, { + message: "Invalid CertificateVerify. Message too short.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } + var b = record.fragment; + b.read -= 4; + var msgBytes = b.bytes(); + b.read += 4; + var msg = { + signature: readVector(b, 2).getBytes() + }; + var verify = forge.util.createBuffer(); + verify.putBuffer(c.session.md5.digest()); + verify.putBuffer(c.session.sha1.digest()); + verify = verify.getBytes(); + try { + var cert = c.session.clientCertificate; + if (!cert.publicKey.verify(verify, msg.signature, "NONE")) { + throw new Error("CertificateVerify signature does not match."); + } + c.session.md5.update(msgBytes); + c.session.sha1.update(msgBytes); + } catch (ex) { + return c.error(c, { + message: "Bad signature in CertificateVerify.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.handshake_failure + } + }); + } + c.expect = CCC; + c.process(); + }; + tls.handleServerHelloDone = function(c, record, length) { + if (length > 0) { + return c.error(c, { + message: "Invalid ServerHelloDone message. Invalid length.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.record_overflow + } + }); + } + if (c.serverCertificate === null) { + var error2 = { + message: "No server certificate provided. Not enough security.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.insufficient_security + } + }; + var depth = 0; + var ret = c.verify(c, error2.alert.description, depth, []); + if (ret !== true) { + if (ret || ret === 0) { + if (typeof ret === "object" && !forge.util.isArray(ret)) { + if (ret.message) { + error2.message = ret.message; + } + if (ret.alert) { + error2.alert.description = ret.alert; + } + } else if (typeof ret === "number") { + error2.alert.description = ret; + } + } + return c.error(c, error2); + } + } + if (c.session.certificateRequest !== null) { + record = tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createCertificate(c) + }); + tls.queue(c, record); + } + record = tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createClientKeyExchange(c) + }); + tls.queue(c, record); + c.expect = SER; + var callback = function(c2, signature) { + if (c2.session.certificateRequest !== null && c2.session.clientCertificate !== null) { + tls.queue(c2, tls.createRecord(c2, { + type: tls.ContentType.handshake, + data: tls.createCertificateVerify(c2, signature) + })); + } + tls.queue(c2, tls.createRecord(c2, { + type: tls.ContentType.change_cipher_spec, + data: tls.createChangeCipherSpec() + })); + c2.state.pending = tls.createConnectionState(c2); + c2.state.current.write = c2.state.pending.write; + tls.queue(c2, tls.createRecord(c2, { + type: tls.ContentType.handshake, + data: tls.createFinished(c2) + })); + c2.expect = SCC; + tls.flush(c2); + c2.process(); + }; + if (c.session.certificateRequest === null || c.session.clientCertificate === null) { + return callback(c, null); + } + tls.getClientSignature(c, callback); + }; + tls.handleChangeCipherSpec = function(c, record) { + if (record.fragment.getByte() !== 1) { + return c.error(c, { + message: "Invalid ChangeCipherSpec message received.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } + var client = c.entity === tls.ConnectionEnd.client; + if (c.session.resuming && client || !c.session.resuming && !client) { + c.state.pending = tls.createConnectionState(c); + } + c.state.current.read = c.state.pending.read; + if (!c.session.resuming && client || c.session.resuming && !client) { + c.state.pending = null; + } + c.expect = client ? SFI : CFI; + c.process(); + }; + tls.handleFinished = function(c, record, length) { + var b = record.fragment; + b.read -= 4; + var msgBytes = b.bytes(); + b.read += 4; + var vd = record.fragment.getBytes(); + b = forge.util.createBuffer(); + b.putBuffer(c.session.md5.digest()); + b.putBuffer(c.session.sha1.digest()); + var client = c.entity === tls.ConnectionEnd.client; + var label = client ? "server finished" : "client finished"; + var sp = c.session.sp; + var vdl = 12; + var prf = prf_TLS1; + b = prf(sp.master_secret, label, b.getBytes(), vdl); + if (b.getBytes() !== vd) { + return c.error(c, { + message: "Invalid verify_data in Finished message.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.decrypt_error + } + }); + } + c.session.md5.update(msgBytes); + c.session.sha1.update(msgBytes); + if (c.session.resuming && client || !c.session.resuming && !client) { + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.change_cipher_spec, + data: tls.createChangeCipherSpec() + })); + c.state.current.write = c.state.pending.write; + c.state.pending = null; + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createFinished(c) + })); + } + c.expect = client ? SAD : CAD; + c.handshaking = false; + ++c.handshakes; + c.peerCertificate = client ? c.session.serverCertificate : c.session.clientCertificate; + tls.flush(c); + c.isConnected = true; + c.connected(c); + c.process(); + }; + tls.handleAlert = function(c, record) { + var b = record.fragment; + var alert = { + level: b.getByte(), + description: b.getByte() + }; + var msg; + switch (alert.description) { + case tls.Alert.Description.close_notify: + msg = "Connection closed."; + break; + case tls.Alert.Description.unexpected_message: + msg = "Unexpected message."; + break; + case tls.Alert.Description.bad_record_mac: + msg = "Bad record MAC."; + break; + case tls.Alert.Description.decryption_failed: + msg = "Decryption failed."; + break; + case tls.Alert.Description.record_overflow: + msg = "Record overflow."; + break; + case tls.Alert.Description.decompression_failure: + msg = "Decompression failed."; + break; + case tls.Alert.Description.handshake_failure: + msg = "Handshake failure."; + break; + case tls.Alert.Description.bad_certificate: + msg = "Bad certificate."; + break; + case tls.Alert.Description.unsupported_certificate: + msg = "Unsupported certificate."; + break; + case tls.Alert.Description.certificate_revoked: + msg = "Certificate revoked."; + break; + case tls.Alert.Description.certificate_expired: + msg = "Certificate expired."; + break; + case tls.Alert.Description.certificate_unknown: + msg = "Certificate unknown."; + break; + case tls.Alert.Description.illegal_parameter: + msg = "Illegal parameter."; + break; + case tls.Alert.Description.unknown_ca: + msg = "Unknown certificate authority."; + break; + case tls.Alert.Description.access_denied: + msg = "Access denied."; + break; + case tls.Alert.Description.decode_error: + msg = "Decode error."; + break; + case tls.Alert.Description.decrypt_error: + msg = "Decrypt error."; + break; + case tls.Alert.Description.export_restriction: + msg = "Export restriction."; + break; + case tls.Alert.Description.protocol_version: + msg = "Unsupported protocol version."; + break; + case tls.Alert.Description.insufficient_security: + msg = "Insufficient security."; + break; + case tls.Alert.Description.internal_error: + msg = "Internal error."; + break; + case tls.Alert.Description.user_canceled: + msg = "User canceled."; + break; + case tls.Alert.Description.no_renegotiation: + msg = "Renegotiation not supported."; + break; + default: + msg = "Unknown error."; + break; + } + if (alert.description === tls.Alert.Description.close_notify) { + return c.close(); + } + c.error(c, { + message: msg, + send: false, + // origin is the opposite end + origin: c.entity === tls.ConnectionEnd.client ? "server" : "client", + alert + }); + c.process(); + }; + tls.handleHandshake = function(c, record) { + var b = record.fragment; + var type = b.getByte(); + var length = b.getInt24(); + if (length > b.length()) { + c.fragmented = record; + record.fragment = forge.util.createBuffer(); + b.read -= 4; + return c.process(); + } + c.fragmented = null; + b.read -= 4; + var bytes = b.bytes(length + 4); + b.read += 4; + if (type in hsTable[c.entity][c.expect]) { + if (c.entity === tls.ConnectionEnd.server && !c.open && !c.fail) { + c.handshaking = true; + c.session = { + version: null, + extensions: { + server_name: { + serverNameList: [] + } + }, + cipherSuite: null, + compressionMethod: null, + serverCertificate: null, + clientCertificate: null, + md5: forge.md.md5.create(), + sha1: forge.md.sha1.create() + }; + } + if (type !== tls.HandshakeType.hello_request && type !== tls.HandshakeType.certificate_verify && type !== tls.HandshakeType.finished) { + c.session.md5.update(bytes); + c.session.sha1.update(bytes); + } + hsTable[c.entity][c.expect][type](c, record, length); + } else { + tls.handleUnexpected(c, record); + } + }; + tls.handleApplicationData = function(c, record) { + c.data.putBuffer(record.fragment); + c.dataReady(c); + c.process(); + }; + tls.handleHeartbeat = function(c, record) { + var b = record.fragment; + var type = b.getByte(); + var length = b.getInt16(); + var payload = b.getBytes(length); + if (type === tls.HeartbeatMessageType.heartbeat_request) { + if (c.handshaking || length > payload.length) { + return c.process(); + } + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.heartbeat, + data: tls.createHeartbeat( + tls.HeartbeatMessageType.heartbeat_response, + payload + ) + })); + tls.flush(c); + } else if (type === tls.HeartbeatMessageType.heartbeat_response) { + if (payload !== c.expectedHeartbeatPayload) { + return c.process(); + } + if (c.heartbeatReceived) { + c.heartbeatReceived(c, forge.util.createBuffer(payload)); + } + } + c.process(); + }; + var SHE = 0; + var SCE = 1; + var SKE = 2; + var SCR = 3; + var SHD = 4; + var SCC = 5; + var SFI = 6; + var SAD = 7; + var SER = 8; + var CHE = 0; + var CCE = 1; + var CKE = 2; + var CCV = 3; + var CCC = 4; + var CFI = 5; + var CAD = 6; + var __ = tls.handleUnexpected; + var R0 = tls.handleChangeCipherSpec; + var R1 = tls.handleAlert; + var R2 = tls.handleHandshake; + var R3 = tls.handleApplicationData; + var R4 = tls.handleHeartbeat; + var ctTable = []; + ctTable[tls.ConnectionEnd.client] = [ + // CC,AL,HS,AD,HB + /*SHE*/ + [__, R1, R2, __, R4], + /*SCE*/ + [__, R1, R2, __, R4], + /*SKE*/ + [__, R1, R2, __, R4], + /*SCR*/ + [__, R1, R2, __, R4], + /*SHD*/ + [__, R1, R2, __, R4], + /*SCC*/ + [R0, R1, __, __, R4], + /*SFI*/ + [__, R1, R2, __, R4], + /*SAD*/ + [__, R1, R2, R3, R4], + /*SER*/ + [__, R1, R2, __, R4] + ]; + ctTable[tls.ConnectionEnd.server] = [ + // CC,AL,HS,AD + /*CHE*/ + [__, R1, R2, __, R4], + /*CCE*/ + [__, R1, R2, __, R4], + /*CKE*/ + [__, R1, R2, __, R4], + /*CCV*/ + [__, R1, R2, __, R4], + /*CCC*/ + [R0, R1, __, __, R4], + /*CFI*/ + [__, R1, R2, __, R4], + /*CAD*/ + [__, R1, R2, R3, R4], + /*CER*/ + [__, R1, R2, __, R4] + ]; + var H0 = tls.handleHelloRequest; + var H1 = tls.handleServerHello; + var H2 = tls.handleCertificate; + var H3 = tls.handleServerKeyExchange; + var H4 = tls.handleCertificateRequest; + var H5 = tls.handleServerHelloDone; + var H6 = tls.handleFinished; + var hsTable = []; + hsTable[tls.ConnectionEnd.client] = [ + // HR,01,SH,03,04,05,06,07,08,09,10,SC,SK,CR,HD,15,CK,17,18,19,FI + /*SHE*/ + [__, __, H1, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], + /*SCE*/ + [H0, __, __, __, __, __, __, __, __, __, __, H2, H3, H4, H5, __, __, __, __, __, __], + /*SKE*/ + [H0, __, __, __, __, __, __, __, __, __, __, __, H3, H4, H5, __, __, __, __, __, __], + /*SCR*/ + [H0, __, __, __, __, __, __, __, __, __, __, __, __, H4, H5, __, __, __, __, __, __], + /*SHD*/ + [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, H5, __, __, __, __, __, __], + /*SCC*/ + [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], + /*SFI*/ + [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H6], + /*SAD*/ + [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], + /*SER*/ + [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __] + ]; + var H7 = tls.handleClientHello; + var H8 = tls.handleClientKeyExchange; + var H9 = tls.handleCertificateVerify; + hsTable[tls.ConnectionEnd.server] = [ + // 01,CH,02,03,04,05,06,07,08,09,10,CC,12,13,14,CV,CK,17,18,19,FI + /*CHE*/ + [__, H7, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], + /*CCE*/ + [__, __, __, __, __, __, __, __, __, __, __, H2, __, __, __, __, __, __, __, __, __], + /*CKE*/ + [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H8, __, __, __, __], + /*CCV*/ + [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H9, __, __, __, __, __], + /*CCC*/ + [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], + /*CFI*/ + [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H6], + /*CAD*/ + [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], + /*CER*/ + [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __] + ]; + tls.generateKeys = function(c, sp) { + var prf = prf_TLS1; + var random = sp.client_random + sp.server_random; + if (!c.session.resuming) { + sp.master_secret = prf( + sp.pre_master_secret, + "master secret", + random, + 48 + ).bytes(); + sp.pre_master_secret = null; + } + random = sp.server_random + sp.client_random; + var length = 2 * sp.mac_key_length + 2 * sp.enc_key_length; + var tls10 = c.version.major === tls.Versions.TLS_1_0.major && c.version.minor === tls.Versions.TLS_1_0.minor; + if (tls10) { + length += 2 * sp.fixed_iv_length; + } + var km = prf(sp.master_secret, "key expansion", random, length); + var rval = { + client_write_MAC_key: km.getBytes(sp.mac_key_length), + server_write_MAC_key: km.getBytes(sp.mac_key_length), + client_write_key: km.getBytes(sp.enc_key_length), + server_write_key: km.getBytes(sp.enc_key_length) + }; + if (tls10) { + rval.client_write_IV = km.getBytes(sp.fixed_iv_length); + rval.server_write_IV = km.getBytes(sp.fixed_iv_length); + } + return rval; + }; + tls.createConnectionState = function(c) { + var client = c.entity === tls.ConnectionEnd.client; + var createMode = function() { + var mode = { + // two 32-bit numbers, first is most significant + sequenceNumber: [0, 0], + macKey: null, + macLength: 0, + macFunction: null, + cipherState: null, + cipherFunction: function(record) { + return true; + }, + compressionState: null, + compressFunction: function(record) { + return true; + }, + updateSequenceNumber: function() { + if (mode.sequenceNumber[1] === 4294967295) { + mode.sequenceNumber[1] = 0; + ++mode.sequenceNumber[0]; + } else { + ++mode.sequenceNumber[1]; + } + } + }; + return mode; + }; + var state = { + read: createMode(), + write: createMode() + }; + state.read.update = function(c2, record) { + if (!state.read.cipherFunction(record, state.read)) { + c2.error(c2, { + message: "Could not decrypt record or bad MAC.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + // doesn't matter if decryption failed or MAC was + // invalid, return the same error so as not to reveal + // which one occurred + description: tls.Alert.Description.bad_record_mac + } + }); + } else if (!state.read.compressFunction(c2, record, state.read)) { + c2.error(c2, { + message: "Could not decompress record.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.decompression_failure + } + }); + } + return !c2.fail; + }; + state.write.update = function(c2, record) { + if (!state.write.compressFunction(c2, record, state.write)) { + c2.error(c2, { + message: "Could not compress record.", + send: false, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } else if (!state.write.cipherFunction(record, state.write)) { + c2.error(c2, { + message: "Could not encrypt record.", + send: false, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } + return !c2.fail; + }; + if (c.session) { + var sp = c.session.sp; + c.session.cipherSuite.initSecurityParameters(sp); + sp.keys = tls.generateKeys(c, sp); + state.read.macKey = client ? sp.keys.server_write_MAC_key : sp.keys.client_write_MAC_key; + state.write.macKey = client ? sp.keys.client_write_MAC_key : sp.keys.server_write_MAC_key; + c.session.cipherSuite.initConnectionState(state, c, sp); + switch (sp.compression_algorithm) { + case tls.CompressionMethod.none: + break; + case tls.CompressionMethod.deflate: + state.read.compressFunction = inflate; + state.write.compressFunction = deflate; + break; + default: + throw new Error("Unsupported compression algorithm."); + } + } + return state; + }; + tls.createRandom = function() { + var d = /* @__PURE__ */ new Date(); + var utc = +d + d.getTimezoneOffset() * 6e4; + var rval = forge.util.createBuffer(); + rval.putInt32(utc); + rval.putBytes(forge.random.getBytes(28)); + return rval; + }; + tls.createRecord = function(c, options) { + if (!options.data) { + return null; + } + var record = { + type: options.type, + version: { + major: c.version.major, + minor: c.version.minor + }, + length: options.data.length(), + fragment: options.data + }; + return record; + }; + tls.createAlert = function(c, alert) { + var b = forge.util.createBuffer(); + b.putByte(alert.level); + b.putByte(alert.description); + return tls.createRecord(c, { + type: tls.ContentType.alert, + data: b + }); + }; + tls.createClientHello = function(c) { + c.session.clientHelloVersion = { + major: c.version.major, + minor: c.version.minor + }; + var cipherSuites = forge.util.createBuffer(); + for (var i = 0; i < c.cipherSuites.length; ++i) { + var cs = c.cipherSuites[i]; + cipherSuites.putByte(cs.id[0]); + cipherSuites.putByte(cs.id[1]); + } + var cSuites = cipherSuites.length(); + var compressionMethods = forge.util.createBuffer(); + compressionMethods.putByte(tls.CompressionMethod.none); + var cMethods = compressionMethods.length(); + var extensions = forge.util.createBuffer(); + if (c.virtualHost) { + var ext = forge.util.createBuffer(); + ext.putByte(0); + ext.putByte(0); + var serverName = forge.util.createBuffer(); + serverName.putByte(0); + writeVector(serverName, 2, forge.util.createBuffer(c.virtualHost)); + var snList = forge.util.createBuffer(); + writeVector(snList, 2, serverName); + writeVector(ext, 2, snList); + extensions.putBuffer(ext); + } + var extLength = extensions.length(); + if (extLength > 0) { + extLength += 2; + } + var sessionId = c.session.id; + var length = sessionId.length + 1 + // session ID vector + 2 + // version (major + minor) + 4 + 28 + // random time and random bytes + 2 + cSuites + // cipher suites vector + 1 + cMethods + // compression methods vector + extLength; + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.client_hello); + rval.putInt24(length); + rval.putByte(c.version.major); + rval.putByte(c.version.minor); + rval.putBytes(c.session.sp.client_random); + writeVector(rval, 1, forge.util.createBuffer(sessionId)); + writeVector(rval, 2, cipherSuites); + writeVector(rval, 1, compressionMethods); + if (extLength > 0) { + writeVector(rval, 2, extensions); + } + return rval; + }; + tls.createServerHello = function(c) { + var sessionId = c.session.id; + var length = sessionId.length + 1 + // session ID vector + 2 + // version (major + minor) + 4 + 28 + // random time and random bytes + 2 + // chosen cipher suite + 1; + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.server_hello); + rval.putInt24(length); + rval.putByte(c.version.major); + rval.putByte(c.version.minor); + rval.putBytes(c.session.sp.server_random); + writeVector(rval, 1, forge.util.createBuffer(sessionId)); + rval.putByte(c.session.cipherSuite.id[0]); + rval.putByte(c.session.cipherSuite.id[1]); + rval.putByte(c.session.compressionMethod); + return rval; + }; + tls.createCertificate = function(c) { + var client = c.entity === tls.ConnectionEnd.client; + var cert = null; + if (c.getCertificate) { + var hint; + if (client) { + hint = c.session.certificateRequest; + } else { + hint = c.session.extensions.server_name.serverNameList; + } + cert = c.getCertificate(c, hint); + } + var certList = forge.util.createBuffer(); + if (cert !== null) { + try { + if (!forge.util.isArray(cert)) { + cert = [cert]; + } + var asn1 = null; + for (var i = 0; i < cert.length; ++i) { + var msg = forge.pem.decode(cert[i])[0]; + if (msg.type !== "CERTIFICATE" && msg.type !== "X509 CERTIFICATE" && msg.type !== "TRUSTED CERTIFICATE") { + var error2 = new Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".'); + error2.headerType = msg.type; + throw error2; + } + if (msg.procType && msg.procType.type === "ENCRYPTED") { + throw new Error("Could not convert certificate from PEM; PEM is encrypted."); + } + var der = forge.util.createBuffer(msg.body); + if (asn1 === null) { + asn1 = forge.asn1.fromDer(der.bytes(), false); + } + var certBuffer = forge.util.createBuffer(); + writeVector(certBuffer, 3, der); + certList.putBuffer(certBuffer); + } + cert = forge.pki.certificateFromAsn1(asn1); + if (client) { + c.session.clientCertificate = cert; + } else { + c.session.serverCertificate = cert; + } + } catch (ex) { + return c.error(c, { + message: "Could not send certificate list.", + cause: ex, + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.bad_certificate + } + }); + } + } + var length = 3 + certList.length(); + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.certificate); + rval.putInt24(length); + writeVector(rval, 3, certList); + return rval; + }; + tls.createClientKeyExchange = function(c) { + var b = forge.util.createBuffer(); + b.putByte(c.session.clientHelloVersion.major); + b.putByte(c.session.clientHelloVersion.minor); + b.putBytes(forge.random.getBytes(46)); + var sp = c.session.sp; + sp.pre_master_secret = b.getBytes(); + var key2 = c.session.serverCertificate.publicKey; + b = key2.encrypt(sp.pre_master_secret); + var length = b.length + 2; + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.client_key_exchange); + rval.putInt24(length); + rval.putInt16(b.length); + rval.putBytes(b); + return rval; + }; + tls.createServerKeyExchange = function(c) { + var length = 0; + var rval = forge.util.createBuffer(); + if (length > 0) { + rval.putByte(tls.HandshakeType.server_key_exchange); + rval.putInt24(length); + } + return rval; + }; + tls.getClientSignature = function(c, callback) { + var b = forge.util.createBuffer(); + b.putBuffer(c.session.md5.digest()); + b.putBuffer(c.session.sha1.digest()); + b = b.getBytes(); + c.getSignature = c.getSignature || function(c2, b2, callback2) { + var privateKey = null; + if (c2.getPrivateKey) { + try { + privateKey = c2.getPrivateKey(c2, c2.session.clientCertificate); + privateKey = forge.pki.privateKeyFromPem(privateKey); + } catch (ex) { + c2.error(c2, { + message: "Could not get private key.", + cause: ex, + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } + } + if (privateKey === null) { + c2.error(c2, { + message: "No private key set.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } else { + b2 = privateKey.sign(b2, null); + } + callback2(c2, b2); + }; + c.getSignature(c, b, callback); + }; + tls.createCertificateVerify = function(c, signature) { + var length = signature.length + 2; + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.certificate_verify); + rval.putInt24(length); + rval.putInt16(signature.length); + rval.putBytes(signature); + return rval; + }; + tls.createCertificateRequest = function(c) { + var certTypes = forge.util.createBuffer(); + certTypes.putByte(1); + var cAs = forge.util.createBuffer(); + for (var key2 in c.caStore.certs) { + var cert = c.caStore.certs[key2]; + var dn = forge.pki.distinguishedNameToAsn1(cert.subject); + var byteBuffer = forge.asn1.toDer(dn); + cAs.putInt16(byteBuffer.length()); + cAs.putBuffer(byteBuffer); + } + var length = 1 + certTypes.length() + 2 + cAs.length(); + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.certificate_request); + rval.putInt24(length); + writeVector(rval, 1, certTypes); + writeVector(rval, 2, cAs); + return rval; + }; + tls.createServerHelloDone = function(c) { + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.server_hello_done); + rval.putInt24(0); + return rval; + }; + tls.createChangeCipherSpec = function() { + var rval = forge.util.createBuffer(); + rval.putByte(1); + return rval; + }; + tls.createFinished = function(c) { + var b = forge.util.createBuffer(); + b.putBuffer(c.session.md5.digest()); + b.putBuffer(c.session.sha1.digest()); + var client = c.entity === tls.ConnectionEnd.client; + var sp = c.session.sp; + var vdl = 12; + var prf = prf_TLS1; + var label = client ? "client finished" : "server finished"; + b = prf(sp.master_secret, label, b.getBytes(), vdl); + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.finished); + rval.putInt24(b.length()); + rval.putBuffer(b); + return rval; + }; + tls.createHeartbeat = function(type, payload, payloadLength) { + if (typeof payloadLength === "undefined") { + payloadLength = payload.length; + } + var rval = forge.util.createBuffer(); + rval.putByte(type); + rval.putInt16(payloadLength); + rval.putBytes(payload); + var plaintextLength = rval.length(); + var paddingLength = Math.max(16, plaintextLength - payloadLength - 3); + rval.putBytes(forge.random.getBytes(paddingLength)); + return rval; + }; + tls.queue = function(c, record) { + if (!record) { + return; + } + if (record.fragment.length() === 0) { + if (record.type === tls.ContentType.handshake || record.type === tls.ContentType.alert || record.type === tls.ContentType.change_cipher_spec) { + return; + } + } + if (record.type === tls.ContentType.handshake) { + var bytes = record.fragment.bytes(); + c.session.md5.update(bytes); + c.session.sha1.update(bytes); + bytes = null; + } + var records; + if (record.fragment.length() <= tls.MaxFragment) { + records = [record]; + } else { + records = []; + var data = record.fragment.bytes(); + while (data.length > tls.MaxFragment) { + records.push(tls.createRecord(c, { + type: record.type, + data: forge.util.createBuffer(data.slice(0, tls.MaxFragment)) + })); + data = data.slice(tls.MaxFragment); + } + if (data.length > 0) { + records.push(tls.createRecord(c, { + type: record.type, + data: forge.util.createBuffer(data) + })); + } + } + for (var i = 0; i < records.length && !c.fail; ++i) { + var rec = records[i]; + var s = c.state.current.write; + if (s.update(c, rec)) { + c.records.push(rec); + } + } + }; + tls.flush = function(c) { + for (var i = 0; i < c.records.length; ++i) { + var record = c.records[i]; + c.tlsData.putByte(record.type); + c.tlsData.putByte(record.version.major); + c.tlsData.putByte(record.version.minor); + c.tlsData.putInt16(record.fragment.length()); + c.tlsData.putBuffer(c.records[i].fragment); + } + c.records = []; + return c.tlsDataReady(c); + }; + var _certErrorToAlertDesc = function(error2) { + switch (error2) { + case true: + return true; + case forge.pki.certificateError.bad_certificate: + return tls.Alert.Description.bad_certificate; + case forge.pki.certificateError.unsupported_certificate: + return tls.Alert.Description.unsupported_certificate; + case forge.pki.certificateError.certificate_revoked: + return tls.Alert.Description.certificate_revoked; + case forge.pki.certificateError.certificate_expired: + return tls.Alert.Description.certificate_expired; + case forge.pki.certificateError.certificate_unknown: + return tls.Alert.Description.certificate_unknown; + case forge.pki.certificateError.unknown_ca: + return tls.Alert.Description.unknown_ca; + default: + return tls.Alert.Description.bad_certificate; + } + }; + var _alertDescToCertError = function(desc) { + switch (desc) { + case true: + return true; + case tls.Alert.Description.bad_certificate: + return forge.pki.certificateError.bad_certificate; + case tls.Alert.Description.unsupported_certificate: + return forge.pki.certificateError.unsupported_certificate; + case tls.Alert.Description.certificate_revoked: + return forge.pki.certificateError.certificate_revoked; + case tls.Alert.Description.certificate_expired: + return forge.pki.certificateError.certificate_expired; + case tls.Alert.Description.certificate_unknown: + return forge.pki.certificateError.certificate_unknown; + case tls.Alert.Description.unknown_ca: + return forge.pki.certificateError.unknown_ca; + default: + return forge.pki.certificateError.bad_certificate; + } + }; + tls.verifyCertificateChain = function(c, chain) { + try { + var options = {}; + for (var key2 in c.verifyOptions) { + options[key2] = c.verifyOptions[key2]; + } + options.verify = function(vfd, depth, chain2) { + var desc = _certErrorToAlertDesc(vfd); + var ret = c.verify(c, vfd, depth, chain2); + if (ret !== true) { + if (typeof ret === "object" && !forge.util.isArray(ret)) { + var error2 = new Error("The application rejected the certificate."); + error2.send = true; + error2.alert = { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.bad_certificate + }; + if (ret.message) { + error2.message = ret.message; + } + if (ret.alert) { + error2.alert.description = ret.alert; + } + throw error2; + } + if (ret !== vfd) { + ret = _alertDescToCertError(ret); + } + } + return ret; + }; + forge.pki.verifyCertificateChain(c.caStore, chain, options); + } catch (ex) { + var err = ex; + if (typeof err !== "object" || forge.util.isArray(err)) { + err = { + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: _certErrorToAlertDesc(ex) + } + }; + } + if (!("send" in err)) { + err.send = true; + } + if (!("alert" in err)) { + err.alert = { + level: tls.Alert.Level.fatal, + description: _certErrorToAlertDesc(err.error) + }; + } + c.error(c, err); + } + return !c.fail; + }; + tls.createSessionCache = function(cache, capacity) { + var rval = null; + if (cache && cache.getSession && cache.setSession && cache.order) { + rval = cache; + } else { + rval = {}; + rval.cache = cache || {}; + rval.capacity = Math.max(capacity || 100, 1); + rval.order = []; + for (var key2 in cache) { + if (rval.order.length <= capacity) { + rval.order.push(key2); + } else { + delete cache[key2]; + } + } + rval.getSession = function(sessionId) { + var session = null; + var key3 = null; + if (sessionId) { + key3 = forge.util.bytesToHex(sessionId); + } else if (rval.order.length > 0) { + key3 = rval.order[0]; + } + if (key3 !== null && key3 in rval.cache) { + session = rval.cache[key3]; + delete rval.cache[key3]; + for (var i in rval.order) { + if (rval.order[i] === key3) { + rval.order.splice(i, 1); + break; + } + } + } + return session; + }; + rval.setSession = function(sessionId, session) { + if (rval.order.length === rval.capacity) { + var key3 = rval.order.shift(); + delete rval.cache[key3]; + } + var key3 = forge.util.bytesToHex(sessionId); + rval.order.push(key3); + rval.cache[key3] = session; + }; + } + return rval; + }; + tls.createConnection = function(options) { + var caStore = null; + if (options.caStore) { + if (forge.util.isArray(options.caStore)) { + caStore = forge.pki.createCaStore(options.caStore); + } else { + caStore = options.caStore; + } + } else { + caStore = forge.pki.createCaStore(); + } + var cipherSuites = options.cipherSuites || null; + if (cipherSuites === null) { + cipherSuites = []; + for (var key2 in tls.CipherSuites) { + cipherSuites.push(tls.CipherSuites[key2]); + } + } + var entity = options.server || false ? tls.ConnectionEnd.server : tls.ConnectionEnd.client; + var sessionCache = options.sessionCache ? tls.createSessionCache(options.sessionCache) : null; + var c = { + version: { major: tls.Version.major, minor: tls.Version.minor }, + entity, + sessionId: options.sessionId, + caStore, + sessionCache, + cipherSuites, + connected: options.connected, + virtualHost: options.virtualHost || null, + verifyClient: options.verifyClient || false, + verify: options.verify || function(cn, vfd, dpth, cts) { + return vfd; + }, + verifyOptions: options.verifyOptions || {}, + getCertificate: options.getCertificate || null, + getPrivateKey: options.getPrivateKey || null, + getSignature: options.getSignature || null, + input: forge.util.createBuffer(), + tlsData: forge.util.createBuffer(), + data: forge.util.createBuffer(), + tlsDataReady: options.tlsDataReady, + dataReady: options.dataReady, + heartbeatReceived: options.heartbeatReceived, + closed: options.closed, + error: function(c2, ex) { + ex.origin = ex.origin || (c2.entity === tls.ConnectionEnd.client ? "client" : "server"); + if (ex.send) { + tls.queue(c2, tls.createAlert(c2, ex.alert)); + tls.flush(c2); + } + var fatal = ex.fatal !== false; + if (fatal) { + c2.fail = true; + } + options.error(c2, ex); + if (fatal) { + c2.close(false); + } + }, + deflate: options.deflate || null, + inflate: options.inflate || null + }; + c.reset = function(clearFail) { + c.version = { major: tls.Version.major, minor: tls.Version.minor }; + c.record = null; + c.session = null; + c.peerCertificate = null; + c.state = { + pending: null, + current: null + }; + c.expect = c.entity === tls.ConnectionEnd.client ? SHE : CHE; + c.fragmented = null; + c.records = []; + c.open = false; + c.handshakes = 0; + c.handshaking = false; + c.isConnected = false; + c.fail = !(clearFail || typeof clearFail === "undefined"); + c.input.clear(); + c.tlsData.clear(); + c.data.clear(); + c.state.current = tls.createConnectionState(c); + }; + c.reset(); + var _update = function(c2, record) { + var aligned = record.type - tls.ContentType.change_cipher_spec; + var handlers = ctTable[c2.entity][c2.expect]; + if (aligned in handlers) { + handlers[aligned](c2, record); + } else { + tls.handleUnexpected(c2, record); + } + }; + var _readRecordHeader = function(c2) { + var rval = 0; + var b = c2.input; + var len = b.length(); + if (len < 5) { + rval = 5 - len; + } else { + c2.record = { + type: b.getByte(), + version: { + major: b.getByte(), + minor: b.getByte() + }, + length: b.getInt16(), + fragment: forge.util.createBuffer(), + ready: false + }; + var compatibleVersion = c2.record.version.major === c2.version.major; + if (compatibleVersion && c2.session && c2.session.version) { + compatibleVersion = c2.record.version.minor === c2.version.minor; + } + if (!compatibleVersion) { + c2.error(c2, { + message: "Incompatible TLS version.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.protocol_version + } + }); + } + } + return rval; + }; + var _readRecord = function(c2) { + var rval = 0; + var b = c2.input; + var len = b.length(); + if (len < c2.record.length) { + rval = c2.record.length - len; + } else { + c2.record.fragment.putBytes(b.getBytes(c2.record.length)); + b.compact(); + var s = c2.state.current.read; + if (s.update(c2, c2.record)) { + if (c2.fragmented !== null) { + if (c2.fragmented.type === c2.record.type) { + c2.fragmented.fragment.putBuffer(c2.record.fragment); + c2.record = c2.fragmented; + } else { + c2.error(c2, { + message: "Invalid fragmented record.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.unexpected_message + } + }); + } + } + c2.record.ready = true; + } + } + return rval; + }; + c.handshake = function(sessionId) { + if (c.entity !== tls.ConnectionEnd.client) { + c.error(c, { + message: "Cannot initiate handshake as a server.", + fatal: false + }); + } else if (c.handshaking) { + c.error(c, { + message: "Handshake already in progress.", + fatal: false + }); + } else { + if (c.fail && !c.open && c.handshakes === 0) { + c.fail = false; + } + c.handshaking = true; + sessionId = sessionId || ""; + var session = null; + if (sessionId.length > 0) { + if (c.sessionCache) { + session = c.sessionCache.getSession(sessionId); + } + if (session === null) { + sessionId = ""; + } + } + if (sessionId.length === 0 && c.sessionCache) { + session = c.sessionCache.getSession(); + if (session !== null) { + sessionId = session.id; + } + } + c.session = { + id: sessionId, + version: null, + cipherSuite: null, + compressionMethod: null, + serverCertificate: null, + certificateRequest: null, + clientCertificate: null, + sp: {}, + md5: forge.md.md5.create(), + sha1: forge.md.sha1.create() + }; + if (session) { + c.version = session.version; + c.session.sp = session.sp; + } + c.session.sp.client_random = tls.createRandom().getBytes(); + c.open = true; + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createClientHello(c) + })); + tls.flush(c); + } + }; + c.process = function(data) { + var rval = 0; + if (data) { + c.input.putBytes(data); + } + if (!c.fail) { + if (c.record !== null && c.record.ready && c.record.fragment.isEmpty()) { + c.record = null; + } + if (c.record === null) { + rval = _readRecordHeader(c); + } + if (!c.fail && c.record !== null && !c.record.ready) { + rval = _readRecord(c); + } + if (!c.fail && c.record !== null && c.record.ready) { + _update(c, c.record); + } + } + return rval; + }; + c.prepare = function(data) { + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.application_data, + data: forge.util.createBuffer(data) + })); + return tls.flush(c); + }; + c.prepareHeartbeatRequest = function(payload, payloadLength) { + if (payload instanceof forge.util.ByteBuffer) { + payload = payload.bytes(); + } + if (typeof payloadLength === "undefined") { + payloadLength = payload.length; + } + c.expectedHeartbeatPayload = payload; + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.heartbeat, + data: tls.createHeartbeat( + tls.HeartbeatMessageType.heartbeat_request, + payload, + payloadLength + ) + })); + return tls.flush(c); + }; + c.close = function(clearFail) { + if (!c.fail && c.sessionCache && c.session) { + var session = { + id: c.session.id, + version: c.session.version, + sp: c.session.sp + }; + session.sp.keys = null; + c.sessionCache.setSession(session.id, session); + } + if (c.open) { + c.open = false; + c.input.clear(); + if (c.isConnected || c.handshaking) { + c.isConnected = c.handshaking = false; + tls.queue(c, tls.createAlert(c, { + level: tls.Alert.Level.warning, + description: tls.Alert.Description.close_notify + })); + tls.flush(c); + } + c.closed(c); + } + c.reset(clearFail); + }; + return c; + }; + module2.exports = forge.tls = forge.tls || {}; + for (key in tls) { + if (typeof tls[key] !== "function") { + forge.tls[key] = tls[key]; + } + } + var key; + forge.tls.prf_tls1 = prf_TLS1; + forge.tls.hmac_sha1 = hmac_sha1; + forge.tls.createSessionCache = tls.createSessionCache; + forge.tls.createConnection = tls.createConnection; + } +}); + +// node_modules/node-forge/lib/aesCipherSuites.js +var require_aesCipherSuites = __commonJS({ + "node_modules/node-forge/lib/aesCipherSuites.js"(exports2, module2) { + var forge = require_forge(); + require_aes(); + require_tls(); + var tls = module2.exports = forge.tls; + tls.CipherSuites["TLS_RSA_WITH_AES_128_CBC_SHA"] = { + id: [0, 47], + name: "TLS_RSA_WITH_AES_128_CBC_SHA", + initSecurityParameters: function(sp) { + sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes; + sp.cipher_type = tls.CipherType.block; + sp.enc_key_length = 16; + sp.block_length = 16; + sp.fixed_iv_length = 16; + sp.record_iv_length = 16; + sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1; + sp.mac_length = 20; + sp.mac_key_length = 20; + }, + initConnectionState + }; + tls.CipherSuites["TLS_RSA_WITH_AES_256_CBC_SHA"] = { + id: [0, 53], + name: "TLS_RSA_WITH_AES_256_CBC_SHA", + initSecurityParameters: function(sp) { + sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes; + sp.cipher_type = tls.CipherType.block; + sp.enc_key_length = 32; + sp.block_length = 16; + sp.fixed_iv_length = 16; + sp.record_iv_length = 16; + sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1; + sp.mac_length = 20; + sp.mac_key_length = 20; + }, + initConnectionState + }; + function initConnectionState(state, c, sp) { + var client = c.entity === forge.tls.ConnectionEnd.client; + state.read.cipherState = { + init: false, + cipher: forge.cipher.createDecipher("AES-CBC", client ? sp.keys.server_write_key : sp.keys.client_write_key), + iv: client ? sp.keys.server_write_IV : sp.keys.client_write_IV + }; + state.write.cipherState = { + init: false, + cipher: forge.cipher.createCipher("AES-CBC", client ? sp.keys.client_write_key : sp.keys.server_write_key), + iv: client ? sp.keys.client_write_IV : sp.keys.server_write_IV + }; + state.read.cipherFunction = decrypt_aes_cbc_sha1; + state.write.cipherFunction = encrypt_aes_cbc_sha1; + state.read.macLength = state.write.macLength = sp.mac_length; + state.read.macFunction = state.write.macFunction = tls.hmac_sha1; + } + function encrypt_aes_cbc_sha1(record, s) { + var rval = false; + var mac = s.macFunction(s.macKey, s.sequenceNumber, record); + record.fragment.putBytes(mac); + s.updateSequenceNumber(); + var iv; + if (record.version.minor === tls.Versions.TLS_1_0.minor) { + iv = s.cipherState.init ? null : s.cipherState.iv; + } else { + iv = forge.random.getBytesSync(16); + } + s.cipherState.init = true; + var cipher = s.cipherState.cipher; + cipher.start({ iv }); + if (record.version.minor >= tls.Versions.TLS_1_1.minor) { + cipher.output.putBytes(iv); + } + cipher.update(record.fragment); + if (cipher.finish(encrypt_aes_cbc_sha1_padding)) { + record.fragment = cipher.output; + record.length = record.fragment.length(); + rval = true; + } + return rval; + } + function encrypt_aes_cbc_sha1_padding(blockSize, input, decrypt) { + if (!decrypt) { + var padding = blockSize - input.length() % blockSize; + input.fillWithByte(padding - 1, padding); + } + return true; + } + function decrypt_aes_cbc_sha1_padding(blockSize, output, decrypt) { + var rval = true; + if (decrypt) { + var len = output.length(); + var paddingLength = output.last(); + for (var i = len - 1 - paddingLength; i < len - 1; ++i) { + rval = rval && output.at(i) == paddingLength; + } + if (rval) { + output.truncate(paddingLength + 1); + } + } + return rval; + } + function decrypt_aes_cbc_sha1(record, s) { + var rval = false; + var iv; + if (record.version.minor === tls.Versions.TLS_1_0.minor) { + iv = s.cipherState.init ? null : s.cipherState.iv; + } else { + iv = record.fragment.getBytes(16); + } + s.cipherState.init = true; + var cipher = s.cipherState.cipher; + cipher.start({ iv }); + cipher.update(record.fragment); + rval = cipher.finish(decrypt_aes_cbc_sha1_padding); + var macLen = s.macLength; + var mac = forge.random.getBytesSync(macLen); + var len = cipher.output.length(); + if (len >= macLen) { + record.fragment = cipher.output.getBytes(len - macLen); + mac = cipher.output.getBytes(macLen); + } else { + record.fragment = cipher.output.getBytes(); + } + record.fragment = forge.util.createBuffer(record.fragment); + record.length = record.fragment.length(); + var mac2 = s.macFunction(s.macKey, s.sequenceNumber, record); + s.updateSequenceNumber(); + rval = compareMacs(s.macKey, mac, mac2) && rval; + return rval; + } + function compareMacs(key, mac1, mac2) { + var hmac = forge.hmac.create(); + hmac.start("SHA1", key); + hmac.update(mac1); + mac1 = hmac.digest().getBytes(); + hmac.start(null, null); + hmac.update(mac2); + mac2 = hmac.digest().getBytes(); + return mac1 === mac2; + } + } +}); + +// node_modules/node-forge/lib/sha512.js +var require_sha512 = __commonJS({ + "node_modules/node-forge/lib/sha512.js"(exports2, module2) { + var forge = require_forge(); + require_md(); + require_util13(); + var sha512 = module2.exports = forge.sha512 = forge.sha512 || {}; + forge.md.sha512 = forge.md.algorithms.sha512 = sha512; + var sha384 = forge.sha384 = forge.sha512.sha384 = forge.sha512.sha384 || {}; + sha384.create = function() { + return sha512.create("SHA-384"); + }; + forge.md.sha384 = forge.md.algorithms.sha384 = sha384; + forge.sha512.sha256 = forge.sha512.sha256 || { + create: function() { + return sha512.create("SHA-512/256"); + } + }; + forge.md["sha512/256"] = forge.md.algorithms["sha512/256"] = forge.sha512.sha256; + forge.sha512.sha224 = forge.sha512.sha224 || { + create: function() { + return sha512.create("SHA-512/224"); + } + }; + forge.md["sha512/224"] = forge.md.algorithms["sha512/224"] = forge.sha512.sha224; + sha512.create = function(algorithm) { + if (!_initialized) { + _init(); + } + if (typeof algorithm === "undefined") { + algorithm = "SHA-512"; + } + if (!(algorithm in _states)) { + throw new Error("Invalid SHA-512 algorithm: " + algorithm); + } + var _state = _states[algorithm]; + var _h = null; + var _input = forge.util.createBuffer(); + var _w = new Array(80); + for (var wi = 0; wi < 80; ++wi) { + _w[wi] = new Array(2); + } + var digestLength = 64; + switch (algorithm) { + case "SHA-384": + digestLength = 48; + break; + case "SHA-512/256": + digestLength = 32; + break; + case "SHA-512/224": + digestLength = 28; + break; + } + var md2 = { + // SHA-512 => sha512 + algorithm: algorithm.replace("-", "").toLowerCase(), + blockLength: 128, + digestLength, + // 56-bit length of message so far (does not including padding) + messageLength: 0, + // true message length + fullMessageLength: null, + // size of message length in bytes + messageLengthSize: 16 + }; + md2.start = function() { + md2.messageLength = 0; + md2.fullMessageLength = md2.messageLength128 = []; + var int32s = md2.messageLengthSize / 4; + for (var i = 0; i < int32s; ++i) { + md2.fullMessageLength.push(0); + } + _input = forge.util.createBuffer(); + _h = new Array(_state.length); + for (var i = 0; i < _state.length; ++i) { + _h[i] = _state[i].slice(0); + } + return md2; + }; + md2.start(); + md2.update = function(msg, encoding) { + if (encoding === "utf8") { + msg = forge.util.encodeUtf8(msg); + } + var len = msg.length; + md2.messageLength += len; + len = [len / 4294967296 >>> 0, len >>> 0]; + for (var i = md2.fullMessageLength.length - 1; i >= 0; --i) { + md2.fullMessageLength[i] += len[1]; + len[1] = len[0] + (md2.fullMessageLength[i] / 4294967296 >>> 0); + md2.fullMessageLength[i] = md2.fullMessageLength[i] >>> 0; + len[0] = len[1] / 4294967296 >>> 0; + } + _input.putBytes(msg); + _update(_h, _w, _input); + if (_input.read > 2048 || _input.length() === 0) { + _input.compact(); + } + return md2; + }; + md2.digest = function() { + var finalBlock = forge.util.createBuffer(); + finalBlock.putBytes(_input.bytes()); + var remaining = md2.fullMessageLength[md2.fullMessageLength.length - 1] + md2.messageLengthSize; + var overflow = remaining & md2.blockLength - 1; + finalBlock.putBytes(_padding.substr(0, md2.blockLength - overflow)); + var next, carry; + var bits = md2.fullMessageLength[0] * 8; + for (var i = 0; i < md2.fullMessageLength.length - 1; ++i) { + next = md2.fullMessageLength[i + 1] * 8; + carry = next / 4294967296 >>> 0; + bits += carry; + finalBlock.putInt32(bits >>> 0); + bits = next >>> 0; + } + finalBlock.putInt32(bits); + var h = new Array(_h.length); + for (var i = 0; i < _h.length; ++i) { + h[i] = _h[i].slice(0); + } + _update(h, _w, finalBlock); + var rval = forge.util.createBuffer(); + var hlen; + if (algorithm === "SHA-512") { + hlen = h.length; + } else if (algorithm === "SHA-384") { + hlen = h.length - 2; + } else { + hlen = h.length - 4; + } + for (var i = 0; i < hlen; ++i) { + rval.putInt32(h[i][0]); + if (i !== hlen - 1 || algorithm !== "SHA-512/224") { + rval.putInt32(h[i][1]); + } + } + return rval; + }; + return md2; + }; + var _padding = null; + var _initialized = false; + var _k = null; + var _states = null; + function _init() { + _padding = String.fromCharCode(128); + _padding += forge.util.fillString(String.fromCharCode(0), 128); + _k = [ + [1116352408, 3609767458], + [1899447441, 602891725], + [3049323471, 3964484399], + [3921009573, 2173295548], + [961987163, 4081628472], + [1508970993, 3053834265], + [2453635748, 2937671579], + [2870763221, 3664609560], + [3624381080, 2734883394], + [310598401, 1164996542], + [607225278, 1323610764], + [1426881987, 3590304994], + [1925078388, 4068182383], + [2162078206, 991336113], + [2614888103, 633803317], + [3248222580, 3479774868], + [3835390401, 2666613458], + [4022224774, 944711139], + [264347078, 2341262773], + [604807628, 2007800933], + [770255983, 1495990901], + [1249150122, 1856431235], + [1555081692, 3175218132], + [1996064986, 2198950837], + [2554220882, 3999719339], + [2821834349, 766784016], + [2952996808, 2566594879], + [3210313671, 3203337956], + [3336571891, 1034457026], + [3584528711, 2466948901], + [113926993, 3758326383], + [338241895, 168717936], + [666307205, 1188179964], + [773529912, 1546045734], + [1294757372, 1522805485], + [1396182291, 2643833823], + [1695183700, 2343527390], + [1986661051, 1014477480], + [2177026350, 1206759142], + [2456956037, 344077627], + [2730485921, 1290863460], + [2820302411, 3158454273], + [3259730800, 3505952657], + [3345764771, 106217008], + [3516065817, 3606008344], + [3600352804, 1432725776], + [4094571909, 1467031594], + [275423344, 851169720], + [430227734, 3100823752], + [506948616, 1363258195], + [659060556, 3750685593], + [883997877, 3785050280], + [958139571, 3318307427], + [1322822218, 3812723403], + [1537002063, 2003034995], + [1747873779, 3602036899], + [1955562222, 1575990012], + [2024104815, 1125592928], + [2227730452, 2716904306], + [2361852424, 442776044], + [2428436474, 593698344], + [2756734187, 3733110249], + [3204031479, 2999351573], + [3329325298, 3815920427], + [3391569614, 3928383900], + [3515267271, 566280711], + [3940187606, 3454069534], + [4118630271, 4000239992], + [116418474, 1914138554], + [174292421, 2731055270], + [289380356, 3203993006], + [460393269, 320620315], + [685471733, 587496836], + [852142971, 1086792851], + [1017036298, 365543100], + [1126000580, 2618297676], + [1288033470, 3409855158], + [1501505948, 4234509866], + [1607167915, 987167468], + [1816402316, 1246189591] + ]; + _states = {}; + _states["SHA-512"] = [ + [1779033703, 4089235720], + [3144134277, 2227873595], + [1013904242, 4271175723], + [2773480762, 1595750129], + [1359893119, 2917565137], + [2600822924, 725511199], + [528734635, 4215389547], + [1541459225, 327033209] + ]; + _states["SHA-384"] = [ + [3418070365, 3238371032], + [1654270250, 914150663], + [2438529370, 812702999], + [355462360, 4144912697], + [1731405415, 4290775857], + [2394180231, 1750603025], + [3675008525, 1694076839], + [1203062813, 3204075428] + ]; + _states["SHA-512/256"] = [ + [573645204, 4230739756], + [2673172387, 3360449730], + [596883563, 1867755857], + [2520282905, 1497426621], + [2519219938, 2827943907], + [3193839141, 1401305490], + [721525244, 746961066], + [246885852, 2177182882] + ]; + _states["SHA-512/224"] = [ + [2352822216, 424955298], + [1944164710, 2312950998], + [502970286, 855612546], + [1738396948, 1479516111], + [258812777, 2077511080], + [2011393907, 79989058], + [1067287976, 1780299464], + [286451373, 2446758561] + ]; + _initialized = true; + } + function _update(s, w, bytes) { + var t1_hi, t1_lo; + var t2_hi, t2_lo; + var s0_hi, s0_lo; + var s1_hi, s1_lo; + var ch_hi, ch_lo; + var maj_hi, maj_lo; + var a_hi, a_lo; + var b_hi, b_lo; + var c_hi, c_lo; + var d_hi, d_lo; + var e_hi, e_lo; + var f_hi, f_lo; + var g_hi, g_lo; + var h_hi, h_lo; + var i, hi, lo, w2, w7, w15, w16; + var len = bytes.length(); + while (len >= 128) { + for (i = 0; i < 16; ++i) { + w[i][0] = bytes.getInt32() >>> 0; + w[i][1] = bytes.getInt32() >>> 0; + } + for (; i < 80; ++i) { + w2 = w[i - 2]; + hi = w2[0]; + lo = w2[1]; + t1_hi = ((hi >>> 19 | lo << 13) ^ // ROTR 19 + (lo >>> 29 | hi << 3) ^ // ROTR 61/(swap + ROTR 29) + hi >>> 6) >>> 0; + t1_lo = ((hi << 13 | lo >>> 19) ^ // ROTR 19 + (lo << 3 | hi >>> 29) ^ // ROTR 61/(swap + ROTR 29) + (hi << 26 | lo >>> 6)) >>> 0; + w15 = w[i - 15]; + hi = w15[0]; + lo = w15[1]; + t2_hi = ((hi >>> 1 | lo << 31) ^ // ROTR 1 + (hi >>> 8 | lo << 24) ^ // ROTR 8 + hi >>> 7) >>> 0; + t2_lo = ((hi << 31 | lo >>> 1) ^ // ROTR 1 + (hi << 24 | lo >>> 8) ^ // ROTR 8 + (hi << 25 | lo >>> 7)) >>> 0; + w7 = w[i - 7]; + w16 = w[i - 16]; + lo = t1_lo + w7[1] + t2_lo + w16[1]; + w[i][0] = t1_hi + w7[0] + t2_hi + w16[0] + (lo / 4294967296 >>> 0) >>> 0; + w[i][1] = lo >>> 0; + } + a_hi = s[0][0]; + a_lo = s[0][1]; + b_hi = s[1][0]; + b_lo = s[1][1]; + c_hi = s[2][0]; + c_lo = s[2][1]; + d_hi = s[3][0]; + d_lo = s[3][1]; + e_hi = s[4][0]; + e_lo = s[4][1]; + f_hi = s[5][0]; + f_lo = s[5][1]; + g_hi = s[6][0]; + g_lo = s[6][1]; + h_hi = s[7][0]; + h_lo = s[7][1]; + for (i = 0; i < 80; ++i) { + s1_hi = ((e_hi >>> 14 | e_lo << 18) ^ // ROTR 14 + (e_hi >>> 18 | e_lo << 14) ^ // ROTR 18 + (e_lo >>> 9 | e_hi << 23)) >>> 0; + s1_lo = ((e_hi << 18 | e_lo >>> 14) ^ // ROTR 14 + (e_hi << 14 | e_lo >>> 18) ^ // ROTR 18 + (e_lo << 23 | e_hi >>> 9)) >>> 0; + ch_hi = (g_hi ^ e_hi & (f_hi ^ g_hi)) >>> 0; + ch_lo = (g_lo ^ e_lo & (f_lo ^ g_lo)) >>> 0; + s0_hi = ((a_hi >>> 28 | a_lo << 4) ^ // ROTR 28 + (a_lo >>> 2 | a_hi << 30) ^ // ROTR 34/(swap + ROTR 2) + (a_lo >>> 7 | a_hi << 25)) >>> 0; + s0_lo = ((a_hi << 4 | a_lo >>> 28) ^ // ROTR 28 + (a_lo << 30 | a_hi >>> 2) ^ // ROTR 34/(swap + ROTR 2) + (a_lo << 25 | a_hi >>> 7)) >>> 0; + maj_hi = (a_hi & b_hi | c_hi & (a_hi ^ b_hi)) >>> 0; + maj_lo = (a_lo & b_lo | c_lo & (a_lo ^ b_lo)) >>> 0; + lo = h_lo + s1_lo + ch_lo + _k[i][1] + w[i][1]; + t1_hi = h_hi + s1_hi + ch_hi + _k[i][0] + w[i][0] + (lo / 4294967296 >>> 0) >>> 0; + t1_lo = lo >>> 0; + lo = s0_lo + maj_lo; + t2_hi = s0_hi + maj_hi + (lo / 4294967296 >>> 0) >>> 0; + t2_lo = lo >>> 0; + h_hi = g_hi; + h_lo = g_lo; + g_hi = f_hi; + g_lo = f_lo; + f_hi = e_hi; + f_lo = e_lo; + lo = d_lo + t1_lo; + e_hi = d_hi + t1_hi + (lo / 4294967296 >>> 0) >>> 0; + e_lo = lo >>> 0; + d_hi = c_hi; + d_lo = c_lo; + c_hi = b_hi; + c_lo = b_lo; + b_hi = a_hi; + b_lo = a_lo; + lo = t1_lo + t2_lo; + a_hi = t1_hi + t2_hi + (lo / 4294967296 >>> 0) >>> 0; + a_lo = lo >>> 0; + } + lo = s[0][1] + a_lo; + s[0][0] = s[0][0] + a_hi + (lo / 4294967296 >>> 0) >>> 0; + s[0][1] = lo >>> 0; + lo = s[1][1] + b_lo; + s[1][0] = s[1][0] + b_hi + (lo / 4294967296 >>> 0) >>> 0; + s[1][1] = lo >>> 0; + lo = s[2][1] + c_lo; + s[2][0] = s[2][0] + c_hi + (lo / 4294967296 >>> 0) >>> 0; + s[2][1] = lo >>> 0; + lo = s[3][1] + d_lo; + s[3][0] = s[3][0] + d_hi + (lo / 4294967296 >>> 0) >>> 0; + s[3][1] = lo >>> 0; + lo = s[4][1] + e_lo; + s[4][0] = s[4][0] + e_hi + (lo / 4294967296 >>> 0) >>> 0; + s[4][1] = lo >>> 0; + lo = s[5][1] + f_lo; + s[5][0] = s[5][0] + f_hi + (lo / 4294967296 >>> 0) >>> 0; + s[5][1] = lo >>> 0; + lo = s[6][1] + g_lo; + s[6][0] = s[6][0] + g_hi + (lo / 4294967296 >>> 0) >>> 0; + s[6][1] = lo >>> 0; + lo = s[7][1] + h_lo; + s[7][0] = s[7][0] + h_hi + (lo / 4294967296 >>> 0) >>> 0; + s[7][1] = lo >>> 0; + len -= 128; + } + } + } +}); + +// node_modules/node-forge/lib/asn1-validator.js +var require_asn1_validator = __commonJS({ + "node_modules/node-forge/lib/asn1-validator.js"(exports2) { + var forge = require_forge(); + require_asn1(); + var asn1 = forge.asn1; + exports2.privateKeyValidator = { + // PrivateKeyInfo + name: "PrivateKeyInfo", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + // Version (INTEGER) + name: "PrivateKeyInfo.version", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "privateKeyVersion" + }, { + // privateKeyAlgorithm + name: "PrivateKeyInfo.privateKeyAlgorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "AlgorithmIdentifier.algorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "privateKeyOid" + }] + }, { + // PrivateKey + name: "PrivateKeyInfo", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: "privateKey" + }] + }; + exports2.publicKeyValidator = { + name: "SubjectPublicKeyInfo", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: "subjectPublicKeyInfo", + value: [ + { + name: "SubjectPublicKeyInfo.AlgorithmIdentifier", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "AlgorithmIdentifier.algorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "publicKeyOid" + }] + }, + // capture group for ed25519PublicKey + { + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + composed: true, + captureBitStringValue: "ed25519PublicKey" + } + // FIXME: this is capture group for rsaPublicKey, use it in this API or + // discard? + /* { + // subjectPublicKey + name: 'SubjectPublicKeyInfo.subjectPublicKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + value: [{ + // RSAPublicKey + name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + optional: true, + captureAsn1: 'rsaPublicKey' + }] + } */ + ] + }; + } +}); + +// node_modules/node-forge/lib/ed25519.js +var require_ed25519 = __commonJS({ + "node_modules/node-forge/lib/ed25519.js"(exports2, module2) { + var forge = require_forge(); + require_jsbn(); + require_random(); + require_sha512(); + require_util13(); + var asn1Validator = require_asn1_validator(); + var publicKeyValidator = asn1Validator.publicKeyValidator; + var privateKeyValidator = asn1Validator.privateKeyValidator; + if (typeof BigInteger === "undefined") { + BigInteger = forge.jsbn.BigInteger; + } + var BigInteger; + var ByteBuffer = forge.util.ByteBuffer; + var NativeBuffer = typeof Buffer === "undefined" ? Uint8Array : Buffer; + forge.pki = forge.pki || {}; + module2.exports = forge.pki.ed25519 = forge.ed25519 = forge.ed25519 || {}; + var ed25519 = forge.ed25519; + ed25519.constants = {}; + ed25519.constants.PUBLIC_KEY_BYTE_LENGTH = 32; + ed25519.constants.PRIVATE_KEY_BYTE_LENGTH = 64; + ed25519.constants.SEED_BYTE_LENGTH = 32; + ed25519.constants.SIGN_BYTE_LENGTH = 64; + ed25519.constants.HASH_BYTE_LENGTH = 64; + ed25519.generateKeyPair = function(options) { + options = options || {}; + var seed = options.seed; + if (seed === void 0) { + seed = forge.random.getBytesSync(ed25519.constants.SEED_BYTE_LENGTH); + } else if (typeof seed === "string") { + if (seed.length !== ed25519.constants.SEED_BYTE_LENGTH) { + throw new TypeError( + '"seed" must be ' + ed25519.constants.SEED_BYTE_LENGTH + " bytes in length." + ); + } + } else if (!(seed instanceof Uint8Array)) { + throw new TypeError( + '"seed" must be a node.js Buffer, Uint8Array, or a binary string.' + ); + } + seed = messageToNativeBuffer({ message: seed, encoding: "binary" }); + var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); + var sk = new NativeBuffer(ed25519.constants.PRIVATE_KEY_BYTE_LENGTH); + for (var i = 0; i < 32; ++i) { + sk[i] = seed[i]; + } + crypto_sign_keypair(pk, sk); + return { publicKey: pk, privateKey: sk }; + }; + ed25519.privateKeyFromAsn1 = function(obj) { + var capture = {}; + var errors = []; + var valid = forge.asn1.validate(obj, privateKeyValidator, capture, errors); + if (!valid) { + var error2 = new Error("Invalid Key."); + error2.errors = errors; + throw error2; + } + var oid = forge.asn1.derToOid(capture.privateKeyOid); + var ed25519Oid = forge.oids.EdDSA25519; + if (oid !== ed25519Oid) { + throw new Error('Invalid OID "' + oid + '"; OID must be "' + ed25519Oid + '".'); + } + var privateKey = capture.privateKey; + var privateKeyBytes = messageToNativeBuffer({ + message: forge.asn1.fromDer(privateKey).value, + encoding: "binary" + }); + return { privateKeyBytes }; + }; + ed25519.publicKeyFromAsn1 = function(obj) { + var capture = {}; + var errors = []; + var valid = forge.asn1.validate(obj, publicKeyValidator, capture, errors); + if (!valid) { + var error2 = new Error("Invalid Key."); + error2.errors = errors; + throw error2; + } + var oid = forge.asn1.derToOid(capture.publicKeyOid); + var ed25519Oid = forge.oids.EdDSA25519; + if (oid !== ed25519Oid) { + throw new Error('Invalid OID "' + oid + '"; OID must be "' + ed25519Oid + '".'); + } + var publicKeyBytes = capture.ed25519PublicKey; + if (publicKeyBytes.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) { + throw new Error("Key length is invalid."); + } + return messageToNativeBuffer({ + message: publicKeyBytes, + encoding: "binary" + }); + }; + ed25519.publicKeyFromPrivateKey = function(options) { + options = options || {}; + var privateKey = messageToNativeBuffer({ + message: options.privateKey, + encoding: "binary" + }); + if (privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) { + throw new TypeError( + '"options.privateKey" must have a byte length of ' + ed25519.constants.PRIVATE_KEY_BYTE_LENGTH + ); + } + var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); + for (var i = 0; i < pk.length; ++i) { + pk[i] = privateKey[32 + i]; + } + return pk; + }; + ed25519.sign = function(options) { + options = options || {}; + var msg = messageToNativeBuffer(options); + var privateKey = messageToNativeBuffer({ + message: options.privateKey, + encoding: "binary" + }); + if (privateKey.length === ed25519.constants.SEED_BYTE_LENGTH) { + var keyPair = ed25519.generateKeyPair({ seed: privateKey }); + privateKey = keyPair.privateKey; + } else if (privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) { + throw new TypeError( + '"options.privateKey" must have a byte length of ' + ed25519.constants.SEED_BYTE_LENGTH + " or " + ed25519.constants.PRIVATE_KEY_BYTE_LENGTH + ); + } + var signedMsg = new NativeBuffer( + ed25519.constants.SIGN_BYTE_LENGTH + msg.length + ); + crypto_sign(signedMsg, msg, msg.length, privateKey); + var sig = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH); + for (var i = 0; i < sig.length; ++i) { + sig[i] = signedMsg[i]; + } + return sig; + }; + ed25519.verify = function(options) { + options = options || {}; + var msg = messageToNativeBuffer(options); + if (options.signature === void 0) { + throw new TypeError( + '"options.signature" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a binary string.' + ); + } + var sig = messageToNativeBuffer({ + message: options.signature, + encoding: "binary" + }); + if (sig.length !== ed25519.constants.SIGN_BYTE_LENGTH) { + throw new TypeError( + '"options.signature" must have a byte length of ' + ed25519.constants.SIGN_BYTE_LENGTH + ); + } + var publicKey = messageToNativeBuffer({ + message: options.publicKey, + encoding: "binary" + }); + if (publicKey.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) { + throw new TypeError( + '"options.publicKey" must have a byte length of ' + ed25519.constants.PUBLIC_KEY_BYTE_LENGTH + ); + } + var sm = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length); + var m = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length); + var i; + for (i = 0; i < ed25519.constants.SIGN_BYTE_LENGTH; ++i) { + sm[i] = sig[i]; + } + for (i = 0; i < msg.length; ++i) { + sm[i + ed25519.constants.SIGN_BYTE_LENGTH] = msg[i]; + } + return crypto_sign_open(m, sm, sm.length, publicKey) >= 0; + }; + function messageToNativeBuffer(options) { + var message = options.message; + if (message instanceof Uint8Array || message instanceof NativeBuffer) { + return message; + } + var encoding = options.encoding; + if (message === void 0) { + if (options.md) { + message = options.md.digest().getBytes(); + encoding = "binary"; + } else { + throw new TypeError('"options.message" or "options.md" not specified.'); + } + } + if (typeof message === "string" && !encoding) { + throw new TypeError('"options.encoding" must be "binary" or "utf8".'); + } + if (typeof message === "string") { + if (typeof Buffer !== "undefined") { + return Buffer.from(message, encoding); + } + message = new ByteBuffer(message, encoding); + } else if (!(message instanceof ByteBuffer)) { + throw new TypeError( + '"options.message" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a string with "options.encoding" specifying its encoding.' + ); + } + var buffer = new NativeBuffer(message.length()); + for (var i = 0; i < buffer.length; ++i) { + buffer[i] = message.at(i); + } + return buffer; + } + var gf0 = gf(); + var gf1 = gf([1]); + var D = gf([ + 30883, + 4953, + 19914, + 30187, + 55467, + 16705, + 2637, + 112, + 59544, + 30585, + 16505, + 36039, + 65139, + 11119, + 27886, + 20995 + ]); + var D2 = gf([ + 61785, + 9906, + 39828, + 60374, + 45398, + 33411, + 5274, + 224, + 53552, + 61171, + 33010, + 6542, + 64743, + 22239, + 55772, + 9222 + ]); + var X = gf([ + 54554, + 36645, + 11616, + 51542, + 42930, + 38181, + 51040, + 26924, + 56412, + 64982, + 57905, + 49316, + 21502, + 52590, + 14035, + 8553 + ]); + var Y = gf([ + 26200, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214 + ]); + var L = new Float64Array([ + 237, + 211, + 245, + 92, + 26, + 99, + 18, + 88, + 214, + 156, + 247, + 162, + 222, + 249, + 222, + 20, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 16 + ]); + var I = gf([ + 41136, + 18958, + 6951, + 50414, + 58488, + 44335, + 6150, + 12099, + 55207, + 15867, + 153, + 11085, + 57099, + 20417, + 9344, + 11139 + ]); + function sha512(msg, msgLen) { + var md2 = forge.md.sha512.create(); + var buffer = new ByteBuffer(msg); + md2.update(buffer.getBytes(msgLen), "binary"); + var hash = md2.digest().getBytes(); + if (typeof Buffer !== "undefined") { + return Buffer.from(hash, "binary"); + } + var out = new NativeBuffer(ed25519.constants.HASH_BYTE_LENGTH); + for (var i = 0; i < 64; ++i) { + out[i] = hash.charCodeAt(i); + } + return out; + } + function crypto_sign_keypair(pk, sk) { + var p = [gf(), gf(), gf(), gf()]; + var i; + var d = sha512(sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + scalarbase(p, d); + pack2(pk, p); + for (i = 0; i < 32; ++i) { + sk[i + 32] = pk[i]; + } + return 0; + } + function crypto_sign(sm, m, n, sk) { + var i, j, x = new Float64Array(64); + var p = [gf(), gf(), gf(), gf()]; + var d = sha512(sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + var smlen = n + 64; + for (i = 0; i < n; ++i) { + sm[64 + i] = m[i]; + } + for (i = 0; i < 32; ++i) { + sm[32 + i] = d[32 + i]; + } + var r = sha512(sm.subarray(32), n + 32); + reduce(r); + scalarbase(p, r); + pack2(sm, p); + for (i = 32; i < 64; ++i) { + sm[i] = sk[i]; + } + var h = sha512(sm, n + 64); + reduce(h); + for (i = 32; i < 64; ++i) { + x[i] = 0; + } + for (i = 0; i < 32; ++i) { + x[i] = r[i]; + } + for (i = 0; i < 32; ++i) { + for (j = 0; j < 32; j++) { + x[i + j] += h[i] * d[j]; + } + } + modL(sm.subarray(32), x); + return smlen; + } + function crypto_sign_open(m, sm, n, pk) { + var i, mlen; + var t = new NativeBuffer(32); + var p = [gf(), gf(), gf(), gf()], q = [gf(), gf(), gf(), gf()]; + mlen = -1; + if (n < 64) { + return -1; + } + if (unpackneg(q, pk)) { + return -1; + } + if (!_isCanonicalSignatureScalar(sm, 32)) { + return -1; + } + for (i = 0; i < n; ++i) { + m[i] = sm[i]; + } + for (i = 0; i < 32; ++i) { + m[i + 32] = pk[i]; + } + var h = sha512(m, n); + reduce(h); + scalarmult(p, q, h); + scalarbase(q, sm.subarray(32)); + add(p, q); + pack2(t, p); + n -= 64; + if (crypto_verify_32(sm, 0, t, 0)) { + for (i = 0; i < n; ++i) { + m[i] = 0; + } + return -1; + } + for (i = 0; i < n; ++i) { + m[i] = sm[i + 64]; + } + mlen = n; + return mlen; + } + function _isCanonicalSignatureScalar(bytes, offset) { + var i; + for (i = 31; i >= 0; --i) { + if (bytes[offset + i] < L[i]) { + return true; + } + if (bytes[offset + i] > L[i]) { + return false; + } + } + return false; + } + function modL(r, x) { + var carry, i, j, k; + for (i = 63; i >= 32; --i) { + carry = 0; + for (j = i - 32, k = i - 12; j < k; ++j) { + x[j] += carry - 16 * x[i] * L[j - (i - 32)]; + carry = x[j] + 128 >> 8; + x[j] -= carry * 256; + } + x[j] += carry; + x[i] = 0; + } + carry = 0; + for (j = 0; j < 32; ++j) { + x[j] += carry - (x[31] >> 4) * L[j]; + carry = x[j] >> 8; + x[j] &= 255; + } + for (j = 0; j < 32; ++j) { + x[j] -= carry * L[j]; + } + for (i = 0; i < 32; ++i) { + x[i + 1] += x[i] >> 8; + r[i] = x[i] & 255; + } + } + function reduce(r) { + var x = new Float64Array(64); + for (var i = 0; i < 64; ++i) { + x[i] = r[i]; + r[i] = 0; + } + modL(r, x); + } + function add(p, q) { + var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(), g = gf(), h = gf(), t = gf(); + Z(a, p[1], p[0]); + Z(t, q[1], q[0]); + M(a, a, t); + A(b, p[0], p[1]); + A(t, q[0], q[1]); + M(b, b, t); + M(c, p[3], q[3]); + M(c, c, D2); + M(d, p[2], q[2]); + A(d, d, d); + Z(e, b, a); + Z(f, d, c); + A(g, d, c); + A(h, b, a); + M(p[0], e, f); + M(p[1], h, g); + M(p[2], g, f); + M(p[3], e, h); + } + function cswap(p, q, b) { + for (var i = 0; i < 4; ++i) { + sel25519(p[i], q[i], b); + } + } + function pack2(r, p) { + var tx = gf(), ty = gf(), zi = gf(); + inv25519(zi, p[2]); + M(tx, p[0], zi); + M(ty, p[1], zi); + pack25519(r, ty); + r[31] ^= par25519(tx) << 7; + } + function pack25519(o, n) { + var i, j, b; + var m = gf(), t = gf(); + for (i = 0; i < 16; ++i) { + t[i] = n[i]; + } + car25519(t); + car25519(t); + car25519(t); + for (j = 0; j < 2; ++j) { + m[0] = t[0] - 65517; + for (i = 1; i < 15; ++i) { + m[i] = t[i] - 65535 - (m[i - 1] >> 16 & 1); + m[i - 1] &= 65535; + } + m[15] = t[15] - 32767 - (m[14] >> 16 & 1); + b = m[15] >> 16 & 1; + m[14] &= 65535; + sel25519(t, m, 1 - b); + } + for (i = 0; i < 16; i++) { + o[2 * i] = t[i] & 255; + o[2 * i + 1] = t[i] >> 8; + } + } + function unpackneg(r, p) { + var t = gf(), chk = gf(), num = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf(); + set25519(r[2], gf1); + unpack25519(r[1], p); + S(num, r[1]); + M(den, num, D); + Z(num, num, r[2]); + A(den, r[2], den); + S(den2, den); + S(den4, den2); + M(den6, den4, den2); + M(t, den6, num); + M(t, t, den); + pow2523(t, t); + M(t, t, num); + M(t, t, den); + M(t, t, den); + M(r[0], t, den); + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) { + M(r[0], r[0], I); + } + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) { + return -1; + } + if (par25519(r[0]) === p[31] >> 7) { + Z(r[0], gf0, r[0]); + } + M(r[3], r[0], r[1]); + return 0; + } + function unpack25519(o, n) { + var i; + for (i = 0; i < 16; ++i) { + o[i] = n[2 * i] + (n[2 * i + 1] << 8); + } + o[15] &= 32767; + } + function pow2523(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; ++a) { + c[a] = i[a]; + } + for (a = 250; a >= 0; --a) { + S(c, c); + if (a !== 1) { + M(c, c, i); + } + } + for (a = 0; a < 16; ++a) { + o[a] = c[a]; + } + } + function neq25519(a, b) { + var c = new NativeBuffer(32); + var d = new NativeBuffer(32); + pack25519(c, a); + pack25519(d, b); + return crypto_verify_32(c, 0, d, 0); + } + function crypto_verify_32(x, xi, y, yi) { + return vn(x, xi, y, yi, 32); + } + function vn(x, xi, y, yi, n) { + var i, d = 0; + for (i = 0; i < n; ++i) { + d |= x[xi + i] ^ y[yi + i]; + } + return (1 & d - 1 >>> 8) - 1; + } + function par25519(a) { + var d = new NativeBuffer(32); + pack25519(d, a); + return d[0] & 1; + } + function scalarmult(p, q, s) { + var b, i; + set25519(p[0], gf0); + set25519(p[1], gf1); + set25519(p[2], gf1); + set25519(p[3], gf0); + for (i = 255; i >= 0; --i) { + b = s[i / 8 | 0] >> (i & 7) & 1; + cswap(p, q, b); + add(q, p); + add(p, p); + cswap(p, q, b); + } + } + function scalarbase(p, s) { + var q = [gf(), gf(), gf(), gf()]; + set25519(q[0], X); + set25519(q[1], Y); + set25519(q[2], gf1); + M(q[3], X, Y); + scalarmult(p, q, s); + } + function set25519(r, a) { + var i; + for (i = 0; i < 16; i++) { + r[i] = a[i] | 0; + } + } + function inv25519(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; ++a) { + c[a] = i[a]; + } + for (a = 253; a >= 0; --a) { + S(c, c); + if (a !== 2 && a !== 4) { + M(c, c, i); + } + } + for (a = 0; a < 16; ++a) { + o[a] = c[a]; + } + } + function car25519(o) { + var i, v, c = 1; + for (i = 0; i < 16; ++i) { + v = o[i] + c + 65535; + c = Math.floor(v / 65536); + o[i] = v - c * 65536; + } + o[0] += c - 1 + 37 * (c - 1); + } + function sel25519(p, q, b) { + var t, c = ~(b - 1); + for (var i = 0; i < 16; ++i) { + t = c & (p[i] ^ q[i]); + p[i] ^= t; + q[i] ^= t; + } + } + function gf(init) { + var i, r = new Float64Array(16); + if (init) { + for (i = 0; i < init.length; ++i) { + r[i] = init[i]; + } + } + return r; + } + function A(o, a, b) { + for (var i = 0; i < 16; ++i) { + o[i] = a[i] + b[i]; + } + } + function Z(o, a, b) { + for (var i = 0; i < 16; ++i) { + o[i] = a[i] - b[i]; + } + } + function S(o, a) { + M(o, a, a); + } + function M(o, a, b) { + var v, c, t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3], b4 = b[4], b5 = b[5], b6 = b[6], b7 = b[7], b8 = b[8], b9 = b[9], b10 = b[10], b11 = b[11], b12 = b[12], b13 = b[13], b14 = b[14], b15 = b[15]; + v = a[0]; + t0 += v * b0; + t1 += v * b1; + t2 += v * b2; + t3 += v * b3; + t4 += v * b4; + t5 += v * b5; + t6 += v * b6; + t7 += v * b7; + t8 += v * b8; + t9 += v * b9; + t10 += v * b10; + t11 += v * b11; + t12 += v * b12; + t13 += v * b13; + t14 += v * b14; + t15 += v * b15; + v = a[1]; + t1 += v * b0; + t2 += v * b1; + t3 += v * b2; + t4 += v * b3; + t5 += v * b4; + t6 += v * b5; + t7 += v * b6; + t8 += v * b7; + t9 += v * b8; + t10 += v * b9; + t11 += v * b10; + t12 += v * b11; + t13 += v * b12; + t14 += v * b13; + t15 += v * b14; + t16 += v * b15; + v = a[2]; + t2 += v * b0; + t3 += v * b1; + t4 += v * b2; + t5 += v * b3; + t6 += v * b4; + t7 += v * b5; + t8 += v * b6; + t9 += v * b7; + t10 += v * b8; + t11 += v * b9; + t12 += v * b10; + t13 += v * b11; + t14 += v * b12; + t15 += v * b13; + t16 += v * b14; + t17 += v * b15; + v = a[3]; + t3 += v * b0; + t4 += v * b1; + t5 += v * b2; + t6 += v * b3; + t7 += v * b4; + t8 += v * b5; + t9 += v * b6; + t10 += v * b7; + t11 += v * b8; + t12 += v * b9; + t13 += v * b10; + t14 += v * b11; + t15 += v * b12; + t16 += v * b13; + t17 += v * b14; + t18 += v * b15; + v = a[4]; + t4 += v * b0; + t5 += v * b1; + t6 += v * b2; + t7 += v * b3; + t8 += v * b4; + t9 += v * b5; + t10 += v * b6; + t11 += v * b7; + t12 += v * b8; + t13 += v * b9; + t14 += v * b10; + t15 += v * b11; + t16 += v * b12; + t17 += v * b13; + t18 += v * b14; + t19 += v * b15; + v = a[5]; + t5 += v * b0; + t6 += v * b1; + t7 += v * b2; + t8 += v * b3; + t9 += v * b4; + t10 += v * b5; + t11 += v * b6; + t12 += v * b7; + t13 += v * b8; + t14 += v * b9; + t15 += v * b10; + t16 += v * b11; + t17 += v * b12; + t18 += v * b13; + t19 += v * b14; + t20 += v * b15; + v = a[6]; + t6 += v * b0; + t7 += v * b1; + t8 += v * b2; + t9 += v * b3; + t10 += v * b4; + t11 += v * b5; + t12 += v * b6; + t13 += v * b7; + t14 += v * b8; + t15 += v * b9; + t16 += v * b10; + t17 += v * b11; + t18 += v * b12; + t19 += v * b13; + t20 += v * b14; + t21 += v * b15; + v = a[7]; + t7 += v * b0; + t8 += v * b1; + t9 += v * b2; + t10 += v * b3; + t11 += v * b4; + t12 += v * b5; + t13 += v * b6; + t14 += v * b7; + t15 += v * b8; + t16 += v * b9; + t17 += v * b10; + t18 += v * b11; + t19 += v * b12; + t20 += v * b13; + t21 += v * b14; + t22 += v * b15; + v = a[8]; + t8 += v * b0; + t9 += v * b1; + t10 += v * b2; + t11 += v * b3; + t12 += v * b4; + t13 += v * b5; + t14 += v * b6; + t15 += v * b7; + t16 += v * b8; + t17 += v * b9; + t18 += v * b10; + t19 += v * b11; + t20 += v * b12; + t21 += v * b13; + t22 += v * b14; + t23 += v * b15; + v = a[9]; + t9 += v * b0; + t10 += v * b1; + t11 += v * b2; + t12 += v * b3; + t13 += v * b4; + t14 += v * b5; + t15 += v * b6; + t16 += v * b7; + t17 += v * b8; + t18 += v * b9; + t19 += v * b10; + t20 += v * b11; + t21 += v * b12; + t22 += v * b13; + t23 += v * b14; + t24 += v * b15; + v = a[10]; + t10 += v * b0; + t11 += v * b1; + t12 += v * b2; + t13 += v * b3; + t14 += v * b4; + t15 += v * b5; + t16 += v * b6; + t17 += v * b7; + t18 += v * b8; + t19 += v * b9; + t20 += v * b10; + t21 += v * b11; + t22 += v * b12; + t23 += v * b13; + t24 += v * b14; + t25 += v * b15; + v = a[11]; + t11 += v * b0; + t12 += v * b1; + t13 += v * b2; + t14 += v * b3; + t15 += v * b4; + t16 += v * b5; + t17 += v * b6; + t18 += v * b7; + t19 += v * b8; + t20 += v * b9; + t21 += v * b10; + t22 += v * b11; + t23 += v * b12; + t24 += v * b13; + t25 += v * b14; + t26 += v * b15; + v = a[12]; + t12 += v * b0; + t13 += v * b1; + t14 += v * b2; + t15 += v * b3; + t16 += v * b4; + t17 += v * b5; + t18 += v * b6; + t19 += v * b7; + t20 += v * b8; + t21 += v * b9; + t22 += v * b10; + t23 += v * b11; + t24 += v * b12; + t25 += v * b13; + t26 += v * b14; + t27 += v * b15; + v = a[13]; + t13 += v * b0; + t14 += v * b1; + t15 += v * b2; + t16 += v * b3; + t17 += v * b4; + t18 += v * b5; + t19 += v * b6; + t20 += v * b7; + t21 += v * b8; + t22 += v * b9; + t23 += v * b10; + t24 += v * b11; + t25 += v * b12; + t26 += v * b13; + t27 += v * b14; + t28 += v * b15; + v = a[14]; + t14 += v * b0; + t15 += v * b1; + t16 += v * b2; + t17 += v * b3; + t18 += v * b4; + t19 += v * b5; + t20 += v * b6; + t21 += v * b7; + t22 += v * b8; + t23 += v * b9; + t24 += v * b10; + t25 += v * b11; + t26 += v * b12; + t27 += v * b13; + t28 += v * b14; + t29 += v * b15; + v = a[15]; + t15 += v * b0; + t16 += v * b1; + t17 += v * b2; + t18 += v * b3; + t19 += v * b4; + t20 += v * b5; + t21 += v * b6; + t22 += v * b7; + t23 += v * b8; + t24 += v * b9; + t25 += v * b10; + t26 += v * b11; + t27 += v * b12; + t28 += v * b13; + t29 += v * b14; + t30 += v * b15; + t0 += 38 * t16; + t1 += 38 * t17; + t2 += 38 * t18; + t3 += 38 * t19; + t4 += 38 * t20; + t5 += 38 * t21; + t6 += 38 * t22; + t7 += 38 * t23; + t8 += 38 * t24; + t9 += 38 * t25; + t10 += 38 * t26; + t11 += 38 * t27; + t12 += 38 * t28; + t13 += 38 * t29; + t14 += 38 * t30; + c = 1; + v = t0 + c + 65535; + c = Math.floor(v / 65536); + t0 = v - c * 65536; + v = t1 + c + 65535; + c = Math.floor(v / 65536); + t1 = v - c * 65536; + v = t2 + c + 65535; + c = Math.floor(v / 65536); + t2 = v - c * 65536; + v = t3 + c + 65535; + c = Math.floor(v / 65536); + t3 = v - c * 65536; + v = t4 + c + 65535; + c = Math.floor(v / 65536); + t4 = v - c * 65536; + v = t5 + c + 65535; + c = Math.floor(v / 65536); + t5 = v - c * 65536; + v = t6 + c + 65535; + c = Math.floor(v / 65536); + t6 = v - c * 65536; + v = t7 + c + 65535; + c = Math.floor(v / 65536); + t7 = v - c * 65536; + v = t8 + c + 65535; + c = Math.floor(v / 65536); + t8 = v - c * 65536; + v = t9 + c + 65535; + c = Math.floor(v / 65536); + t9 = v - c * 65536; + v = t10 + c + 65535; + c = Math.floor(v / 65536); + t10 = v - c * 65536; + v = t11 + c + 65535; + c = Math.floor(v / 65536); + t11 = v - c * 65536; + v = t12 + c + 65535; + c = Math.floor(v / 65536); + t12 = v - c * 65536; + v = t13 + c + 65535; + c = Math.floor(v / 65536); + t13 = v - c * 65536; + v = t14 + c + 65535; + c = Math.floor(v / 65536); + t14 = v - c * 65536; + v = t15 + c + 65535; + c = Math.floor(v / 65536); + t15 = v - c * 65536; + t0 += c - 1 + 37 * (c - 1); + c = 1; + v = t0 + c + 65535; + c = Math.floor(v / 65536); + t0 = v - c * 65536; + v = t1 + c + 65535; + c = Math.floor(v / 65536); + t1 = v - c * 65536; + v = t2 + c + 65535; + c = Math.floor(v / 65536); + t2 = v - c * 65536; + v = t3 + c + 65535; + c = Math.floor(v / 65536); + t3 = v - c * 65536; + v = t4 + c + 65535; + c = Math.floor(v / 65536); + t4 = v - c * 65536; + v = t5 + c + 65535; + c = Math.floor(v / 65536); + t5 = v - c * 65536; + v = t6 + c + 65535; + c = Math.floor(v / 65536); + t6 = v - c * 65536; + v = t7 + c + 65535; + c = Math.floor(v / 65536); + t7 = v - c * 65536; + v = t8 + c + 65535; + c = Math.floor(v / 65536); + t8 = v - c * 65536; + v = t9 + c + 65535; + c = Math.floor(v / 65536); + t9 = v - c * 65536; + v = t10 + c + 65535; + c = Math.floor(v / 65536); + t10 = v - c * 65536; + v = t11 + c + 65535; + c = Math.floor(v / 65536); + t11 = v - c * 65536; + v = t12 + c + 65535; + c = Math.floor(v / 65536); + t12 = v - c * 65536; + v = t13 + c + 65535; + c = Math.floor(v / 65536); + t13 = v - c * 65536; + v = t14 + c + 65535; + c = Math.floor(v / 65536); + t14 = v - c * 65536; + v = t15 + c + 65535; + c = Math.floor(v / 65536); + t15 = v - c * 65536; + t0 += c - 1 + 37 * (c - 1); + o[0] = t0; + o[1] = t1; + o[2] = t2; + o[3] = t3; + o[4] = t4; + o[5] = t5; + o[6] = t6; + o[7] = t7; + o[8] = t8; + o[9] = t9; + o[10] = t10; + o[11] = t11; + o[12] = t12; + o[13] = t13; + o[14] = t14; + o[15] = t15; + } + } +}); + +// node_modules/node-forge/lib/kem.js +var require_kem = __commonJS({ + "node_modules/node-forge/lib/kem.js"(exports2, module2) { + var forge = require_forge(); + require_util13(); + require_random(); + require_jsbn(); + module2.exports = forge.kem = forge.kem || {}; + var BigInteger = forge.jsbn.BigInteger; + forge.kem.rsa = {}; + forge.kem.rsa.create = function(kdf, options) { + options = options || {}; + var prng = options.prng || forge.random; + var kem = {}; + kem.encrypt = function(publicKey, keyLength) { + var byteLength = Math.ceil(publicKey.n.bitLength() / 8); + var r; + do { + r = new BigInteger( + forge.util.bytesToHex(prng.getBytesSync(byteLength)), + 16 + ).mod(publicKey.n); + } while (r.compareTo(BigInteger.ONE) <= 0); + r = forge.util.hexToBytes(r.toString(16)); + var zeros = byteLength - r.length; + if (zeros > 0) { + r = forge.util.fillString(String.fromCharCode(0), zeros) + r; + } + var encapsulation = publicKey.encrypt(r, "NONE"); + var key = kdf.generate(r, keyLength); + return { encapsulation, key }; + }; + kem.decrypt = function(privateKey, encapsulation, keyLength) { + var r = privateKey.decrypt(encapsulation, "NONE"); + return kdf.generate(r, keyLength); + }; + return kem; + }; + forge.kem.kdf1 = function(md2, digestLength) { + _createKDF(this, md2, 0, digestLength || md2.digestLength); + }; + forge.kem.kdf2 = function(md2, digestLength) { + _createKDF(this, md2, 1, digestLength || md2.digestLength); + }; + function _createKDF(kdf, md2, counterStart, digestLength) { + kdf.generate = function(x, length) { + var key = new forge.util.ByteBuffer(); + var k = Math.ceil(length / digestLength) + counterStart; + var c = new forge.util.ByteBuffer(); + for (var i = counterStart; i < k; ++i) { + c.putInt32(i); + md2.start(); + md2.update(x + c.getBytes()); + var hash = md2.digest(); + key.putBytes(hash.getBytes(digestLength)); + } + key.truncate(key.length() - length); + return key.getBytes(); + }; + } + } +}); + +// node_modules/node-forge/lib/log.js +var require_log = __commonJS({ + "node_modules/node-forge/lib/log.js"(exports2, module2) { + var forge = require_forge(); + require_util13(); + module2.exports = forge.log = forge.log || {}; + forge.log.levels = [ + "none", + "error", + "warning", + "info", + "debug", + "verbose", + "max" + ]; + var sLevelInfo = {}; + var sLoggers = []; + var sConsoleLogger = null; + forge.log.LEVEL_LOCKED = 1 << 1; + forge.log.NO_LEVEL_CHECK = 1 << 2; + forge.log.INTERPOLATE = 1 << 3; + for (i = 0; i < forge.log.levels.length; ++i) { + level = forge.log.levels[i]; + sLevelInfo[level] = { + index: i, + name: level.toUpperCase() + }; + } + var level; + var i; + forge.log.logMessage = function(message) { + var messageLevelIndex = sLevelInfo[message.level].index; + for (var i2 = 0; i2 < sLoggers.length; ++i2) { + var logger2 = sLoggers[i2]; + if (logger2.flags & forge.log.NO_LEVEL_CHECK) { + logger2.f(message); + } else { + var loggerLevelIndex = sLevelInfo[logger2.level].index; + if (messageLevelIndex <= loggerLevelIndex) { + logger2.f(logger2, message); + } + } + } + }; + forge.log.prepareStandard = function(message) { + if (!("standard" in message)) { + message.standard = sLevelInfo[message.level].name + //' ' + +message.timestamp + + " [" + message.category + "] " + message.message; + } + }; + forge.log.prepareFull = function(message) { + if (!("full" in message)) { + var args = [message.message]; + args = args.concat([]); + message.full = forge.util.format.apply(this, args); + } + }; + forge.log.prepareStandardFull = function(message) { + if (!("standardFull" in message)) { + forge.log.prepareStandard(message); + message.standardFull = message.standard; + } + }; + if (true) { + levels = ["error", "warning", "info", "debug", "verbose"]; + for (i = 0; i < levels.length; ++i) { + (function(level2) { + forge.log[level2] = function(category, message) { + var args = Array.prototype.slice.call(arguments).slice(2); + var msg = { + timestamp: /* @__PURE__ */ new Date(), + level: level2, + category, + message, + "arguments": args + /*standard*/ + /*full*/ + /*fullMessage*/ + }; + forge.log.logMessage(msg); + }; + })(levels[i]); + } + } + var levels; + var i; + forge.log.makeLogger = function(logFunction) { + var logger2 = { + flags: 0, + f: logFunction + }; + forge.log.setLevel(logger2, "none"); + return logger2; + }; + forge.log.setLevel = function(logger2, level2) { + var rval = false; + if (logger2 && !(logger2.flags & forge.log.LEVEL_LOCKED)) { + for (var i2 = 0; i2 < forge.log.levels.length; ++i2) { + var aValidLevel = forge.log.levels[i2]; + if (level2 == aValidLevel) { + logger2.level = level2; + rval = true; + break; + } + } + } + return rval; + }; + forge.log.lock = function(logger2, lock2) { + if (typeof lock2 === "undefined" || lock2) { + logger2.flags |= forge.log.LEVEL_LOCKED; + } else { + logger2.flags &= ~forge.log.LEVEL_LOCKED; + } + }; + forge.log.addLogger = function(logger2) { + sLoggers.push(logger2); + }; + if (typeof console !== "undefined" && "log" in console) { + if (console.error && console.warn && console.info && console.debug) { + levelHandlers = { + error: console.error, + warning: console.warn, + info: console.info, + debug: console.debug, + verbose: console.debug + }; + f = function(logger2, message) { + forge.log.prepareStandard(message); + var handler2 = levelHandlers[message.level]; + var args = [message.standard]; + args = args.concat(message["arguments"].slice()); + handler2.apply(console, args); + }; + logger = forge.log.makeLogger(f); + } else { + f = function(logger2, message) { + forge.log.prepareStandardFull(message); + console.log(message.standardFull); + }; + logger = forge.log.makeLogger(f); + } + forge.log.setLevel(logger, "debug"); + forge.log.addLogger(logger); + sConsoleLogger = logger; + } else { + console = { + log: function() { + } + }; + } + var logger; + var levelHandlers; + var f; + if (sConsoleLogger !== null && typeof window !== "undefined" && window.location) { + query = new URL(window.location.href).searchParams; + if (query.has("console.level")) { + forge.log.setLevel( + sConsoleLogger, + query.get("console.level").slice(-1)[0] + ); + } + if (query.has("console.lock")) { + lock = query.get("console.lock").slice(-1)[0]; + if (lock == "true") { + forge.log.lock(sConsoleLogger); + } + } + } + var query; + var lock; + forge.log.consoleLogger = sConsoleLogger; + } +}); + +// node_modules/node-forge/lib/md.all.js +var require_md_all = __commonJS({ + "node_modules/node-forge/lib/md.all.js"(exports2, module2) { + module2.exports = require_md(); + require_md5(); + require_sha1(); + require_sha256(); + require_sha512(); + } +}); + +// node_modules/node-forge/lib/pkcs7.js +var require_pkcs7 = __commonJS({ + "node_modules/node-forge/lib/pkcs7.js"(exports2, module2) { + var forge = require_forge(); + require_aes(); + require_asn1(); + require_des(); + require_oids(); + require_pem(); + require_pkcs7asn1(); + require_random(); + require_util13(); + require_x509(); + var asn1 = forge.asn1; + var p7 = module2.exports = forge.pkcs7 = forge.pkcs7 || {}; + p7.messageFromPem = function(pem) { + var msg = forge.pem.decode(pem)[0]; + if (msg.type !== "PKCS7") { + var error2 = new Error('Could not convert PKCS#7 message from PEM; PEM header type is not "PKCS#7".'); + error2.headerType = msg.type; + throw error2; + } + if (msg.procType && msg.procType.type === "ENCRYPTED") { + throw new Error("Could not convert PKCS#7 message from PEM; PEM is encrypted."); + } + var obj = asn1.fromDer(msg.body); + return p7.messageFromAsn1(obj); + }; + p7.messageToPem = function(msg, maxline) { + var pemObj = { + type: "PKCS7", + body: asn1.toDer(msg.toAsn1()).getBytes() + }; + return forge.pem.encode(pemObj, { maxline }); + }; + p7.messageFromAsn1 = function(obj) { + var capture = {}; + var errors = []; + if (!asn1.validate(obj, p7.asn1.contentInfoValidator, capture, errors)) { + var error2 = new Error("Cannot read PKCS#7 message. ASN.1 object is not an PKCS#7 ContentInfo."); + error2.errors = errors; + throw error2; + } + var contentType = asn1.derToOid(capture.contentType); + var msg; + switch (contentType) { + case forge.pki.oids.envelopedData: + msg = p7.createEnvelopedData(); + break; + case forge.pki.oids.encryptedData: + msg = p7.createEncryptedData(); + break; + case forge.pki.oids.signedData: + msg = p7.createSignedData(); + break; + default: + throw new Error("Cannot read PKCS#7 message. ContentType with OID " + contentType + " is not (yet) supported."); + } + msg.fromAsn1(capture.content.value[0]); + return msg; + }; + p7.createSignedData = function() { + var msg = null; + msg = { + type: forge.pki.oids.signedData, + version: 1, + certificates: [], + crls: [], + // TODO: add json-formatted signer stuff here? + signers: [], + // populated during sign() + digestAlgorithmIdentifiers: [], + contentInfo: null, + signerInfos: [], + fromAsn1: function(obj) { + _fromAsn1(msg, obj, p7.asn1.signedDataValidator); + msg.certificates = []; + msg.crls = []; + msg.digestAlgorithmIdentifiers = []; + msg.contentInfo = null; + msg.signerInfos = []; + if (msg.rawCapture.certificates) { + var certs = msg.rawCapture.certificates.value; + for (var i = 0; i < certs.length; ++i) { + msg.certificates.push(forge.pki.certificateFromAsn1(certs[i])); + } + } + }, + toAsn1: function() { + if (!msg.contentInfo) { + msg.sign(); + } + var certs = []; + for (var i = 0; i < msg.certificates.length; ++i) { + certs.push(forge.pki.certificateToAsn1(msg.certificates[i])); + } + var crls = []; + var signedData = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Version + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + asn1.integerToDer(msg.version).getBytes() + ), + // DigestAlgorithmIdentifiers + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SET, + true, + msg.digestAlgorithmIdentifiers + ), + // ContentInfo + msg.contentInfo + ]) + ]); + if (certs.length > 0) { + signedData.value[0].value.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, certs) + ); + } + if (crls.length > 0) { + signedData.value[0].value.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, crls) + ); + } + signedData.value[0].value.push( + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SET, + true, + msg.signerInfos + ) + ); + return asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SEQUENCE, + true, + [ + // ContentType + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(msg.type).getBytes() + ), + // [0] SignedData + signedData + ] + ); + }, + /** + * Add (another) entity to list of signers. + * + * Note: If authenticatedAttributes are provided, then, per RFC 2315, + * they must include at least two attributes: content type and + * message digest. The message digest attribute value will be + * auto-calculated during signing and will be ignored if provided. + * + * Here's an example of providing these two attributes: + * + * forge.pkcs7.createSignedData(); + * p7.addSigner({ + * issuer: cert.issuer.attributes, + * serialNumber: cert.serialNumber, + * key: privateKey, + * digestAlgorithm: forge.pki.oids.sha1, + * authenticatedAttributes: [{ + * type: forge.pki.oids.contentType, + * value: forge.pki.oids.data + * }, { + * type: forge.pki.oids.messageDigest + * }] + * }); + * + * TODO: Support [subjectKeyIdentifier] as signer's ID. + * + * @param signer the signer information: + * key the signer's private key. + * [certificate] a certificate containing the public key + * associated with the signer's private key; use this option as + * an alternative to specifying signer.issuer and + * signer.serialNumber. + * [issuer] the issuer attributes (eg: cert.issuer.attributes). + * [serialNumber] the signer's certificate's serial number in + * hexadecimal (eg: cert.serialNumber). + * [digestAlgorithm] the message digest OID, as a string, to use + * (eg: forge.pki.oids.sha1). + * [authenticatedAttributes] an optional array of attributes + * to also sign along with the content. + */ + addSigner: function(signer) { + var issuer = signer.issuer; + var serialNumber = signer.serialNumber; + if (signer.certificate) { + var cert = signer.certificate; + if (typeof cert === "string") { + cert = forge.pki.certificateFromPem(cert); + } + issuer = cert.issuer.attributes; + serialNumber = cert.serialNumber; + } + var key = signer.key; + if (!key) { + throw new Error( + "Could not add PKCS#7 signer; no private key specified." + ); + } + if (typeof key === "string") { + key = forge.pki.privateKeyFromPem(key); + } + var digestAlgorithm = signer.digestAlgorithm || forge.pki.oids.sha1; + switch (digestAlgorithm) { + case forge.pki.oids.sha1: + case forge.pki.oids.sha256: + case forge.pki.oids.sha384: + case forge.pki.oids.sha512: + case forge.pki.oids.md5: + break; + default: + throw new Error( + "Could not add PKCS#7 signer; unknown message digest algorithm: " + digestAlgorithm + ); + } + var authenticatedAttributes = signer.authenticatedAttributes || []; + if (authenticatedAttributes.length > 0) { + var contentType = false; + var messageDigest = false; + for (var i = 0; i < authenticatedAttributes.length; ++i) { + var attr = authenticatedAttributes[i]; + if (!contentType && attr.type === forge.pki.oids.contentType) { + contentType = true; + if (messageDigest) { + break; + } + continue; + } + if (!messageDigest && attr.type === forge.pki.oids.messageDigest) { + messageDigest = true; + if (contentType) { + break; + } + continue; + } + } + if (!contentType || !messageDigest) { + throw new Error("Invalid signer.authenticatedAttributes. If signer.authenticatedAttributes is specified, then it must contain at least two attributes, PKCS #9 content-type and PKCS #9 message-digest."); + } + } + msg.signers.push({ + key, + version: 1, + issuer, + serialNumber, + digestAlgorithm, + signatureAlgorithm: forge.pki.oids.rsaEncryption, + signature: null, + authenticatedAttributes, + unauthenticatedAttributes: [] + }); + }, + /** + * Signs the content. + * @param options Options to apply when signing: + * [detached] boolean. If signing should be done in detached mode. Defaults to false. + */ + sign: function(options) { + options = options || {}; + if (typeof msg.content !== "object" || msg.contentInfo === null) { + msg.contentInfo = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SEQUENCE, + true, + [ + // ContentType + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(forge.pki.oids.data).getBytes() + ) + ] + ); + if ("content" in msg) { + var content; + if (msg.content instanceof forge.util.ByteBuffer) { + content = msg.content.bytes(); + } else if (typeof msg.content === "string") { + content = forge.util.encodeUtf8(msg.content); + } + if (options.detached) { + msg.detachedContent = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, content); + } else { + msg.contentInfo.value.push( + // [0] EXPLICIT content + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + content + ) + ]) + ); + } + } + } + if (msg.signers.length === 0) { + return; + } + var mds = addDigestAlgorithmIds(); + addSignerInfos(mds); + }, + verify: function() { + throw new Error("PKCS#7 signature verification not yet implemented."); + }, + /** + * Add a certificate. + * + * @param cert the certificate to add. + */ + addCertificate: function(cert) { + if (typeof cert === "string") { + cert = forge.pki.certificateFromPem(cert); + } + msg.certificates.push(cert); + }, + /** + * Add a certificate revokation list. + * + * @param crl the certificate revokation list to add. + */ + addCertificateRevokationList: function(crl) { + throw new Error("PKCS#7 CRL support not yet implemented."); + } + }; + return msg; + function addDigestAlgorithmIds() { + var mds = {}; + for (var i = 0; i < msg.signers.length; ++i) { + var signer = msg.signers[i]; + var oid = signer.digestAlgorithm; + if (!(oid in mds)) { + mds[oid] = forge.md[forge.pki.oids[oid]].create(); + } + if (signer.authenticatedAttributes.length === 0) { + signer.md = mds[oid]; + } else { + signer.md = forge.md[forge.pki.oids[oid]].create(); + } + } + msg.digestAlgorithmIdentifiers = []; + for (var oid in mds) { + msg.digestAlgorithmIdentifiers.push( + // AlgorithmIdentifier + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(oid).getBytes() + ), + // parameters (null) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") + ]) + ); + } + return mds; + } + function addSignerInfos(mds) { + var content; + if (msg.detachedContent) { + content = msg.detachedContent; + } else { + content = msg.contentInfo.value[1]; + content = content.value[0]; + } + if (!content) { + throw new Error( + "Could not sign PKCS#7 message; there is no content to sign." + ); + } + var contentType = asn1.derToOid(msg.contentInfo.value[0].value); + var bytes = asn1.toDer(content); + bytes.getByte(); + asn1.getBerValueLength(bytes); + bytes = bytes.getBytes(); + for (var oid in mds) { + mds[oid].start().update(bytes); + } + var signingTime = /* @__PURE__ */ new Date(); + for (var i = 0; i < msg.signers.length; ++i) { + var signer = msg.signers[i]; + if (signer.authenticatedAttributes.length === 0) { + if (contentType !== forge.pki.oids.data) { + throw new Error( + "Invalid signer; authenticatedAttributes must be present when the ContentInfo content type is not PKCS#7 Data." + ); + } + } else { + signer.authenticatedAttributesAsn1 = asn1.create( + asn1.Class.CONTEXT_SPECIFIC, + 0, + true, + [] + ); + var attrsAsn1 = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SET, + true, + [] + ); + for (var ai = 0; ai < signer.authenticatedAttributes.length; ++ai) { + var attr = signer.authenticatedAttributes[ai]; + if (attr.type === forge.pki.oids.messageDigest) { + attr.value = mds[signer.digestAlgorithm].digest(); + } else if (attr.type === forge.pki.oids.signingTime) { + if (!attr.value) { + attr.value = signingTime; + } + } + attrsAsn1.value.push(_attributeToAsn1(attr)); + signer.authenticatedAttributesAsn1.value.push(_attributeToAsn1(attr)); + } + bytes = asn1.toDer(attrsAsn1).getBytes(); + signer.md.start().update(bytes); + } + signer.signature = signer.key.sign(signer.md, "RSASSA-PKCS1-V1_5"); + } + msg.signerInfos = _signersToAsn1(msg.signers); + } + }; + p7.createEncryptedData = function() { + var msg = null; + msg = { + type: forge.pki.oids.encryptedData, + version: 0, + encryptedContent: { + algorithm: forge.pki.oids["aes256-CBC"] + }, + /** + * Reads an EncryptedData content block (in ASN.1 format) + * + * @param obj The ASN.1 representation of the EncryptedData content block + */ + fromAsn1: function(obj) { + _fromAsn1(msg, obj, p7.asn1.encryptedDataValidator); + }, + /** + * Decrypt encrypted content + * + * @param key The (symmetric) key as a byte buffer + */ + decrypt: function(key) { + if (key !== void 0) { + msg.encryptedContent.key = key; + } + _decryptContent(msg); + } + }; + return msg; + }; + p7.createEnvelopedData = function() { + var msg = null; + msg = { + type: forge.pki.oids.envelopedData, + version: 0, + recipients: [], + encryptedContent: { + algorithm: forge.pki.oids["aes256-CBC"] + }, + /** + * Reads an EnvelopedData content block (in ASN.1 format) + * + * @param obj the ASN.1 representation of the EnvelopedData content block. + */ + fromAsn1: function(obj) { + var capture = _fromAsn1(msg, obj, p7.asn1.envelopedDataValidator); + msg.recipients = _recipientsFromAsn1(capture.recipientInfos.value); + }, + toAsn1: function() { + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // ContentType + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(msg.type).getBytes() + ), + // [0] EnvelopedData + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Version + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + asn1.integerToDer(msg.version).getBytes() + ), + // RecipientInfos + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SET, + true, + _recipientsToAsn1(msg.recipients) + ), + // EncryptedContentInfo + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SEQUENCE, + true, + _encryptedContentToAsn1(msg.encryptedContent) + ) + ]) + ]) + ]); + }, + /** + * Find recipient by X.509 certificate's issuer. + * + * @param cert the certificate with the issuer to look for. + * + * @return the recipient object. + */ + findRecipient: function(cert) { + var sAttr = cert.issuer.attributes; + for (var i = 0; i < msg.recipients.length; ++i) { + var r = msg.recipients[i]; + var rAttr = r.issuer; + if (r.serialNumber !== cert.serialNumber) { + continue; + } + if (rAttr.length !== sAttr.length) { + continue; + } + var match = true; + for (var j = 0; j < sAttr.length; ++j) { + if (rAttr[j].type !== sAttr[j].type || rAttr[j].value !== sAttr[j].value) { + match = false; + break; + } + } + if (match) { + return r; + } + } + return null; + }, + /** + * Decrypt enveloped content + * + * @param recipient The recipient object related to the private key + * @param privKey The (RSA) private key object + */ + decrypt: function(recipient, privKey) { + if (msg.encryptedContent.key === void 0 && recipient !== void 0 && privKey !== void 0) { + switch (recipient.encryptedContent.algorithm) { + case forge.pki.oids.rsaEncryption: + case forge.pki.oids.desCBC: + var key = privKey.decrypt(recipient.encryptedContent.content); + msg.encryptedContent.key = forge.util.createBuffer(key); + break; + default: + throw new Error("Unsupported asymmetric cipher, OID " + recipient.encryptedContent.algorithm); + } + } + _decryptContent(msg); + }, + /** + * Add (another) entity to list of recipients. + * + * @param cert The certificate of the entity to add. + */ + addRecipient: function(cert) { + msg.recipients.push({ + version: 0, + issuer: cert.issuer.attributes, + serialNumber: cert.serialNumber, + encryptedContent: { + // We simply assume rsaEncryption here, since forge.pki only + // supports RSA so far. If the PKI module supports other + // ciphers one day, we need to modify this one as well. + algorithm: forge.pki.oids.rsaEncryption, + key: cert.publicKey + } + }); + }, + /** + * Encrypt enveloped content. + * + * This function supports two optional arguments, cipher and key, which + * can be used to influence symmetric encryption. Unless cipher is + * provided, the cipher specified in encryptedContent.algorithm is used + * (defaults to AES-256-CBC). If no key is provided, encryptedContent.key + * is (re-)used. If that one's not set, a random key will be generated + * automatically. + * + * @param [key] The key to be used for symmetric encryption. + * @param [cipher] The OID of the symmetric cipher to use. + */ + encrypt: function(key, cipher) { + if (msg.encryptedContent.content === void 0) { + cipher = cipher || msg.encryptedContent.algorithm; + key = key || msg.encryptedContent.key; + var keyLen, ivLen, ciphFn; + switch (cipher) { + case forge.pki.oids["aes128-CBC"]: + keyLen = 16; + ivLen = 16; + ciphFn = forge.aes.createEncryptionCipher; + break; + case forge.pki.oids["aes192-CBC"]: + keyLen = 24; + ivLen = 16; + ciphFn = forge.aes.createEncryptionCipher; + break; + case forge.pki.oids["aes256-CBC"]: + keyLen = 32; + ivLen = 16; + ciphFn = forge.aes.createEncryptionCipher; + break; + case forge.pki.oids["des-EDE3-CBC"]: + keyLen = 24; + ivLen = 8; + ciphFn = forge.des.createEncryptionCipher; + break; + default: + throw new Error("Unsupported symmetric cipher, OID " + cipher); + } + if (key === void 0) { + key = forge.util.createBuffer(forge.random.getBytes(keyLen)); + } else if (key.length() != keyLen) { + throw new Error("Symmetric key has wrong length; got " + key.length() + " bytes, expected " + keyLen + "."); + } + msg.encryptedContent.algorithm = cipher; + msg.encryptedContent.key = key; + msg.encryptedContent.parameter = forge.util.createBuffer( + forge.random.getBytes(ivLen) + ); + var ciph = ciphFn(key); + ciph.start(msg.encryptedContent.parameter.copy()); + ciph.update(msg.content); + if (!ciph.finish()) { + throw new Error("Symmetric encryption failed."); + } + msg.encryptedContent.content = ciph.output; + } + for (var i = 0; i < msg.recipients.length; ++i) { + var recipient = msg.recipients[i]; + if (recipient.encryptedContent.content !== void 0) { + continue; + } + switch (recipient.encryptedContent.algorithm) { + case forge.pki.oids.rsaEncryption: + recipient.encryptedContent.content = recipient.encryptedContent.key.encrypt( + msg.encryptedContent.key.data + ); + break; + default: + throw new Error("Unsupported asymmetric cipher, OID " + recipient.encryptedContent.algorithm); + } + } + } + }; + return msg; + }; + function _recipientFromAsn1(obj) { + var capture = {}; + var errors = []; + if (!asn1.validate(obj, p7.asn1.recipientInfoValidator, capture, errors)) { + var error2 = new Error("Cannot read PKCS#7 RecipientInfo. ASN.1 object is not an PKCS#7 RecipientInfo."); + error2.errors = errors; + throw error2; + } + return { + version: capture.version.charCodeAt(0), + issuer: forge.pki.RDNAttributesAsArray(capture.issuer), + serialNumber: forge.util.createBuffer(capture.serial).toHex(), + encryptedContent: { + algorithm: asn1.derToOid(capture.encAlgorithm), + parameter: capture.encParameter ? capture.encParameter.value : void 0, + content: capture.encKey + } + }; + } + function _recipientToAsn1(obj) { + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Version + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + asn1.integerToDer(obj.version).getBytes() + ), + // IssuerAndSerialNumber + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Name + forge.pki.distinguishedNameToAsn1({ attributes: obj.issuer }), + // Serial + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + forge.util.hexToBytes(obj.serialNumber) + ) + ]), + // KeyEncryptionAlgorithmIdentifier + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Algorithm + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(obj.encryptedContent.algorithm).getBytes() + ), + // Parameter, force NULL, only RSA supported for now. + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") + ]), + // EncryptedKey + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + obj.encryptedContent.content + ) + ]); + } + function _recipientsFromAsn1(infos) { + var ret = []; + for (var i = 0; i < infos.length; ++i) { + ret.push(_recipientFromAsn1(infos[i])); + } + return ret; + } + function _recipientsToAsn1(recipients) { + var ret = []; + for (var i = 0; i < recipients.length; ++i) { + ret.push(_recipientToAsn1(recipients[i])); + } + return ret; + } + function _signerToAsn1(obj) { + var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // version + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + asn1.integerToDer(obj.version).getBytes() + ), + // issuerAndSerialNumber + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // name + forge.pki.distinguishedNameToAsn1({ attributes: obj.issuer }), + // serial + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + forge.util.hexToBytes(obj.serialNumber) + ) + ]), + // digestAlgorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(obj.digestAlgorithm).getBytes() + ), + // parameters (null) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") + ]) + ]); + if (obj.authenticatedAttributesAsn1) { + rval.value.push(obj.authenticatedAttributesAsn1); + } + rval.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(obj.signatureAlgorithm).getBytes() + ), + // parameters (null) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") + ])); + rval.value.push(asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + obj.signature + )); + if (obj.unauthenticatedAttributes.length > 0) { + var attrsAsn1 = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, []); + for (var i = 0; i < obj.unauthenticatedAttributes.length; ++i) { + var attr = obj.unauthenticatedAttributes[i]; + attrsAsn1.values.push(_attributeToAsn1(attr)); + } + rval.value.push(attrsAsn1); + } + return rval; + } + function _signersToAsn1(signers) { + var ret = []; + for (var i = 0; i < signers.length; ++i) { + ret.push(_signerToAsn1(signers[i])); + } + return ret; + } + function _attributeToAsn1(attr) { + var value; + if (attr.type === forge.pki.oids.contentType) { + value = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(attr.value).getBytes() + ); + } else if (attr.type === forge.pki.oids.messageDigest) { + value = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + attr.value.bytes() + ); + } else if (attr.type === forge.pki.oids.signingTime) { + var jan_1_1950 = /* @__PURE__ */ new Date("1950-01-01T00:00:00Z"); + var jan_1_2050 = /* @__PURE__ */ new Date("2050-01-01T00:00:00Z"); + var date = attr.value; + if (typeof date === "string") { + var timestamp = Date.parse(date); + if (!isNaN(timestamp)) { + date = new Date(timestamp); + } else if (date.length === 13) { + date = asn1.utcTimeToDate(date); + } else { + date = asn1.generalizedTimeToDate(date); + } + } + if (date >= jan_1_1950 && date < jan_1_2050) { + value = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.UTCTIME, + false, + asn1.dateToUtcTime(date) + ); + } else { + value = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.GENERALIZEDTIME, + false, + asn1.dateToGeneralizedTime(date) + ); + } + } + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // AttributeType + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(attr.type).getBytes() + ), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ + // AttributeValue + value + ]) + ]); + } + function _encryptedContentToAsn1(ec) { + return [ + // ContentType, always Data for the moment + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(forge.pki.oids.data).getBytes() + ), + // ContentEncryptionAlgorithmIdentifier + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Algorithm + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(ec.algorithm).getBytes() + ), + // Parameters (IV) + !ec.parameter ? void 0 : asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + ec.parameter.getBytes() + ) + ]), + // [0] EncryptedContent + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + ec.content.getBytes() + ) + ]) + ]; + } + function _fromAsn1(msg, obj, validator) { + var capture = {}; + var errors = []; + if (!asn1.validate(obj, validator, capture, errors)) { + var error2 = new Error("Cannot read PKCS#7 message. ASN.1 object is not a supported PKCS#7 message."); + error2.errors = error2; + throw error2; + } + var contentType = asn1.derToOid(capture.contentType); + if (contentType !== forge.pki.oids.data) { + throw new Error("Unsupported PKCS#7 message. Only wrapped ContentType Data supported."); + } + if (capture.encryptedContent) { + var content = ""; + if (forge.util.isArray(capture.encryptedContent)) { + for (var i = 0; i < capture.encryptedContent.length; ++i) { + if (capture.encryptedContent[i].type !== asn1.Type.OCTETSTRING) { + throw new Error("Malformed PKCS#7 message, expecting encrypted content constructed of only OCTET STRING objects."); + } + content += capture.encryptedContent[i].value; + } + } else { + content = capture.encryptedContent; + } + msg.encryptedContent = { + algorithm: asn1.derToOid(capture.encAlgorithm), + parameter: forge.util.createBuffer(capture.encParameter.value), + content: forge.util.createBuffer(content) + }; + } + if (capture.content) { + var content = ""; + if (forge.util.isArray(capture.content)) { + for (var i = 0; i < capture.content.length; ++i) { + if (capture.content[i].type !== asn1.Type.OCTETSTRING) { + throw new Error("Malformed PKCS#7 message, expecting content constructed of only OCTET STRING objects."); + } + content += capture.content[i].value; + } + } else { + content = capture.content; + } + msg.content = forge.util.createBuffer(content); + } + msg.version = capture.version.charCodeAt(0); + msg.rawCapture = capture; + return capture; + } + function _decryptContent(msg) { + if (msg.encryptedContent.key === void 0) { + throw new Error("Symmetric key not available."); + } + if (msg.content === void 0) { + var ciph; + switch (msg.encryptedContent.algorithm) { + case forge.pki.oids["aes128-CBC"]: + case forge.pki.oids["aes192-CBC"]: + case forge.pki.oids["aes256-CBC"]: + ciph = forge.aes.createDecryptionCipher(msg.encryptedContent.key); + break; + case forge.pki.oids["desCBC"]: + case forge.pki.oids["des-EDE3-CBC"]: + ciph = forge.des.createDecryptionCipher(msg.encryptedContent.key); + break; + default: + throw new Error("Unsupported symmetric cipher, OID " + msg.encryptedContent.algorithm); + } + ciph.start(msg.encryptedContent.parameter); + ciph.update(msg.encryptedContent.content); + if (!ciph.finish()) { + throw new Error("Symmetric decryption failed."); + } + msg.content = ciph.output; + } + } + } +}); + +// node_modules/node-forge/lib/ssh.js +var require_ssh2 = __commonJS({ + "node_modules/node-forge/lib/ssh.js"(exports2, module2) { + var forge = require_forge(); + require_aes(); + require_hmac(); + require_md5(); + require_sha1(); + require_util13(); + var ssh = module2.exports = forge.ssh = forge.ssh || {}; + ssh.privateKeyToPutty = function(privateKey, passphrase, comment) { + comment = comment || ""; + passphrase = passphrase || ""; + var algorithm = "ssh-rsa"; + var encryptionAlgorithm = passphrase === "" ? "none" : "aes256-cbc"; + var ppk = "PuTTY-User-Key-File-2: " + algorithm + "\r\n"; + ppk += "Encryption: " + encryptionAlgorithm + "\r\n"; + ppk += "Comment: " + comment + "\r\n"; + var pubbuffer = forge.util.createBuffer(); + _addStringToBuffer(pubbuffer, algorithm); + _addBigIntegerToBuffer(pubbuffer, privateKey.e); + _addBigIntegerToBuffer(pubbuffer, privateKey.n); + var pub = forge.util.encode64(pubbuffer.bytes(), 64); + var length = Math.floor(pub.length / 66) + 1; + ppk += "Public-Lines: " + length + "\r\n"; + ppk += pub; + var privbuffer = forge.util.createBuffer(); + _addBigIntegerToBuffer(privbuffer, privateKey.d); + _addBigIntegerToBuffer(privbuffer, privateKey.p); + _addBigIntegerToBuffer(privbuffer, privateKey.q); + _addBigIntegerToBuffer(privbuffer, privateKey.qInv); + var priv; + if (!passphrase) { + priv = forge.util.encode64(privbuffer.bytes(), 64); + } else { + var encLen = privbuffer.length() + 16 - 1; + encLen -= encLen % 16; + var padding = _sha1(privbuffer.bytes()); + padding.truncate(padding.length() - encLen + privbuffer.length()); + privbuffer.putBuffer(padding); + var aeskey = forge.util.createBuffer(); + aeskey.putBuffer(_sha1("\0\0\0\0", passphrase)); + aeskey.putBuffer(_sha1("\0\0\0", passphrase)); + var cipher = forge.aes.createEncryptionCipher(aeskey.truncate(8), "CBC"); + cipher.start(forge.util.createBuffer().fillWithByte(0, 16)); + cipher.update(privbuffer.copy()); + cipher.finish(); + var encrypted = cipher.output; + encrypted.truncate(16); + priv = forge.util.encode64(encrypted.bytes(), 64); + } + length = Math.floor(priv.length / 66) + 1; + ppk += "\r\nPrivate-Lines: " + length + "\r\n"; + ppk += priv; + var mackey = _sha1("putty-private-key-file-mac-key", passphrase); + var macbuffer = forge.util.createBuffer(); + _addStringToBuffer(macbuffer, algorithm); + _addStringToBuffer(macbuffer, encryptionAlgorithm); + _addStringToBuffer(macbuffer, comment); + macbuffer.putInt32(pubbuffer.length()); + macbuffer.putBuffer(pubbuffer); + macbuffer.putInt32(privbuffer.length()); + macbuffer.putBuffer(privbuffer); + var hmac = forge.hmac.create(); + hmac.start("sha1", mackey); + hmac.update(macbuffer.bytes()); + ppk += "\r\nPrivate-MAC: " + hmac.digest().toHex() + "\r\n"; + return ppk; + }; + ssh.publicKeyToOpenSSH = function(key, comment) { + var type = "ssh-rsa"; + comment = comment || ""; + var buffer = forge.util.createBuffer(); + _addStringToBuffer(buffer, type); + _addBigIntegerToBuffer(buffer, key.e); + _addBigIntegerToBuffer(buffer, key.n); + return type + " " + forge.util.encode64(buffer.bytes()) + " " + comment; + }; + ssh.privateKeyToOpenSSH = function(privateKey, passphrase) { + if (!passphrase) { + return forge.pki.privateKeyToPem(privateKey); + } + return forge.pki.encryptRsaPrivateKey( + privateKey, + passphrase, + { legacy: true, algorithm: "aes128" } + ); + }; + ssh.getPublicKeyFingerprint = function(key, options) { + options = options || {}; + var md2 = options.md || forge.md.md5.create(); + var type = "ssh-rsa"; + var buffer = forge.util.createBuffer(); + _addStringToBuffer(buffer, type); + _addBigIntegerToBuffer(buffer, key.e); + _addBigIntegerToBuffer(buffer, key.n); + md2.start(); + md2.update(buffer.getBytes()); + var digest = md2.digest(); + if (options.encoding === "hex") { + var hex = digest.toHex(); + if (options.delimiter) { + return hex.match(/.{2}/g).join(options.delimiter); + } + return hex; + } else if (options.encoding === "binary") { + return digest.getBytes(); + } else if (options.encoding) { + throw new Error('Unknown encoding "' + options.encoding + '".'); + } + return digest; + }; + function _addBigIntegerToBuffer(buffer, val) { + var hexVal = val.toString(16); + if (hexVal[0] >= "8") { + hexVal = "00" + hexVal; + } + var bytes = forge.util.hexToBytes(hexVal); + buffer.putInt32(bytes.length); + buffer.putBytes(bytes); + } + function _addStringToBuffer(buffer, val) { + buffer.putInt32(val.length); + buffer.putString(val); + } + function _sha1() { + var sha = forge.md.sha1.create(); + var num = arguments.length; + for (var i = 0; i < num; ++i) { + sha.update(arguments[i]); + } + return sha.digest(); + } + } +}); + +// node_modules/node-forge/lib/index.js +var require_lib5 = __commonJS({ + "node_modules/node-forge/lib/index.js"(exports2, module2) { + module2.exports = require_forge(); + require_aes(); + require_aesCipherSuites(); + require_asn1(); + require_cipher(); + require_des(); + require_ed25519(); + require_hmac(); + require_kem(); + require_log(); + require_md_all(); + require_mgf1(); + require_pbkdf2(); + require_pem(); + require_pkcs1(); + require_pkcs12(); + require_pkcs7(); + require_pki(); + require_prime(); + require_prng(); + require_pss(); + require_random(); + require_rc2(); + require_ssh2(); + require_tls(); + require_util13(); + } +}); + +// src/main.ts +var main_exports = {}; +__export(main_exports, { + DependabotErrorType: () => DependabotErrorType, + credentialsFromEnv: () => credentialsFromEnv, + getPackagesCredential: () => getPackagesCredential, + run: () => run +}); +module.exports = __toCommonJS(main_exports); + +// node_modules/@actions/core/lib/command.js +var os = __toESM(require("os"), 1); + +// node_modules/@actions/core/lib/utils.js +function toCommandValue(input) { + if (input === null || input === void 0) { + return ""; + } else if (typeof input === "string" || input instanceof String) { + return input; + } + return JSON.stringify(input); +} +function toCommandProperties(annotationProperties) { + if (!Object.keys(annotationProperties).length) { + return {}; + } + return { + title: annotationProperties.title, + file: annotationProperties.file, + line: annotationProperties.startLine, + endLine: annotationProperties.endLine, + col: annotationProperties.startColumn, + endColumn: annotationProperties.endColumn + }; +} + +// node_modules/@actions/core/lib/command.js +function issueCommand(command, properties, message) { + const cmd = new Command(command, properties, message); + process.stdout.write(cmd.toString() + os.EOL); +} +function issue(name, message = "") { + issueCommand(name, {}, message); +} +var CMD_STRING = "::"; +var Command = class { + constructor(command, properties, message) { + if (!command) { + command = "missing.command"; + } + this.command = command; + this.properties = properties; + this.message = message; + } + toString() { + let cmdStr = CMD_STRING + this.command; + if (this.properties && Object.keys(this.properties).length > 0) { + cmdStr += " "; + let first = true; + for (const key in this.properties) { + if (this.properties.hasOwnProperty(key)) { + const val = this.properties[key]; + if (val) { + if (first) { + first = false; + } else { + cmdStr += ","; + } + cmdStr += `${key}=${escapeProperty(val)}`; + } + } + } + } + cmdStr += `${CMD_STRING}${escapeData(this.message)}`; + return cmdStr; + } +}; +function escapeData(s) { + return toCommandValue(s).replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A"); +} +function escapeProperty(s) { + return toCommandValue(s).replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A").replace(/:/g, "%3A").replace(/,/g, "%2C"); +} + +// node_modules/@actions/core/lib/core.js +var os3 = __toESM(require("os"), 1); + +// node_modules/@actions/http-client/lib/index.js +var http = __toESM(require("http"), 1); +var https = __toESM(require("https"), 1); + +// node_modules/@actions/http-client/lib/proxy.js +function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; + } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; + } + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); + } + } else { + return void 0; + } +} +function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; + } + } + return false; +} +function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); +} +var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; + } +}; + +// node_modules/@actions/http-client/lib/index.js +var tunnel = __toESM(require_tunnel2(), 1); +var import_undici = __toESM(require_undici(), 1); +var __awaiter = function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = 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 HttpCodes; +(function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; +})(HttpCodes || (HttpCodes = {})); +var Headers; +(function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; +})(Headers || (Headers = {})); +var MediaTypes; +(function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; +})(MediaTypes || (MediaTypes = {})); +var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect +]; +var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout +]; +var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; +var ExponentialBackoffCeiling = 10; +var ExponentialBackoffTimeSlice = 5; +var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); + } +}; +var HttpClientResponse = class { + constructor(message) { + this.message = message; + } + readBody() { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve(output.toString()); + }); + })); + }); + } + readBodyBuffer() { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve(Buffer.concat(chunks)); + }); + })); + }); + } +}; +var HttpClient = class { + constructor(userAgent2, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = this._getUserAgentWithOrchestrationId(userAgent2); + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } + } + options(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); + } + get(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); + } + del(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); + } + post(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); + } + patch(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); + } + put(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); + } + head(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); + } + sendStream(verb, requestUrl, stream2, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream2, additionalHeaders); + }); + } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl_1) { + return __awaiter(this, arguments, void 0, function* (requestUrl, additionalHeaders = {}) { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + postJson(requestUrl_1, obj_1) { + return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + putJson(requestUrl_1, obj_1) { + return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl_1, obj_1) { + return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); + } + const parsedUrl = new URL(requestUrl); + let info2 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info2, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler2 of this.handlers) { + if (handler2.canHandleAuthentication(response)) { + authenticationHandler = handler2; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info2, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info2 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info2, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); + } + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info2, data) { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve(res); + } + } + this.requestRawWithCallback(info2, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info2, data, onResult) { + if (typeof data === "string") { + if (!info2.options.headers) { + info2.options.headers = {}; + } + info2.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); + } + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } + } + const req = info2.httpModule.request(info2.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info2.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); + } + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); + } else { + req.end(); + } + } + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); + } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); + } + _prepareRequest(method, requestUrl, headers) { + const info2 = {}; + info2.parsedUrl = requestUrl; + const usingSsl = info2.parsedUrl.protocol === "https:"; + info2.httpModule = usingSsl ? https : http; + const defaultPort = usingSsl ? 443 : 80; + info2.options = {}; + info2.options.host = info2.parsedUrl.hostname; + info2.options.port = info2.parsedUrl.port ? parseInt(info2.parsedUrl.port) : defaultPort; + info2.options.path = (info2.parsedUrl.pathname || "") + (info2.parsedUrl.search || ""); + info2.options.method = method; + info2.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info2.options.headers["user-agent"] = this.userAgent; + } + info2.options.agent = this._getAgent(info2.parsedUrl); + if (this.handlers) { + for (const handler2 of this.handlers) { + handler2.prepareRequest(info2.options); + } + } + return info2; + } + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); + } + /** + * Gets an existing header value or returns a default. + * Handles converting number header values to strings since HTTP headers must be strings. + * Note: This returns string | string[] since some headers can have multiple values. + * For headers that must always be a single string (like Content-Type), use the + * specialized _getExistingOrDefaultContentTypeHeader method instead. + */ + _getExistingOrDefaultHeader(additionalHeaders, header, _default) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + const headerValue = lowercaseKeys(this.requestOptions.headers)[header]; + if (headerValue) { + clientHeader = typeof headerValue === "number" ? headerValue.toString() : headerValue; + } + } + const additionalValue = additionalHeaders[header]; + if (additionalValue !== void 0) { + return typeof additionalValue === "number" ? additionalValue.toString() : additionalValue; + } + if (clientHeader !== void 0) { + return clientHeader; + } + return _default; + } + /** + * Specialized version of _getExistingOrDefaultHeader for Content-Type header. + * Always returns a single string (not an array) since Content-Type should be a single value. + * Converts arrays to comma-separated strings and numbers to strings to ensure type safety. + * This was split from _getExistingOrDefaultHeader to provide stricter typing for callers + * that assign the result to places expecting a string (e.g., additionalHeaders[Headers.ContentType]). + */ + _getExistingOrDefaultContentTypeHeader(additionalHeaders, _default) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + const headerValue = lowercaseKeys(this.requestOptions.headers)[Headers.ContentType]; + if (headerValue) { + if (typeof headerValue === "number") { + clientHeader = String(headerValue); + } else if (Array.isArray(headerValue)) { + clientHeader = headerValue.join(", "); + } else { + clientHeader = headerValue; + } + } + } + const additionalValue = additionalHeaders[Headers.ContentType]; + if (additionalValue !== void 0) { + if (typeof additionalValue === "number") { + return String(additionalValue); + } else if (Array.isArray(additionalValue)) { + return additionalValue.join(", "); + } else { + return additionalValue; + } + } + if (clientHeader !== void 0) { + return clientHeader; + } + return _default; + } + _getAgent(parsedUrl) { + let agent; + const proxyUrl = getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; + } + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new import_undici.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _getUserAgentWithOrchestrationId(userAgent2) { + const baseUserAgent = userAgent2 || "actions/http-client"; + const orchId = process.env["ACTIONS_ORCHESTRATION_ID"]; + if (orchId) { + const sanitizedId = orchId.replace(/[^a-z0-9_.-]/gi, "_"); + return `${baseUserAgent} actions_orchestration_id/${sanitizedId}`; + } + return baseUserAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve) => setTimeout(() => resolve(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve(response); + } + })); + }); + } +}; +var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); + +// node_modules/@actions/core/lib/summary.js +var import_os = require("os"); +var import_fs = require("fs"); +var __awaiter2 = function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = 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 { access, appendFile, writeFile } = import_fs.promises; +var SUMMARY_ENV_VAR = "GITHUB_STEP_SUMMARY"; +var Summary = class { + constructor() { + this._buffer = ""; + } + /** + * Finds the summary file path from the environment, rejects if env var is not found or file does not exist + * Also checks r/w permissions. + * + * @returns step summary file path + */ + filePath() { + return __awaiter2(this, void 0, void 0, function* () { + if (this._filePath) { + return this._filePath; + } + const pathFromEnv = process.env[SUMMARY_ENV_VAR]; + if (!pathFromEnv) { + throw new Error(`Unable to find environment variable for $${SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); + } + try { + yield access(pathFromEnv, import_fs.constants.R_OK | import_fs.constants.W_OK); + } catch (_a) { + throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); + } + this._filePath = pathFromEnv; + return this._filePath; + }); + } + /** + * Wraps content in an HTML tag, adding any HTML attributes + * + * @param {string} tag HTML tag to wrap + * @param {string | null} content content within the tag + * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add + * + * @returns {string} content wrapped in HTML element + */ + wrap(tag, content, attrs = {}) { + const htmlAttrs = Object.entries(attrs).map(([key, value]) => ` ${key}="${value}"`).join(""); + if (!content) { + return `<${tag}${htmlAttrs}>`; + } + return `<${tag}${htmlAttrs}>${content}`; + } + /** + * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default. + * + * @param {SummaryWriteOptions} [options] (optional) options for write operation + * + * @returns {Promise} summary instance + */ + write(options) { + return __awaiter2(this, void 0, void 0, function* () { + const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); + const filePath = yield this.filePath(); + const writeFunc = overwrite ? writeFile : appendFile; + yield writeFunc(filePath, this._buffer, { encoding: "utf8" }); + return this.emptyBuffer(); + }); + } + /** + * Clears the summary buffer and wipes the summary file + * + * @returns {Summary} summary instance + */ + clear() { + return __awaiter2(this, void 0, void 0, function* () { + return this.emptyBuffer().write({ overwrite: true }); + }); + } + /** + * Returns the current summary buffer as a string + * + * @returns {string} string of summary buffer + */ + stringify() { + return this._buffer; + } + /** + * If the summary buffer is empty + * + * @returns {boolen} true if the buffer is empty + */ + isEmptyBuffer() { + return this._buffer.length === 0; + } + /** + * Resets the summary buffer without writing to summary file + * + * @returns {Summary} summary instance + */ + emptyBuffer() { + this._buffer = ""; + return this; + } + /** + * Adds raw text to the summary buffer + * + * @param {string} text content to add + * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false) + * + * @returns {Summary} summary instance + */ + addRaw(text, addEOL = false) { + this._buffer += text; + return addEOL ? this.addEOL() : this; + } + /** + * Adds the operating system-specific end-of-line marker to the buffer + * + * @returns {Summary} summary instance + */ + addEOL() { + return this.addRaw(import_os.EOL); + } + /** + * Adds an HTML codeblock to the summary buffer + * + * @param {string} code content to render within fenced code block + * @param {string} lang (optional) language to syntax highlight code + * + * @returns {Summary} summary instance + */ + addCodeBlock(code, lang) { + const attrs = Object.assign({}, lang && { lang }); + const element = this.wrap("pre", this.wrap("code", code), attrs); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML list to the summary buffer + * + * @param {string[]} items list of items to render + * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false) + * + * @returns {Summary} summary instance + */ + addList(items, ordered = false) { + const tag = ordered ? "ol" : "ul"; + const listItems = items.map((item) => this.wrap("li", item)).join(""); + const element = this.wrap(tag, listItems); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML table to the summary buffer + * + * @param {SummaryTableCell[]} rows table rows + * + * @returns {Summary} summary instance + */ + addTable(rows) { + const tableBody = rows.map((row) => { + const cells = row.map((cell) => { + if (typeof cell === "string") { + return this.wrap("td", cell); + } + const { header, data, colspan, rowspan } = cell; + const tag = header ? "th" : "td"; + const attrs = Object.assign(Object.assign({}, colspan && { colspan }), rowspan && { rowspan }); + return this.wrap(tag, data, attrs); + }).join(""); + return this.wrap("tr", cells); + }).join(""); + const element = this.wrap("table", tableBody); + return this.addRaw(element).addEOL(); + } + /** + * Adds a collapsable HTML details element to the summary buffer + * + * @param {string} label text for the closed state + * @param {string} content collapsable content + * + * @returns {Summary} summary instance + */ + addDetails(label, content) { + const element = this.wrap("details", this.wrap("summary", label) + content); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML image tag to the summary buffer + * + * @param {string} src path to the image you to embed + * @param {string} alt text description of the image + * @param {SummaryImageOptions} options (optional) addition image attributes + * + * @returns {Summary} summary instance + */ + addImage(src, alt, options) { + const { width, height } = options || {}; + const attrs = Object.assign(Object.assign({}, width && { width }), height && { height }); + const element = this.wrap("img", null, Object.assign({ src, alt }, attrs)); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML section heading element + * + * @param {string} text heading text + * @param {number | string} [level=1] (optional) the heading level, default: 1 + * + * @returns {Summary} summary instance + */ + addHeading(text, level) { + const tag = `h${level}`; + const allowedTag = ["h1", "h2", "h3", "h4", "h5", "h6"].includes(tag) ? tag : "h1"; + const element = this.wrap(allowedTag, text); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML thematic break (
) to the summary buffer + * + * @returns {Summary} summary instance + */ + addSeparator() { + const element = this.wrap("hr", null); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML line break (
) to the summary buffer + * + * @returns {Summary} summary instance + */ + addBreak() { + const element = this.wrap("br", null); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML blockquote to the summary buffer + * + * @param {string} text quote text + * @param {string} cite (optional) citation url + * + * @returns {Summary} summary instance + */ + addQuote(text, cite) { + const attrs = Object.assign({}, cite && { cite }); + const element = this.wrap("blockquote", text, attrs); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML anchor tag to the summary buffer + * + * @param {string} text link text/content + * @param {string} href hyperlink + * + * @returns {Summary} summary instance + */ + addLink(text, href) { + const element = this.wrap("a", text, { href }); + return this.addRaw(element).addEOL(); + } +}; +var _summary = new Summary(); + +// node_modules/@actions/core/lib/platform.js +var import_os2 = __toESM(require("os"), 1); + +// node_modules/@actions/io/lib/io-util.js +var fs = __toESM(require("fs"), 1); +var { chmod, copyFile, lstat, mkdir, open, readdir, rename, rm, rmdir, stat, symlink, unlink } = fs.promises; +var IS_WINDOWS = process.platform === "win32"; +var READONLY = fs.constants.O_RDONLY; + +// node_modules/@actions/exec/lib/toolrunner.js +var IS_WINDOWS2 = process.platform === "win32"; + +// node_modules/@actions/core/lib/platform.js +var platform = import_os2.default.platform(); +var arch = import_os2.default.arch(); + +// node_modules/@actions/core/lib/core.js +var ExitCode; +(function(ExitCode2) { + ExitCode2[ExitCode2["Success"] = 0] = "Success"; + ExitCode2[ExitCode2["Failure"] = 1] = "Failure"; +})(ExitCode || (ExitCode = {})); +function setSecret(secret) { + issueCommand("add-mask", {}, secret); +} +function setFailed(message) { + process.exitCode = ExitCode.Failure; + error(message); +} +function debug(message) { + issueCommand("debug", {}, message); +} +function error(message, properties = {}) { + issueCommand("error", toCommandProperties(properties), message instanceof Error ? message.toString() : message); +} +function warning(message, properties = {}) { + issueCommand("warning", toCommandProperties(properties), message instanceof Error ? message.toString() : message); +} +function info(message) { + process.stdout.write(message + os3.EOL); +} +function startGroup(name) { + issue("group", name); +} +function endGroup() { + issue("endgroup"); +} + +// node_modules/@actions/github/lib/context.js +var import_fs2 = require("fs"); +var import_os3 = require("os"); +var Context = class { + /** + * Hydrate the context from the environment + */ + constructor() { + var _a, _b, _c; + this.payload = {}; + if (process.env.GITHUB_EVENT_PATH) { + if ((0, import_fs2.existsSync)(process.env.GITHUB_EVENT_PATH)) { + this.payload = JSON.parse((0, import_fs2.readFileSync)(process.env.GITHUB_EVENT_PATH, { encoding: "utf8" })); + } else { + const path = process.env.GITHUB_EVENT_PATH; + process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${import_os3.EOL}`); + } + } + this.eventName = process.env.GITHUB_EVENT_NAME; + this.sha = process.env.GITHUB_SHA; + this.ref = process.env.GITHUB_REF; + this.workflow = process.env.GITHUB_WORKFLOW; + this.action = process.env.GITHUB_ACTION; + this.actor = process.env.GITHUB_ACTOR; + this.job = process.env.GITHUB_JOB; + this.runAttempt = parseInt(process.env.GITHUB_RUN_ATTEMPT, 10); + this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10); + this.runId = parseInt(process.env.GITHUB_RUN_ID, 10); + this.apiUrl = (_a = process.env.GITHUB_API_URL) !== null && _a !== void 0 ? _a : `https://api.github.com`; + this.serverUrl = (_b = process.env.GITHUB_SERVER_URL) !== null && _b !== void 0 ? _b : `https://github.com`; + this.graphqlUrl = (_c = process.env.GITHUB_GRAPHQL_URL) !== null && _c !== void 0 ? _c : `https://api.github.com/graphql`; + } + get issue() { + const payload = this.payload; + return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number }); + } + get repo() { + if (process.env.GITHUB_REPOSITORY) { + const [owner, repo] = process.env.GITHUB_REPOSITORY.split("/"); + return { owner, repo }; + } + if (this.payload.repository) { + return { + owner: this.payload.repository.owner.login, + repo: this.payload.repository.name + }; + } + throw new Error("context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'"); + } +}; + +// node_modules/@actions/github/lib/internal/utils.js +var httpClient = __toESM(require_lib(), 1); +var import_undici2 = __toESM(require_undici(), 1); +var __awaiter3 = function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = 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 getProxyAgent(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgent(destinationUrl); +} +function getProxyAgentDispatcher(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgentDispatcher(destinationUrl); +} +function getProxyFetch(destinationUrl) { + const httpDispatcher = getProxyAgentDispatcher(destinationUrl); + const proxyFetch = (url, opts) => __awaiter3(this, void 0, void 0, function* () { + return (0, import_undici2.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); + }); + return proxyFetch; +} +function getApiBaseUrl() { + return process.env["GITHUB_API_URL"] || "https://api.github.com"; +} + +// node_modules/universal-user-agent/index.js +function getUserAgent() { + if (typeof navigator === "object" && "userAgent" in navigator) { + return navigator.userAgent; + } + if (typeof process === "object" && process.version !== void 0) { + return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; + } + return ""; +} + +// node_modules/before-after-hook/lib/register.js +function register(state, name, method, options) { + if (typeof method !== "function") { + throw new Error("method for before hook must be a function"); + } + if (!options) { + options = {}; + } + if (Array.isArray(name)) { + return name.reverse().reduce((callback, name2) => { + return register.bind(null, state, name2, callback, options); + }, method)(); + } + return Promise.resolve().then(() => { + if (!state.registry[name]) { + return method(options); + } + return state.registry[name].reduce((method2, registered) => { + return registered.hook.bind(null, method2, options); + }, method)(); + }); +} + +// node_modules/before-after-hook/lib/add.js +function addHook(state, kind, name, hook2) { + const orig = hook2; + if (!state.registry[name]) { + state.registry[name] = []; + } + if (kind === "before") { + hook2 = (method, options) => { + return Promise.resolve().then(orig.bind(null, options)).then(method.bind(null, options)); + }; + } + if (kind === "after") { + hook2 = (method, options) => { + let result; + return Promise.resolve().then(method.bind(null, options)).then((result_) => { + result = result_; + return orig(result, options); + }).then(() => { + return result; + }); + }; + } + if (kind === "error") { + hook2 = (method, options) => { + return Promise.resolve().then(method.bind(null, options)).catch((error2) => { + return orig(error2, options); + }); + }; + } + state.registry[name].push({ + hook: hook2, + orig + }); +} + +// node_modules/before-after-hook/lib/remove.js +function removeHook(state, name, method) { + if (!state.registry[name]) { + return; + } + const index = state.registry[name].map((registered) => { + return registered.orig; + }).indexOf(method); + if (index === -1) { + return; + } + state.registry[name].splice(index, 1); +} + +// node_modules/before-after-hook/index.js +var bind = Function.bind; +var bindable = bind.bind(bind); +function bindApi(hook2, state, name) { + const removeHookRef = bindable(removeHook, null).apply( + null, + name ? [state, name] : [state] + ); + hook2.api = { remove: removeHookRef }; + hook2.remove = removeHookRef; + ["before", "error", "after", "wrap"].forEach((kind) => { + const args = name ? [state, kind, name] : [state, kind]; + hook2[kind] = hook2.api[kind] = bindable(addHook, null).apply(null, args); + }); +} +function Singular() { + const singularHookName = /* @__PURE__ */ Symbol("Singular"); + const singularHookState = { + registry: {} + }; + const singularHook = register.bind(null, singularHookState, singularHookName); + bindApi(singularHook, singularHookState, singularHookName); + return singularHook; +} +function Collection() { + const state = { + registry: {} + }; + const hook2 = register.bind(null, state); + bindApi(hook2, state); + return hook2; +} +var before_after_hook_default = { Singular, Collection }; + +// node_modules/@octokit/endpoint/dist-bundle/index.js +var VERSION = "0.0.0-development"; +var userAgent = `octokit-endpoint.js/${VERSION} ${getUserAgent()}`; +var DEFAULTS = { + method: "GET", + baseUrl: "https://api.github.com", + headers: { + accept: "application/vnd.github.v3+json", + "user-agent": userAgent }, - oidc: { - getOidcCustomSubTemplateForOrg: [ - "GET /orgs/{org}/actions/oidc/customization/sub" - ], - updateOidcCustomSubTemplateForOrg: [ - "PUT /orgs/{org}/actions/oidc/customization/sub" - ] + mediaType: { + format: "" + } +}; +function lowercaseKeys2(object) { + if (!object) { + return {}; + } + return Object.keys(object).reduce((newObj, key) => { + newObj[key.toLowerCase()] = object[key]; + return newObj; + }, {}); +} +function isPlainObject(value) { + if (typeof value !== "object" || value === null) return false; + if (Object.prototype.toString.call(value) !== "[object Object]") return false; + const proto = Object.getPrototypeOf(value); + if (proto === null) return true; + const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor; + return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value); +} +function mergeDeep(defaults2, options) { + const result = Object.assign({}, defaults2); + Object.keys(options).forEach((key) => { + if (isPlainObject(options[key])) { + if (!(key in defaults2)) Object.assign(result, { [key]: options[key] }); + else result[key] = mergeDeep(defaults2[key], options[key]); + } else { + Object.assign(result, { [key]: options[key] }); + } + }); + return result; +} +function removeUndefinedProperties(obj) { + for (const key in obj) { + if (obj[key] === void 0) { + delete obj[key]; + } + } + return obj; +} +function merge(defaults2, route, options) { + if (typeof route === "string") { + let [method, url] = route.split(" "); + options = Object.assign(url ? { method, url } : { url: method }, options); + } else { + options = Object.assign({}, route); + } + options.headers = lowercaseKeys2(options.headers); + removeUndefinedProperties(options); + removeUndefinedProperties(options.headers); + const mergedOptions = mergeDeep(defaults2 || {}, options); + if (options.url === "/graphql") { + if (defaults2 && defaults2.mediaType.previews?.length) { + mergedOptions.mediaType.previews = defaults2.mediaType.previews.filter( + (preview) => !mergedOptions.mediaType.previews.includes(preview) + ).concat(mergedOptions.mediaType.previews); + } + mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, "")); + } + return mergedOptions; +} +function addQueryParameters(url, parameters) { + const separator = /\?/.test(url) ? "&" : "?"; + const names = Object.keys(parameters); + if (names.length === 0) { + return url; + } + return url + separator + names.map((name) => { + if (name === "q") { + return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); + } + return `${name}=${encodeURIComponent(parameters[name])}`; + }).join("&"); +} +var urlVariableRegex = /\{[^{}}]+\}/g; +function removeNonChars(variableName) { + return variableName.replace(/(?:^\W+)|(?:(? a.concat(b), []); +} +function omit(object, keysToOmit) { + const result = { __proto__: null }; + for (const key of Object.keys(object)) { + if (keysToOmit.indexOf(key) === -1) { + result[key] = object[key]; + } + } + return result; +} +function encodeReserved(str) { + return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) { + if (!/%[0-9A-Fa-f]/.test(part)) { + part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); + } + return part; + }).join(""); +} +function encodeUnreserved(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); + }); +} +function encodeValue(operator, value, key) { + value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); + if (key) { + return encodeUnreserved(key) + "=" + value; + } else { + return value; + } +} +function isDefined(value) { + return value !== void 0 && value !== null; +} +function isKeyOperator(operator) { + return operator === ";" || operator === "&" || operator === "?"; +} +function getValues(context3, operator, key, modifier) { + var value = context3[key], result = []; + if (isDefined(value) && value !== "") { + if (typeof value === "string" || typeof value === "number" || typeof value === "bigint" || typeof value === "boolean") { + value = value.toString(); + if (modifier && modifier !== "*") { + value = value.substring(0, parseInt(modifier, 10)); + } + result.push( + encodeValue(operator, value, isKeyOperator(operator) ? key : "") + ); + } else { + if (modifier === "*") { + if (Array.isArray(value)) { + value.filter(isDefined).forEach(function(value2) { + result.push( + encodeValue(operator, value2, isKeyOperator(operator) ? key : "") + ); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined(value[k])) { + result.push(encodeValue(operator, value[k], k)); + } + }); + } + } else { + const tmp = []; + if (Array.isArray(value)) { + value.filter(isDefined).forEach(function(value2) { + tmp.push(encodeValue(operator, value2)); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined(value[k])) { + tmp.push(encodeUnreserved(k)); + tmp.push(encodeValue(operator, value[k].toString())); + } + }); + } + if (isKeyOperator(operator)) { + result.push(encodeUnreserved(key) + "=" + tmp.join(",")); + } else if (tmp.length !== 0) { + result.push(tmp.join(",")); + } + } + } + } else { + if (operator === ";") { + if (isDefined(value)) { + result.push(encodeUnreserved(key)); + } + } else if (value === "" && (operator === "&" || operator === "?")) { + result.push(encodeUnreserved(key) + "="); + } else if (value === "") { + result.push(""); + } + } + return result; +} +function parseUrl(template) { + return { + expand: expand.bind(null, template) + }; +} +function expand(template, context3) { + var operators = ["+", "#", ".", "/", ";", "?", "&"]; + template = template.replace( + /\{([^\{\}]+)\}|([^\{\}]+)/g, + function(_, expression, literal) { + if (expression) { + let operator = ""; + const values = []; + if (operators.indexOf(expression.charAt(0)) !== -1) { + operator = expression.charAt(0); + expression = expression.substr(1); + } + expression.split(/,/g).forEach(function(variable) { + var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); + values.push(getValues(context3, operator, tmp[1], tmp[2] || tmp[3])); + }); + if (operator && operator !== "+") { + var separator = ","; + if (operator === "?") { + separator = "&"; + } else if (operator !== "#") { + separator = operator; + } + return (values.length !== 0 ? operator : "") + values.join(separator); + } else { + return values.join(","); + } + } else { + return encodeReserved(literal); + } + } + ); + if (template === "/") { + return template; + } else { + return template.replace(/\/$/, ""); + } +} +function parse(options) { + let method = options.method.toUpperCase(); + let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); + let headers = Object.assign({}, options.headers); + let body; + let parameters = omit(options, [ + "method", + "baseUrl", + "url", + "headers", + "request", + "mediaType" + ]); + const urlVariableNames = extractUrlVariableNames(url); + url = parseUrl(url).expand(parameters); + if (!/^http/.test(url)) { + url = options.baseUrl + url; + } + const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl"); + const remainingParameters = omit(parameters, omittedParameters); + const isBinaryRequest = /application\/octet-stream/i.test(headers.accept); + if (!isBinaryRequest) { + if (options.mediaType.format) { + headers.accept = headers.accept.split(/,/).map( + (format) => format.replace( + /application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, + `application/vnd$1$2.${options.mediaType.format}` + ) + ).join(","); + } + if (url.endsWith("/graphql")) { + if (options.mediaType.previews?.length) { + const previewsFromAcceptHeader = headers.accept.match(/(? { + const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; + return `application/vnd.github.${preview}-preview${format}`; + }).join(","); + } + } + } + if (["GET", "HEAD"].includes(method)) { + url = addQueryParameters(url, remainingParameters); + } else { + if ("data" in remainingParameters) { + body = remainingParameters.data; + } else { + if (Object.keys(remainingParameters).length) { + body = remainingParameters; + } + } + } + if (!headers["content-type"] && typeof body !== "undefined") { + headers["content-type"] = "application/json; charset=utf-8"; + } + if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { + body = ""; + } + return Object.assign( + { method, url, headers }, + typeof body !== "undefined" ? { body } : null, + options.request ? { request: options.request } : null + ); +} +function endpointWithDefaults(defaults2, route, options) { + return parse(merge(defaults2, route, options)); +} +function withDefaults(oldDefaults, newDefaults) { + const DEFAULTS2 = merge(oldDefaults, newDefaults); + const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2); + return Object.assign(endpoint2, { + DEFAULTS: DEFAULTS2, + defaults: withDefaults.bind(null, DEFAULTS2), + merge: merge.bind(null, DEFAULTS2), + parse + }); +} +var endpoint = withDefaults(null, DEFAULTS); + +// node_modules/@octokit/request/node_modules/content-type/dist/index.js +var NullObject = /* @__PURE__ */ (() => { + const C = function() { + }; + C.prototype = /* @__PURE__ */ Object.create(null); + return C; +})(); +function parse2(header, options) { + const stopChar = options?.comma === true ? COMMA : 65536; + const len = header.length; + let index = skipOWS(header, options?.start ?? 0, len); + const valueStart = index; + index = skipValue(header, index, len, stopChar); + const valueEnd = trailingOWS(header, valueStart, index); + const type = header.slice(valueStart, valueEnd).toLowerCase(); + if (options?.parameters === false) { + return { type, index, parameters: new NullObject() }; + } + return parseParameters(header, type, index, len, stopChar); +} +var SP = 32; +var HTAB = 9; +var SEMI = 59; +var EQ = 61; +var DQUOTE = 34; +var BSLASH = 92; +var COMMA = 44; +function parseParameters(header, type, index, len, stopChar) { + const parameters = new NullObject(); + parameter: while (index < len) { + if (header.charCodeAt(index) === stopChar) + break; + index = skipOWS(header, index + 1, len); + const keyStart = index; + while (index < len) { + const code = header.charCodeAt(index); + if (code === stopChar) + break parameter; + if (code === SEMI) + continue parameter; + if (code === EQ) { + const keyEnd = trailingOWS(header, keyStart, index); + const key = header.slice(keyStart, keyEnd).toLowerCase(); + index = skipOWS(header, index + 1, len); + if (index < len && header.charCodeAt(index) === DQUOTE) { + index++; + let value = ""; + while (index < len) { + const code2 = header.charCodeAt(index++); + if (code2 === DQUOTE) { + index = skipValue(header, index, len, stopChar); + if (parameters[key] === void 0) + parameters[key] = value; + break; + } + if (code2 === BSLASH && index < len) { + value += header[index++]; + continue; + } + value += String.fromCharCode(code2); + } + continue parameter; + } + const valueStart = index; + index = skipValue(header, index, len, stopChar); + if (parameters[key] === void 0) { + const valueEnd = trailingOWS(header, valueStart, index); + parameters[key] = header.slice(valueStart, valueEnd); + } + continue parameter; + } + index++; + } + } + return { type, index, parameters }; +} +function skipValue(str, index, len, stopChar) { + while (index < len) { + const code = str.charCodeAt(index); + if (code === SEMI || code === stopChar) + break; + index++; + } + return index; +} +function skipOWS(header, index, len) { + while (index < len) { + const char = header.charCodeAt(index); + if (char !== SP && char !== HTAB) + break; + index++; + } + return index; +} +function trailingOWS(header, start, end) { + while (end > start) { + const char = header.charCodeAt(end - 1); + if (char !== SP && char !== HTAB) + break; + end--; + } + return end; +} + +// node_modules/json-with-bigint/json-with-bigint.js +var intRegex = /^-?\d+$/; +var noiseValue = /^-?\d+n+$/; +var originalStringify = JSON.stringify; +var originalParse = JSON.parse; +var customFormat = /^-?\d+n$/; +var bigIntsStringify = /([\[:])?"(-?\d+)n"($|\s*[,\}\]])/g; +var noiseStringify = /([\[:])?("-?\d+n+)n("$|"\s*[,\}\]])/g; +var isUnstringifiable = (val) => val === void 0 || typeof val === "function" || typeof val === "symbol"; +var isRawJSON = (val) => val !== null && typeof val === "object" && val.constructor && val.constructor.name === "RawJSON"; +var stringifyIteratively = (rootValue, replacer, spaceParam) => { + let space = ""; + if (typeof spaceParam === "number") { + space = " ".repeat(Math.min(10, Math.max(0, Math.floor(spaceParam)))); + } else if (typeof spaceParam === "string") { + space = spaceParam.slice(0, 10); + } + const isFunctionReplacer = typeof replacer === "function"; + const propertyList = Array.isArray(replacer) ? new Set(replacer.map(String)) : null; + const prepareVal = (parent, key, val) => { + const isObject = val !== null && typeof val === "object"; + const hasToJSON = isObject && typeof val.toJSON === "function"; + if (hasToJSON) { + val = val.toJSON(key); + } + const isNoise = typeof val === "string" && noiseValue.test(val); + if (isNoise) return val + "n"; + const isBigInt = typeof val === "bigint"; + if (isBigInt) { + const supportsRawJSON = "rawJSON" in JSON; + if (supportsRawJSON) return JSON.rawJSON(val.toString()); + return val.toString() + "n"; + } + if (isFunctionReplacer) { + val = replacer.call(parent, key, val); + } + const isPostReplacerObject = val !== null && typeof val === "object"; + if (isPostReplacerObject) { + const isPrimitiveWrapper = val instanceof Number || val instanceof String || val instanceof Boolean; + if (isPrimitiveWrapper) { + val = val.valueOf(); + } + } + return val; + }; + const rootProcessed = prepareVal({ "": rootValue }, "", rootValue); + if (isUnstringifiable(rootProcessed)) { + return void 0; + } + const isRootPrimitive = rootProcessed === null || typeof rootProcessed !== "object"; + const isRootNativeRawJSON = isRawJSON(rootProcessed); + if (isRootPrimitive || isRootNativeRawJSON) { + return originalStringify(rootProcessed); + } + const chunks = []; + let level = 0; + const stack = [ + { + parent: { "": rootProcessed }, + key: "", + val: rootProcessed, + isArray: Array.isArray(rootProcessed), + keys: Array.isArray(rootProcessed) ? null : Object.keys(rootProcessed), + index: 0, + first: true + } + ]; + const visited = new WeakSet([rootProcessed]); + while (stack.length > 0) { + const node = stack[stack.length - 1]; + if (node.index === 0) { + chunks.push(node.isArray ? "[" : "{"); + level++; + } + let isDone = false; + if (node.isArray) { + if (node.index < node.val.length) { + if (!node.first) chunks.push(","); + if (space) chunks.push("\n" + space.repeat(level)); + const childRaw = node.val[node.index]; + const childVal = prepareVal(node.val, String(node.index), childRaw); + if (isUnstringifiable(childVal)) { + chunks.push("null"); + node.first = false; + node.index++; + } else { + const isComplexObject = childVal !== null && typeof childVal === "object"; + const isNativeRaw = isRawJSON(childVal); + if (isComplexObject && !isNativeRaw) { + if (visited.has(childVal)) { + throw new TypeError("Converting circular structure to JSON"); + } + visited.add(childVal); + stack.push({ + parent: node.val, + key: String(node.index), + val: childVal, + isArray: Array.isArray(childVal), + keys: Array.isArray(childVal) ? null : Object.keys(childVal), + index: 0, + first: true + }); + node.first = false; + node.index++; + } else { + chunks.push(originalStringify(childVal)); + node.first = false; + node.index++; + } + } + } else { + isDone = true; + } + } else { + while (node.index < node.keys.length) { + const k = node.keys[node.index++]; + const isFilteredOutByArray = propertyList && !propertyList.has(k); + if (isFilteredOutByArray) continue; + const childRaw = node.val[k]; + const childVal = prepareVal(node.val, k, childRaw); + if (isUnstringifiable(childVal)) continue; + if (!node.first) chunks.push(","); + if (space) { + chunks.push("\n" + space.repeat(level) + originalStringify(k) + ": "); + } else { + chunks.push(originalStringify(k) + ":"); + } + const isComplexObject = childVal !== null && typeof childVal === "object"; + const isNativeRaw = isRawJSON(childVal); + if (isComplexObject && !isNativeRaw) { + if (visited.has(childVal)) { + throw new TypeError("Converting circular structure to JSON"); + } + visited.add(childVal); + stack.push({ + parent: node.val, + key: k, + val: childVal, + isArray: Array.isArray(childVal), + keys: Array.isArray(childVal) ? null : Object.keys(childVal), + index: 0, + first: true + }); + node.first = false; + break; + } else { + chunks.push(originalStringify(childVal)); + node.first = false; + } + } + const isNodeFullyProcessed = node.index >= node.keys.length && stack[stack.length - 1] === node; + if (isNodeFullyProcessed) { + isDone = true; + } + } + if (isDone) { + level--; + if (!node.first && space) chunks.push("\n" + space.repeat(level)); + chunks.push(node.isArray ? "]" : "}"); + visited.delete(node.val); + stack.pop(); + } + } + return chunks.join(""); +}; +var JSONStringify = (value, replacer, space) => { + try { + const supportsRawJSON = "rawJSON" in JSON; + if (supportsRawJSON) { + return originalStringify( + value, + (key, val) => { + if (typeof val === "bigint") return JSON.rawJSON(val.toString()); + const hasFunctionReplacer = typeof replacer === "function"; + if (hasFunctionReplacer) return replacer(key, val); + const isKeyInArrayReplacer = Array.isArray(replacer) && replacer.includes(key); + if (isKeyInArrayReplacer) return val; + return val; + }, + space + ); + } + if (!value) return originalStringify(value, replacer, space); + const convertedToCustomJSON = originalStringify( + value, + (key, val) => { + const isNoise = typeof val === "string" && noiseValue.test(val); + if (isNoise) return val.toString() + "n"; + if (typeof val === "bigint") return val.toString() + "n"; + const hasFunctionReplacer = typeof replacer === "function"; + if (hasFunctionReplacer) return replacer(key, val); + const isKeyInArrayReplacer = Array.isArray(replacer) && replacer.includes(key); + if (isKeyInArrayReplacer) return val; + return val; + }, + space + ); + const processedJSON = convertedToCustomJSON.replace( + bigIntsStringify, + "$1$2$3" + ); + const denoisedJSON = processedJSON.replace(noiseStringify, "$1$2$3"); + return denoisedJSON; + } catch (error2) { + if (error2 instanceof RangeError) { + const convertedJSON = stringifyIteratively(value, replacer, space); + if (convertedJSON === void 0) return void 0; + const supportsRawJSON = "rawJSON" in JSON; + if (supportsRawJSON) return convertedJSON; + const processedJSON = convertedJSON.replace(bigIntsStringify, "$1$2$3"); + return processedJSON.replace(noiseStringify, "$1$2$3"); + } + throw error2; + } +}; +var featureCache = /* @__PURE__ */ new Map(); +var isContextSourceSupported = () => { + const parseFingerprint = JSON.parse.toString(); + if (featureCache.has(parseFingerprint)) { + return featureCache.get(parseFingerprint); + } + try { + const result = JSON.parse( + "1", + (_, __, context3) => !!context3?.source && context3.source === "1" + ); + featureCache.set(parseFingerprint, result); + return result; + } catch { + featureCache.set(parseFingerprint, false); + return false; + } +}; +var convertMarkedBigIntsReviver = (key, value, context3, userReviver) => { + const isCustomFormatBigInt = typeof value === "string" && customFormat.test(value); + if (isCustomFormatBigInt) return BigInt(value.slice(0, -1)); + const isNoiseValue = typeof value === "string" && noiseValue.test(value); + if (isNoiseValue) return value.slice(0, -1); + const hasUserReviver = typeof userReviver === "function"; + if (!hasUserReviver) return value; + return userReviver(key, value, context3); +}; +var JSONParseV2 = (text, reviver) => { + return JSON.parse(text, (key, value, context3) => { + const isNumber = typeof value === "number"; + const isOutOfBounds = value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER; + const isBigNumber = isNumber && isOutOfBounds; + const isInt = context3 && intRegex.test(context3.source); + const isBigInt = isBigNumber && isInt; + if (isBigInt) return BigInt(context3.source); + const hasCustomReviver = typeof reviver === "function"; + if (!hasCustomReviver) return value; + return reviver(key, value, context3); + }); +}; +var MAX_INT = Number.MAX_SAFE_INTEGER.toString(); +var MAX_DIGITS = MAX_INT.length; +var stringsOrLargeNumbers = /"(?:[^"\\]|\\.)*"|-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/g; +var noiseValueWithQuotes = /^"-?\d+n+"$/; +var applyReviverIteratively = (parsed, userReviver) => { + const rootHolder = { "": parsed }; + const stack = [{ parent: rootHolder, key: "", visited: false }]; + while (stack.length > 0) { + const node = stack[stack.length - 1]; + if (!node.visited) { + node.visited = true; + const value = node.parent[node.key]; + const isComplexObject = value !== null && typeof value === "object"; + if (isComplexObject) { + const keys = Object.keys(value); + for (let i = keys.length - 1; i >= 0; i--) { + stack.push({ parent: value, key: keys[i], visited: false }); + } + } + } else { + const { parent, key } = node; + let value = parent[key]; + if (typeof value === "string") { + const isCustomFormatBigInt = customFormat.test(value); + if (isCustomFormatBigInt) { + value = BigInt(value.slice(0, -1)); + } else { + const isNoise = noiseValue.test(value); + if (isNoise) value = value.slice(0, -1); + } + } + const hasUserReviver = typeof userReviver === "function"; + if (hasUserReviver) { + value = userReviver.call(parent, key, value); + } + const isDeleted = value === void 0; + if (isDeleted) { + delete parent[key]; + } else { + parent[key] = value; + } + stack.pop(); + } + } + return rootHolder[""]; +}; +var serializeBigInts = (text) => { + return text.replace( + stringsOrLargeNumbers, + (match, digits, fractional, exponential) => { + const isString = match[0] === '"'; + const isNoise = isString && noiseValueWithQuotes.test(match); + if (isNoise) return match.substring(0, match.length - 1) + 'n"'; + const hasFractionalOrExponential = fractional || exponential; + const isLessThanMaxSafeInt = digits && (digits.length < MAX_DIGITS || digits.length === MAX_DIGITS && digits <= MAX_INT); + const isStandardValue = isString || hasFractionalOrExponential || isLessThanMaxSafeInt; + if (isStandardValue) return match; + return '"' + match + 'n"'; + } + ); +}; +var JSONParse = (text, reviver) => { + if (!text) return originalParse(text, reviver); + try { + if (isContextSourceSupported()) return JSONParseV2(text, reviver); + const serializedData = serializeBigInts(text); + return originalParse( + serializedData, + (key, value, context3) => convertMarkedBigIntsReviver(key, value, context3, reviver) + ); + } catch (error2) { + if (error2 instanceof RangeError) { + const serializedData = serializeBigInts(text); + const parsed = originalParse(serializedData); + return applyReviverIteratively(parsed, reviver); + } + throw error2; + } +}; + +// node_modules/@octokit/request-error/dist-src/index.js +var RequestError = class extends Error { + name; + /** + * http status code + */ + status; + /** + * Request options that lead to the error. + */ + request; + /** + * Response object if a response was received + */ + response; + constructor(message, statusCode, options) { + super(message, { cause: options.cause }); + this.name = "HttpError"; + this.status = Number.parseInt(statusCode); + if (Number.isNaN(this.status)) { + this.status = 0; + } + if ("response" in options) { + this.response = options.response; + } + const requestCopy = Object.assign({}, options.request); + if (options.request.headers.authorization) { + requestCopy.headers = Object.assign({}, options.request.headers, { + authorization: options.request.headers.authorization.replace( + /(? ""; +async function fetchWrapper(requestOptions) { + const fetch3 = requestOptions.request?.fetch || globalThis.fetch; + if (!fetch3) { + throw new Error( + "fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing" + ); + } + const log = requestOptions.request?.log || console; + const parseSuccessResponseBody = requestOptions.request?.parseSuccessResponseBody !== false; + const body = isPlainObject2(requestOptions.body) || Array.isArray(requestOptions.body) ? JSONStringify(requestOptions.body) : requestOptions.body; + const requestHeaders = Object.fromEntries( + Object.entries(requestOptions.headers).map(([name, value]) => [ + name, + String(value) + ]) + ); + let fetchResponse; + try { + fetchResponse = await fetch3(requestOptions.url, { + method: requestOptions.method, + body, + redirect: requestOptions.request?.redirect, + headers: requestHeaders, + signal: requestOptions.request?.signal, + // duplex must be set if request.body is ReadableStream or Async Iterables. + // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex. + ...requestOptions.body && { duplex: "half" } + }); + } catch (error2) { + let message = "Unknown Error"; + if (error2 instanceof Error) { + if (error2.name === "AbortError") { + error2.status = 500; + throw error2; + } + message = error2.message; + if (error2.name === "TypeError" && "cause" in error2) { + if (error2.cause instanceof Error) { + message = error2.cause.message; + } else if (typeof error2.cause === "string") { + message = error2.cause; + } + } + } + const requestError = new RequestError(message, 500, { + request: requestOptions + }); + requestError.cause = error2; + throw requestError; + } + const status = fetchResponse.status; + const url = fetchResponse.url; + const responseHeaders = {}; + for (const [key, value] of fetchResponse.headers) { + responseHeaders[key] = value; + } + const octokitResponse = { + url, + status, + headers: responseHeaders, + data: "" + }; + if ("deprecation" in responseHeaders) { + const matches = responseHeaders.link && responseHeaders.link.match(/<([^<>]+)>; rel="deprecation"/); + const deprecationLink = matches && matches.pop(); + log.warn( + `[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${responseHeaders.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` + ); + } + if (status === 204 || status === 205) { + return octokitResponse; + } + if (requestOptions.method === "HEAD") { + if (status < 400) { + return octokitResponse; + } + throw new RequestError(fetchResponse.statusText, status, { + response: octokitResponse, + request: requestOptions + }); + } + if (status === 304) { + octokitResponse.data = await getResponseData(fetchResponse); + throw new RequestError("Not modified", status, { + response: octokitResponse, + request: requestOptions + }); + } + if (status >= 400) { + octokitResponse.data = await getResponseData(fetchResponse); + throw new RequestError(toErrorMessage(octokitResponse.data), status, { + response: octokitResponse, + request: requestOptions + }); + } + octokitResponse.data = parseSuccessResponseBody ? await getResponseData(fetchResponse) : fetchResponse.body; + return octokitResponse; +} +async function getResponseData(response) { + const contentType = response.headers.get("content-type"); + if (!contentType) { + return response.text().catch(noop); + } + const mimetype = parse2(contentType); + if (isJSONResponse(mimetype)) { + let text = ""; + try { + text = await response.text(); + return JSONParse(text); + } catch (err) { + return text; + } + } else if (mimetype.type.startsWith("text/") || // `application/octet-stream` is the canonical "arbitrary binary" type + // (RFC 2046) and must never be decoded as text, even when the response + // carries a (misleading) `charset=utf-8` parameter — see #751. + mimetype.parameters.charset?.toLowerCase() === "utf-8" && mimetype.type !== "application/octet-stream") { + return response.text().catch(noop); + } else { + return response.arrayBuffer().catch( + /* v8 ignore next -- @preserve */ + () => new ArrayBuffer(0) + ); + } +} +function isJSONResponse(mimetype) { + return mimetype.type === "application/json" || mimetype.type === "application/scim+json"; +} +function toErrorMessage(data) { + if (typeof data === "string") { + return data; + } + if (data instanceof ArrayBuffer) { + return "Unknown error"; + } + if (typeof data === "object" && data !== null && "message" in data) { + const objectData = data; + const suffix = "documentation_url" in objectData ? ` - ${objectData.documentation_url}` : ""; + return Array.isArray(objectData.errors) ? `${objectData.message}: ${objectData.errors.map((v) => JSON.stringify(v)).join(", ")}${suffix}` : `${objectData.message}${suffix}`; + } + return `Unknown error: ${JSON.stringify(data)}`; +} +function withDefaults2(oldEndpoint, newDefaults) { + const endpoint2 = oldEndpoint.defaults(newDefaults); + const newApi = function(route, parameters) { + const endpointOptions = endpoint2.merge(route, parameters); + if (!endpointOptions.request || !endpointOptions.request.hook) { + return fetchWrapper(endpoint2.parse(endpointOptions)); + } + const request2 = (route2, parameters2) => { + return fetchWrapper( + endpoint2.parse(endpoint2.merge(route2, parameters2)) + ); + }; + Object.assign(request2, { + endpoint: endpoint2, + defaults: withDefaults2.bind(null, endpoint2) + }); + return endpointOptions.request.hook(request2, endpointOptions); + }; + return Object.assign(newApi, { + endpoint: endpoint2, + defaults: withDefaults2.bind(null, endpoint2) + }); +} +var request = withDefaults2(endpoint, defaults_default); + +// node_modules/@octokit/graphql/dist-bundle/index.js +var VERSION3 = "0.0.0-development"; +function _buildMessageForResponseErrors(data) { + return `Request failed due to following response errors: +` + data.errors.map((e) => ` - ${e.message}`).join("\n"); +} +var GraphqlResponseError = class extends Error { + constructor(request2, headers, response) { + super(_buildMessageForResponseErrors(response)); + this.request = request2; + this.headers = headers; + this.response = response; + this.errors = response.errors; + this.data = response.data; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + } + request; + headers; + response; + name = "GraphqlResponseError"; + errors; + data; +}; +var NON_VARIABLE_OPTIONS = [ + "method", + "baseUrl", + "url", + "headers", + "request", + "query", + "mediaType", + "operationName" +]; +var FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"]; +var GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; +function graphql(request2, query, options) { + if (options) { + if (typeof query === "string" && "query" in options) { + return Promise.reject( + new Error(`[@octokit/graphql] "query" cannot be used as variable name`) + ); + } + for (const key in options) { + if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue; + return Promise.reject( + new Error( + `[@octokit/graphql] "${key}" cannot be used as variable name` + ) + ); + } + } + const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query; + const requestOptions = Object.keys( + parsedOptions + ).reduce((result, key) => { + if (NON_VARIABLE_OPTIONS.includes(key)) { + result[key] = parsedOptions[key]; + return result; + } + if (!result.variables) { + result.variables = {}; + } + result.variables[key] = parsedOptions[key]; + return result; + }, {}); + const baseUrl2 = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl; + if (GHES_V3_SUFFIX_REGEX.test(baseUrl2)) { + requestOptions.url = baseUrl2.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql"); + } + return request2(requestOptions).then((response) => { + if (response.data.errors) { + const headers = {}; + for (const key of Object.keys(response.headers)) { + headers[key] = response.headers[key]; + } + throw new GraphqlResponseError( + requestOptions, + headers, + response.data + ); + } + return response.data.data; + }); +} +function withDefaults3(request2, newDefaults) { + const newRequest = request2.defaults(newDefaults); + const newApi = (query, options) => { + return graphql(newRequest, query, options); + }; + return Object.assign(newApi, { + defaults: withDefaults3.bind(null, newRequest), + endpoint: newRequest.endpoint + }); +} +var graphql2 = withDefaults3(request, { + headers: { + "user-agent": `octokit-graphql.js/${VERSION3} ${getUserAgent()}` }, - orgs: { - addSecurityManagerTeam: [ - "PUT /orgs/{org}/security-managers/teams/{team_slug}", - {}, - { - deprecated: "octokit.rest.orgs.addSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#add-a-security-manager-team" + method: "POST", + url: "/graphql" +}); +function withCustomRequest(customRequest) { + return withDefaults3(customRequest, { + method: "POST", + url: "/graphql" + }); +} + +// node_modules/@octokit/auth-token/dist-bundle/index.js +var b64url = "(?:[a-zA-Z0-9_-]+)"; +var sep = "\\."; +var jwtRE = new RegExp(`^${b64url}${sep}${b64url}${sep}${b64url}$`); +var isJWT = jwtRE.test.bind(jwtRE); +async function auth(token) { + const isApp = isJWT(token); + const isInstallation = token.startsWith("v1.") || token.startsWith("ghs_"); + const isUserToServer = token.startsWith("ghu_"); + const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth"; + return { + type: "token", + token, + tokenType + }; +} +function withAuthorizationPrefix(token) { + if (token.split(/\./).length === 3) { + return `bearer ${token}`; + } + return `token ${token}`; +} +async function hook(token, request2, route, parameters) { + const endpoint2 = request2.endpoint.merge( + route, + parameters + ); + endpoint2.headers.authorization = withAuthorizationPrefix(token); + return request2(endpoint2); +} +var createTokenAuth = function createTokenAuth2(token) { + if (!token) { + throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); + } + if (typeof token !== "string") { + throw new Error( + "[@octokit/auth-token] Token passed to createTokenAuth is not a string" + ); + } + token = token.replace(/^(token|bearer) +/i, ""); + return Object.assign(auth.bind(null, token), { + hook: hook.bind(null, token) + }); +}; + +// node_modules/@octokit/core/dist-src/version.js +var VERSION4 = "7.0.7"; + +// node_modules/@octokit/core/dist-src/index.js +var noop2 = () => { +}; +var consoleWarn = console.warn.bind(console); +var consoleError = console.error.bind(console); +function createLogger(logger = {}) { + if (typeof logger.debug !== "function") { + logger.debug = noop2; + } + if (typeof logger.info !== "function") { + logger.info = noop2; + } + if (typeof logger.warn !== "function") { + logger.warn = consoleWarn; + } + if (typeof logger.error !== "function") { + logger.error = consoleError; + } + return logger; +} +var userAgentTrail = `octokit-core.js/${VERSION4} ${getUserAgent()}`; +var Octokit = class { + static VERSION = VERSION4; + static defaults(defaults2) { + const OctokitWithDefaults = class extends this { + constructor(...args) { + const options = args[0] || {}; + if (typeof defaults2 === "function") { + super(defaults2(options)); + return; + } + super( + Object.assign( + {}, + defaults2, + options, + options.userAgent && defaults2.userAgent ? { + userAgent: `${options.userAgent} ${defaults2.userAgent}` + } : null + ) + ); } - ], - assignTeamToOrgRole: [ - "PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" - ], - assignUserToOrgRole: [ - "PUT /orgs/{org}/organization-roles/users/{username}/{role_id}" - ], - blockUser: ["PUT /orgs/{org}/blocks/{username}"], - cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"], - checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"], - checkMembershipForUser: ["GET /orgs/{org}/members/{username}"], - checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"], - convertMemberToOutsideCollaborator: [ - "PUT /orgs/{org}/outside_collaborators/{username}" - ], - createArtifactStorageRecord: [ - "POST /orgs/{org}/artifacts/metadata/storage-record" - ], - createInvitation: ["POST /orgs/{org}/invitations"], - createIssueType: ["POST /orgs/{org}/issue-types"], - createWebhook: ["POST /orgs/{org}/hooks"], - customPropertiesForOrgsCreateOrUpdateOrganizationValues: [ - "PATCH /organizations/{org}/org-properties/values" - ], - customPropertiesForOrgsGetOrganizationValues: [ - "GET /organizations/{org}/org-properties/values" - ], - customPropertiesForReposCreateOrUpdateOrganizationDefinition: [ - "PUT /orgs/{org}/properties/schema/{custom_property_name}" - ], - customPropertiesForReposCreateOrUpdateOrganizationDefinitions: [ - "PATCH /orgs/{org}/properties/schema" - ], - customPropertiesForReposCreateOrUpdateOrganizationValues: [ - "PATCH /orgs/{org}/properties/values" - ], - customPropertiesForReposDeleteOrganizationDefinition: [ - "DELETE /orgs/{org}/properties/schema/{custom_property_name}" - ], - customPropertiesForReposGetOrganizationDefinition: [ - "GET /orgs/{org}/properties/schema/{custom_property_name}" - ], - customPropertiesForReposGetOrganizationDefinitions: [ - "GET /orgs/{org}/properties/schema" - ], - customPropertiesForReposGetOrganizationValues: [ - "GET /orgs/{org}/properties/values" - ], - delete: ["DELETE /orgs/{org}"], - deleteAttestationsBulk: ["POST /orgs/{org}/attestations/delete-request"], - deleteAttestationsById: [ - "DELETE /orgs/{org}/attestations/{attestation_id}" - ], - deleteAttestationsBySubjectDigest: [ - "DELETE /orgs/{org}/attestations/digest/{subject_digest}" - ], - deleteIssueType: ["DELETE /orgs/{org}/issue-types/{issue_type_id}"], - deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], - disableSelectedRepositoryImmutableReleasesOrganization: [ - "DELETE /orgs/{org}/settings/immutable-releases/repositories/{repository_id}" - ], - enableSelectedRepositoryImmutableReleasesOrganization: [ - "PUT /orgs/{org}/settings/immutable-releases/repositories/{repository_id}" - ], - get: ["GET /orgs/{org}"], - getImmutableReleasesSettings: [ - "GET /orgs/{org}/settings/immutable-releases" - ], - getImmutableReleasesSettingsRepositories: [ - "GET /orgs/{org}/settings/immutable-releases/repositories" - ], - getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], - getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], - getOrgRole: ["GET /orgs/{org}/organization-roles/{role_id}"], - getOrgRulesetHistory: ["GET /orgs/{org}/rulesets/{ruleset_id}/history"], - getOrgRulesetVersion: [ - "GET /orgs/{org}/rulesets/{ruleset_id}/history/{version_id}" - ], - getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], - getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"], - getWebhookDelivery: [ - "GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}" - ], - list: ["GET /organizations"], - listAppInstallations: ["GET /orgs/{org}/installations"], - listArtifactStorageRecords: [ - "GET /orgs/{org}/artifacts/{subject_digest}/metadata/storage-records" - ], - listAttestationRepositories: ["GET /orgs/{org}/attestations/repositories"], - listAttestations: ["GET /orgs/{org}/attestations/{subject_digest}"], - listAttestationsBulk: [ - "POST /orgs/{org}/attestations/bulk-list{?per_page,before,after}" - ], - listBlockedUsers: ["GET /orgs/{org}/blocks"], - listFailedInvitations: ["GET /orgs/{org}/failed_invitations"], - listForAuthenticatedUser: ["GET /user/orgs"], - listForUser: ["GET /users/{username}/orgs"], - listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"], - listIssueTypes: ["GET /orgs/{org}/issue-types"], - listMembers: ["GET /orgs/{org}/members"], - listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"], - listOrgRoleTeams: ["GET /orgs/{org}/organization-roles/{role_id}/teams"], - listOrgRoleUsers: ["GET /orgs/{org}/organization-roles/{role_id}/users"], - listOrgRoles: ["GET /orgs/{org}/organization-roles"], - listOrganizationFineGrainedPermissions: [ - "GET /orgs/{org}/organization-fine-grained-permissions" - ], - listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"], - listPatGrantRepositories: [ - "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories" - ], - listPatGrantRequestRepositories: [ - "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories" - ], - listPatGrantRequests: ["GET /orgs/{org}/personal-access-token-requests"], - listPatGrants: ["GET /orgs/{org}/personal-access-tokens"], - listPendingInvitations: ["GET /orgs/{org}/invitations"], - listPublicMembers: ["GET /orgs/{org}/public_members"], - listSecurityManagerTeams: [ - "GET /orgs/{org}/security-managers", - {}, - { - deprecated: "octokit.rest.orgs.listSecurityManagerTeams() is deprecated, see https://docs.github.com/rest/orgs/security-managers#list-security-manager-teams" + }; + return OctokitWithDefaults; + } + static plugins = []; + /** + * Attach a plugin (or many) to your Octokit instance. + * + * @example + * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) + */ + static plugin(...newPlugins) { + const currentPlugins = this.plugins; + const NewOctokit = class extends this { + static plugins = currentPlugins.concat( + newPlugins.filter((plugin) => !currentPlugins.includes(plugin)) + ); + }; + return NewOctokit; + } + constructor(options = {}) { + const hook2 = new before_after_hook_default.Collection(); + const requestDefaults = { + baseUrl: request.endpoint.DEFAULTS.baseUrl, + headers: {}, + request: Object.assign({}, options.request, { + // @ts-ignore internal usage only, no need to type + hook: hook2.bind(null, "request") + }), + mediaType: { + previews: [], + format: "" } - ], - listWebhookDeliveries: ["GET /orgs/{org}/hooks/{hook_id}/deliveries"], - listWebhooks: ["GET /orgs/{org}/hooks"], - pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"], - redeliverWebhookDelivery: [ - "POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" - ], - removeMember: ["DELETE /orgs/{org}/members/{username}"], - removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], - removeOutsideCollaborator: [ - "DELETE /orgs/{org}/outside_collaborators/{username}" - ], - removePublicMembershipForAuthenticatedUser: [ - "DELETE /orgs/{org}/public_members/{username}" - ], - removeSecurityManagerTeam: [ - "DELETE /orgs/{org}/security-managers/teams/{team_slug}", - {}, - { - deprecated: "octokit.rest.orgs.removeSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#remove-a-security-manager-team" + }; + requestDefaults.headers["user-agent"] = options.userAgent ? `${options.userAgent} ${userAgentTrail}` : userAgentTrail; + if (options.baseUrl) { + requestDefaults.baseUrl = options.baseUrl; + } + if (options.previews) { + requestDefaults.mediaType.previews = options.previews; + } + if (options.timeZone) { + requestDefaults.headers["time-zone"] = options.timeZone; + } + this.request = request.defaults(requestDefaults); + this.graphql = withCustomRequest(this.request).defaults(requestDefaults); + this.log = createLogger(options.log); + this.hook = hook2; + if (!options.authStrategy) { + if (!options.auth) { + this.auth = async () => ({ + type: "unauthenticated" + }); + } else { + const auth2 = createTokenAuth(options.auth); + hook2.wrap("request", auth2.hook); + this.auth = auth2; } + } else { + const { authStrategy, ...otherOptions } = options; + const auth2 = authStrategy( + Object.assign( + { + request: this.request, + log: this.log, + // we pass the current octokit instance as well as its constructor options + // to allow for authentication strategies that return a new octokit instance + // that shares the same internal state as the current one. The original + // requirement for this was the "event-octokit" authentication strategy + // of https://github.com/probot/octokit-auth-probot. + octokit: this, + octokitOptions: otherOptions + }, + options.auth + ) + ); + hook2.wrap("request", auth2.hook); + this.auth = auth2; + } + const classConstructor = this.constructor; + for (let i = 0; i < classConstructor.plugins.length; ++i) { + Object.assign(this, classConstructor.plugins[i](this, options)); + } + } + // assigned during constructor + request; + graphql; + log; + hook; + // TODO: type `octokit.auth` based on passed options.authStrategy + auth; +}; + +// node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/version.js +var VERSION5 = "17.0.0"; + +// node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/generated/endpoints.js +var Endpoints = { + actions: { + addCustomLabelsToSelfHostedRunnerForOrg: [ + "POST /orgs/{org}/actions/runners/{runner_id}/labels" ], - reviewPatGrantRequest: [ - "POST /orgs/{org}/personal-access-token-requests/{pat_request_id}" - ], - reviewPatGrantRequestsInBulk: [ - "POST /orgs/{org}/personal-access-token-requests" - ], - revokeAllOrgRolesTeam: [ - "DELETE /orgs/{org}/organization-roles/teams/{team_slug}" - ], - revokeAllOrgRolesUser: [ - "DELETE /orgs/{org}/organization-roles/users/{username}" - ], - revokeOrgRoleTeam: [ - "DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" - ], - revokeOrgRoleUser: [ - "DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}" - ], - setImmutableReleasesSettings: [ - "PUT /orgs/{org}/settings/immutable-releases" - ], - setImmutableReleasesSettingsRepositories: [ - "PUT /orgs/{org}/settings/immutable-releases/repositories" - ], - setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"], - setPublicMembershipForAuthenticatedUser: [ - "PUT /orgs/{org}/public_members/{username}" - ], - unblockUser: ["DELETE /orgs/{org}/blocks/{username}"], - update: ["PATCH /orgs/{org}"], - updateIssueType: ["PUT /orgs/{org}/issue-types/{issue_type_id}"], - updateMembershipForAuthenticatedUser: [ - "PATCH /user/memberships/orgs/{org}" + addCustomLabelsToSelfHostedRunnerForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" ], - updatePatAccess: ["POST /orgs/{org}/personal-access-tokens/{pat_id}"], - updatePatAccesses: ["POST /orgs/{org}/personal-access-tokens"], - updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"], - updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"] - }, - packages: { - deletePackageForAuthenticatedUser: [ - "DELETE /user/packages/{package_type}/{package_name}" + addRepoAccessToSelfHostedRunnerGroupInOrg: [ + "PUT /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories/{repository_id}" ], - deletePackageForOrg: [ - "DELETE /orgs/{org}/packages/{package_type}/{package_name}" + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" ], - deletePackageForUser: [ - "DELETE /users/{username}/packages/{package_type}/{package_name}" + addSelectedRepoToOrgVariable: [ + "PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" ], - deletePackageVersionForAuthenticatedUser: [ - "DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}" + approveWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve" ], - deletePackageVersionForOrg: [ - "DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" + cancelWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel" ], - deletePackageVersionForUser: [ - "DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" + createEnvironmentVariable: [ + "POST /repos/{owner}/{repo}/environments/{environment_name}/variables" ], - getAllPackageVersionsForAPackageOwnedByAnOrg: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", - {}, - { renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"] } + createHostedRunnerForOrg: ["POST /orgs/{org}/actions/hosted-runners"], + createOrUpdateEnvironmentSecret: [ + "PUT /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}" ], - getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}/versions", - {}, - { - renamed: [ - "packages", - "getAllPackageVersionsForPackageOwnedByAuthenticatedUser" - ] - } + createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}" ], - getAllPackageVersionsForPackageOwnedByAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}/versions" + createOrgVariable: ["POST /orgs/{org}/actions/variables"], + createRegistrationTokenForOrg: [ + "POST /orgs/{org}/actions/runners/registration-token" ], - getAllPackageVersionsForPackageOwnedByOrg: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}/versions" + createRegistrationTokenForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/registration-token" ], - getAllPackageVersionsForPackageOwnedByUser: [ - "GET /users/{username}/packages/{package_type}/{package_name}/versions" + createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], + createRemoveTokenForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/remove-token" ], - getPackageForAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}" + createRepoVariable: ["POST /repos/{owner}/{repo}/actions/variables"], + createWorkflowDispatch: [ + "POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches" ], - getPackageForOrganization: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}" + deleteActionsCacheById: [ + "DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}" ], - getPackageForUser: [ - "GET /users/{username}/packages/{package_type}/{package_name}" + deleteActionsCacheByKey: [ + "DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}" ], - getPackageVersionForAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}" + deleteArtifact: [ + "DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}" ], - getPackageVersionForOrganization: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" + deleteCustomImageFromOrg: [ + "DELETE /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}" ], - getPackageVersionForUser: [ - "GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" + deleteCustomImageVersionFromOrg: [ + "DELETE /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions/{version}" ], - listDockerMigrationConflictingPackagesForAuthenticatedUser: [ - "GET /user/docker/conflicts" + deleteEnvironmentSecret: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}" ], - listDockerMigrationConflictingPackagesForOrganization: [ - "GET /orgs/{org}/docker/conflicts" + deleteEnvironmentVariable: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}" ], - listDockerMigrationConflictingPackagesForUser: [ - "GET /users/{username}/docker/conflicts" + deleteHostedRunnerForOrg: [ + "DELETE /orgs/{org}/actions/hosted-runners/{hosted_runner_id}" ], - listPackagesForAuthenticatedUser: ["GET /user/packages"], - listPackagesForOrganization: ["GET /orgs/{org}/packages"], - listPackagesForUser: ["GET /users/{username}/packages"], - restorePackageForAuthenticatedUser: [ - "POST /user/packages/{package_type}/{package_name}/restore{?token}" + deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"], + deleteOrgVariable: ["DELETE /orgs/{org}/actions/variables/{name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}" ], - restorePackageForOrg: [ - "POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}" + deleteRepoVariable: [ + "DELETE /repos/{owner}/{repo}/actions/variables/{name}" ], - restorePackageForUser: [ - "POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}" + deleteSelfHostedRunnerFromOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}" ], - restorePackageVersionForAuthenticatedUser: [ - "POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + deleteSelfHostedRunnerFromRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}" ], - restorePackageVersionForOrg: [ - "POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"], + deleteWorkflowRunLogs: [ + "DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs" ], - restorePackageVersionForUser: [ - "POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" - ] - }, - privateRegistries: { - createOrgPrivateRegistry: ["POST /orgs/{org}/private-registries"], - deleteOrgPrivateRegistry: [ - "DELETE /orgs/{org}/private-registries/{secret_name}" + disableSelectedRepositoryGithubActionsOrganization: [ + "DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}" ], - getOrgPrivateRegistry: ["GET /orgs/{org}/private-registries/{secret_name}"], - getOrgPublicKey: ["GET /orgs/{org}/private-registries/public-key"], - listOrgPrivateRegistries: ["GET /orgs/{org}/private-registries"], - updateOrgPrivateRegistry: [ - "PATCH /orgs/{org}/private-registries/{secret_name}" - ] - }, - projects: { - addItemForOrg: ["POST /orgs/{org}/projectsV2/{project_number}/items"], - addItemForUser: [ - "POST /users/{username}/projectsV2/{project_number}/items" + disableWorkflow: [ + "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable" ], - deleteItemForOrg: [ - "DELETE /orgs/{org}/projectsV2/{project_number}/items/{item_id}" + downloadArtifact: [ + "GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}" ], - deleteItemForUser: [ - "DELETE /users/{username}/projectsV2/{project_number}/items/{item_id}" + downloadJobLogsForWorkflowRun: [ + "GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs" ], - getFieldForOrg: [ - "GET /orgs/{org}/projectsV2/{project_number}/fields/{field_id}" + downloadWorkflowRunAttemptLogs: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs" ], - getFieldForUser: [ - "GET /users/{username}/projectsV2/{project_number}/fields/{field_id}" + downloadWorkflowRunLogs: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs" ], - getForOrg: ["GET /orgs/{org}/projectsV2/{project_number}"], - getForUser: ["GET /users/{username}/projectsV2/{project_number}"], - getOrgItem: ["GET /orgs/{org}/projectsV2/{project_number}/items/{item_id}"], - getUserItem: [ - "GET /users/{username}/projectsV2/{project_number}/items/{item_id}" + enableSelectedRepositoryGithubActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/repositories/{repository_id}" ], - listFieldsForOrg: ["GET /orgs/{org}/projectsV2/{project_number}/fields"], - listFieldsForUser: [ - "GET /users/{username}/projectsV2/{project_number}/fields" + enableWorkflow: [ + "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable" ], - listForOrg: ["GET /orgs/{org}/projectsV2"], - listForUser: ["GET /users/{username}/projectsV2"], - listItemsForOrg: ["GET /orgs/{org}/projectsV2/{project_number}/items"], - listItemsForUser: [ - "GET /users/{username}/projectsV2/{project_number}/items" + forceCancelWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel" ], - updateItemForOrg: [ - "PATCH /orgs/{org}/projectsV2/{project_number}/items/{item_id}" + generateRunnerJitconfigForOrg: [ + "POST /orgs/{org}/actions/runners/generate-jitconfig" ], - updateItemForUser: [ - "PATCH /users/{username}/projectsV2/{project_number}/items/{item_id}" - ] - }, - pulls: { - checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"], - create: ["POST /repos/{owner}/{repo}/pulls"], - createReplyForReviewComment: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies" + generateRunnerJitconfigForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig" ], - createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], - createReviewComment: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments" + getActionsCacheList: ["GET /repos/{owner}/{repo}/actions/caches"], + getActionsCacheUsage: ["GET /repos/{owner}/{repo}/actions/cache/usage"], + getActionsCacheUsageByRepoForOrg: [ + "GET /orgs/{org}/actions/cache/usage-by-repository" ], - deletePendingReview: [ - "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + getActionsCacheUsageForOrg: ["GET /orgs/{org}/actions/cache/usage"], + getAllowedActionsOrganization: [ + "GET /orgs/{org}/actions/permissions/selected-actions" ], - deleteReviewComment: [ - "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}" + getAllowedActionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/selected-actions" ], - dismissReview: [ - "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals" + getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], + getCustomImageForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}" ], - get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"], - getReview: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + getCustomImageVersionForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions/{version}" ], - getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"], - list: ["GET /repos/{owner}/{repo}/pulls"], - listCommentsForReview: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments" + getCustomOidcSubClaimForRepo: [ + "GET /repos/{owner}/{repo}/actions/oidc/customization/sub" ], - listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"], - listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"], - listRequestedReviewers: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + getEnvironmentPublicKey: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/public-key" ], - listReviewComments: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments" + getEnvironmentSecret: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}" ], - listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"], - listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], - merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"], - removeRequestedReviewers: [ - "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + getEnvironmentVariable: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}" ], - requestReviewers: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + getGithubActionsDefaultWorkflowPermissionsOrganization: [ + "GET /orgs/{org}/actions/permissions/workflow" ], - submitReview: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events" + getGithubActionsDefaultWorkflowPermissionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/workflow" ], - update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"], - updateBranch: [ - "PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch" + getGithubActionsPermissionsOrganization: [ + "GET /orgs/{org}/actions/permissions" ], - updateReview: [ - "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + getGithubActionsPermissionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions" ], - updateReviewComment: [ - "PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}" - ] - }, - rateLimit: { get: ["GET /rate_limit"] }, - reactions: { - createForCommitComment: [ - "POST /repos/{owner}/{repo}/comments/{comment_id}/reactions" + getHostedRunnerForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/{hosted_runner_id}" ], - createForIssue: [ - "POST /repos/{owner}/{repo}/issues/{issue_number}/reactions" + getHostedRunnersGithubOwnedImagesForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/images/github-owned" ], - createForIssueComment: [ - "POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" + getHostedRunnersLimitsForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/limits" ], - createForPullRequestReviewComment: [ - "POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" + getHostedRunnersMachineSpecsForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/machine-sizes" ], - createForRelease: [ - "POST /repos/{owner}/{repo}/releases/{release_id}/reactions" + getHostedRunnersPartnerImagesForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/images/partner" ], - createForTeamDiscussionCommentInOrg: [ - "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" + getHostedRunnersPlatformsForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/platforms" ], - createForTeamDiscussionInOrg: [ - "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" + getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"], + getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"], + getOrgVariable: ["GET /orgs/{org}/actions/variables/{name}"], + getPendingDeploymentsForRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" ], - deleteForCommitComment: [ - "DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}" + getRepoPermissions: [ + "GET /repos/{owner}/{repo}/actions/permissions", + {}, + { renamed: ["actions", "getGithubActionsPermissionsRepository"] } ], - deleteForIssue: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}" + getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"], + getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"], + getRepoVariable: ["GET /repos/{owner}/{repo}/actions/variables/{name}"], + getReviewsForRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals" ], - deleteForIssueComment: [ - "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}" + getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"], + getSelfHostedRunnerForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/{runner_id}" ], - deleteForPullRequestComment: [ - "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}" + getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"], + getWorkflowAccessToRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/access" ], - deleteForRelease: [ - "DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}" + getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"], + getWorkflowRunAttempt: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}" ], - deleteForTeamDiscussion: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}" + getWorkflowRunUsage: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing" ], - deleteForTeamDiscussionComment: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}" + getWorkflowUsage: [ + "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing" ], - listForCommitComment: [ - "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions" + listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"], + listCustomImageVersionsForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions" ], - listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"], - listForIssueComment: [ - "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" + listCustomImagesForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/images/custom" ], - listForPullRequestReviewComment: [ - "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" + listEnvironmentSecrets: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/secrets" ], - listForRelease: [ - "GET /repos/{owner}/{repo}/releases/{release_id}/reactions" + listEnvironmentVariables: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/variables" ], - listForTeamDiscussionCommentInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" + listGithubHostedRunnersInGroupForOrg: [ + "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/hosted-runners" ], - listForTeamDiscussionInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" - ] - }, - repos: { - acceptInvitation: [ - "PATCH /user/repository_invitations/{invitation_id}", - {}, - { renamed: ["repos", "acceptInvitationForAuthenticatedUser"] } + listHostedRunnersForOrg: ["GET /orgs/{org}/actions/hosted-runners"], + listJobsForWorkflowRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs" ], - acceptInvitationForAuthenticatedUser: [ - "PATCH /user/repository_invitations/{invitation_id}" + listJobsForWorkflowRunAttempt: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs" ], - addAppAccessRestrictions: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", - {}, - { mapToData: "apps" } + listLabelsForSelfHostedRunnerForOrg: [ + "GET /orgs/{org}/actions/runners/{runner_id}/labels" ], - addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"], - addStatusCheckContexts: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", - {}, - { mapToData: "contexts" } + listLabelsForSelfHostedRunnerForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" ], - addTeamAccessRestrictions: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", - {}, - { mapToData: "teams" } + listOrgSecrets: ["GET /orgs/{org}/actions/secrets"], + listOrgVariables: ["GET /orgs/{org}/actions/variables"], + listRepoOrganizationSecrets: [ + "GET /repos/{owner}/{repo}/actions/organization-secrets" ], - addUserAccessRestrictions: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", - {}, - { mapToData: "users" } + listRepoOrganizationVariables: [ + "GET /repos/{owner}/{repo}/actions/organization-variables" ], - cancelPagesDeployment: [ - "POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel" + listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"], + listRepoVariables: ["GET /repos/{owner}/{repo}/actions/variables"], + listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"], + listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"], + listRunnerApplicationsForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/downloads" ], - checkAutomatedSecurityFixes: [ - "GET /repos/{owner}/{repo}/automated-security-fixes" + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/actions/secrets/{secret_name}/repositories" ], - checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"], - checkImmutableReleases: ["GET /repos/{owner}/{repo}/immutable-releases"], - checkPrivateVulnerabilityReporting: [ - "GET /repos/{owner}/{repo}/private-vulnerability-reporting" + listSelectedReposForOrgVariable: [ + "GET /orgs/{org}/actions/variables/{name}/repositories" ], - checkVulnerabilityAlerts: [ - "GET /repos/{owner}/{repo}/vulnerability-alerts" + listSelectedRepositoriesEnabledGithubActionsOrganization: [ + "GET /orgs/{org}/actions/permissions/repositories" ], - codeownersErrors: ["GET /repos/{owner}/{repo}/codeowners/errors"], - compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"], - compareCommitsWithBasehead: [ - "GET /repos/{owner}/{repo}/compare/{basehead}" + listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"], + listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"], + listWorkflowRunArtifacts: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts" ], - createAttestation: ["POST /repos/{owner}/{repo}/attestations"], - createAutolink: ["POST /repos/{owner}/{repo}/autolinks"], - createCommitComment: [ - "POST /repos/{owner}/{repo}/commits/{commit_sha}/comments" + listWorkflowRuns: [ + "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs" ], - createCommitSignatureProtection: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"], + reRunJobForWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun" ], - createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"], - createDeployKey: ["POST /repos/{owner}/{repo}/keys"], - createDeployment: ["POST /repos/{owner}/{repo}/deployments"], - createDeploymentBranchPolicy: [ - "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" + reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"], + reRunWorkflowFailedJobs: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs" ], - createDeploymentProtectionRule: [ - "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" + removeAllCustomLabelsFromSelfHostedRunnerForOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}/labels" ], - createDeploymentStatus: [ - "POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" + removeAllCustomLabelsFromSelfHostedRunnerForRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" ], - createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"], - createForAuthenticatedUser: ["POST /user/repos"], - createFork: ["POST /repos/{owner}/{repo}/forks"], - createInOrg: ["POST /orgs/{org}/repos"], - createOrUpdateEnvironment: [ - "PUT /repos/{owner}/{repo}/environments/{environment_name}" + removeCustomLabelFromSelfHostedRunnerForOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}" ], - createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"], - createOrgRuleset: ["POST /orgs/{org}/rulesets"], - createPagesDeployment: ["POST /repos/{owner}/{repo}/pages/deployments"], - createPagesSite: ["POST /repos/{owner}/{repo}/pages"], - createRelease: ["POST /repos/{owner}/{repo}/releases"], - createRepoRuleset: ["POST /repos/{owner}/{repo}/rulesets"], - createUsingTemplate: [ - "POST /repos/{template_owner}/{template_repo}/generate" + removeCustomLabelFromSelfHostedRunnerForRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}" ], - createWebhook: ["POST /repos/{owner}/{repo}/hooks"], - customPropertiesForReposCreateOrUpdateRepositoryValues: [ - "PATCH /repos/{owner}/{repo}/properties/values" + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" ], - customPropertiesForReposGetRepositoryValues: [ - "GET /repos/{owner}/{repo}/properties/values" + removeSelectedRepoFromOrgVariable: [ + "DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" ], - declineInvitation: [ - "DELETE /user/repository_invitations/{invitation_id}", - {}, - { renamed: ["repos", "declineInvitationForAuthenticatedUser"] } + reviewCustomGatesForRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule" ], - declineInvitationForAuthenticatedUser: [ - "DELETE /user/repository_invitations/{invitation_id}" + reviewPendingDeploymentsForRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" ], - delete: ["DELETE /repos/{owner}/{repo}"], - deleteAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" + setAllowedActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/selected-actions" ], - deleteAdminBranchProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + setAllowedActionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/selected-actions" ], - deleteAnEnvironment: [ - "DELETE /repos/{owner}/{repo}/environments/{environment_name}" + setCustomLabelsForSelfHostedRunnerForOrg: [ + "PUT /orgs/{org}/actions/runners/{runner_id}/labels" ], - deleteAutolink: ["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"], - deleteBranchProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection" + setCustomLabelsForSelfHostedRunnerForRepo: [ + "PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" ], - deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"], - deleteCommitSignatureProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + setCustomOidcSubClaimForRepo: [ + "PUT /repos/{owner}/{repo}/actions/oidc/customization/sub" ], - deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"], - deleteDeployment: [ - "DELETE /repos/{owner}/{repo}/deployments/{deployment_id}" + setGithubActionsDefaultWorkflowPermissionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/workflow" ], - deleteDeploymentBranchPolicy: [ - "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + setGithubActionsDefaultWorkflowPermissionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/workflow" ], - deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"], - deleteInvitation: [ - "DELETE /repos/{owner}/{repo}/invitations/{invitation_id}" + setGithubActionsPermissionsOrganization: [ + "PUT /orgs/{org}/actions/permissions" ], - deleteOrgRuleset: ["DELETE /orgs/{org}/rulesets/{ruleset_id}"], - deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages"], - deletePullRequestReviewProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + setGithubActionsPermissionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions" ], - deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"], - deleteReleaseAsset: [ - "DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}" + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories" ], - deleteRepoRuleset: ["DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}"], - deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"], - disableAutomatedSecurityFixes: [ - "DELETE /repos/{owner}/{repo}/automated-security-fixes" + setSelectedReposForOrgVariable: [ + "PUT /orgs/{org}/actions/variables/{name}/repositories" ], - disableDeploymentProtectionRule: [ - "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" + setSelectedRepositoriesEnabledGithubActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/repositories" ], - disableImmutableReleases: [ - "DELETE /repos/{owner}/{repo}/immutable-releases" + setWorkflowAccessToRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/access" ], - disablePrivateVulnerabilityReporting: [ - "DELETE /repos/{owner}/{repo}/private-vulnerability-reporting" + updateEnvironmentVariable: [ + "PATCH /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}" ], - disableVulnerabilityAlerts: [ - "DELETE /repos/{owner}/{repo}/vulnerability-alerts" + updateHostedRunnerForOrg: [ + "PATCH /orgs/{org}/actions/hosted-runners/{hosted_runner_id}" ], - downloadArchive: [ - "GET /repos/{owner}/{repo}/zipball/{ref}", - {}, - { renamed: ["repos", "downloadZipballArchive"] } + updateOrgVariable: ["PATCH /orgs/{org}/actions/variables/{name}"], + updateRepoVariable: [ + "PATCH /repos/{owner}/{repo}/actions/variables/{name}" + ] + }, + activity: { + checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"], + deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"], + deleteThreadSubscription: [ + "DELETE /notifications/threads/{thread_id}/subscription" ], - downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"], - downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"], - enableAutomatedSecurityFixes: [ - "PUT /repos/{owner}/{repo}/automated-security-fixes" + getFeeds: ["GET /feeds"], + getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"], + getThread: ["GET /notifications/threads/{thread_id}"], + getThreadSubscriptionForAuthenticatedUser: [ + "GET /notifications/threads/{thread_id}/subscription" ], - enableImmutableReleases: ["PUT /repos/{owner}/{repo}/immutable-releases"], - enablePrivateVulnerabilityReporting: [ - "PUT /repos/{owner}/{repo}/private-vulnerability-reporting" + listEventsForAuthenticatedUser: ["GET /users/{username}/events"], + listNotificationsForAuthenticatedUser: ["GET /notifications"], + listOrgEventsForAuthenticatedUser: [ + "GET /users/{username}/events/orgs/{org}" ], - enableVulnerabilityAlerts: [ - "PUT /repos/{owner}/{repo}/vulnerability-alerts" + listPublicEvents: ["GET /events"], + listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"], + listPublicEventsForUser: ["GET /users/{username}/events/public"], + listPublicOrgEvents: ["GET /orgs/{org}/events"], + listReceivedEventsForUser: ["GET /users/{username}/received_events"], + listReceivedPublicEventsForUser: [ + "GET /users/{username}/received_events/public" ], - generateReleaseNotes: [ - "POST /repos/{owner}/{repo}/releases/generate-notes" + listRepoEvents: ["GET /repos/{owner}/{repo}/events"], + listRepoNotificationsForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/notifications" ], - get: ["GET /repos/{owner}/{repo}"], - getAccessRestrictions: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" + listReposStarredByAuthenticatedUser: ["GET /user/starred"], + listReposStarredByUser: ["GET /users/{username}/starred"], + listReposWatchedByUser: ["GET /users/{username}/subscriptions"], + listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"], + listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"], + listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"], + markNotificationsAsRead: ["PUT /notifications"], + markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"], + markThreadAsDone: ["DELETE /notifications/threads/{thread_id}"], + markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"], + setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"], + setThreadSubscription: [ + "PUT /notifications/threads/{thread_id}/subscription" ], - getAdminBranchProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"], + unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"] + }, + apps: { + addRepoToInstallation: [ + "PUT /user/installations/{installation_id}/repositories/{repository_id}", + {}, + { renamed: ["apps", "addRepoToInstallationForAuthenticatedUser"] } ], - getAllDeploymentProtectionRules: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" + addRepoToInstallationForAuthenticatedUser: [ + "PUT /user/installations/{installation_id}/repositories/{repository_id}" ], - getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"], - getAllStatusCheckContexts: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts" + checkToken: ["POST /applications/{client_id}/token"], + createFromManifest: ["POST /app-manifests/{code}/conversions"], + createInstallationAccessToken: [ + "POST /app/installations/{installation_id}/access_tokens" ], - getAllTopics: ["GET /repos/{owner}/{repo}/topics"], - getAppsWithAccessToProtectedBranch: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps" + deleteAuthorization: ["DELETE /applications/{client_id}/grant"], + deleteInstallation: ["DELETE /app/installations/{installation_id}"], + deleteToken: ["DELETE /applications/{client_id}/token"], + getAuthenticated: ["GET /app"], + getBySlug: ["GET /apps/{app_slug}"], + getInstallation: ["GET /app/installations/{installation_id}"], + getOrgInstallation: ["GET /orgs/{org}/installation"], + getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"], + getSubscriptionPlanForAccount: [ + "GET /marketplace_listing/accounts/{account_id}" ], - getAutolink: ["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"], - getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"], - getBranchProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection" + getSubscriptionPlanForAccountStubbed: [ + "GET /marketplace_listing/stubbed/accounts/{account_id}" ], - getBranchRules: ["GET /repos/{owner}/{repo}/rules/branches/{branch}"], - getClones: ["GET /repos/{owner}/{repo}/traffic/clones"], - getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"], - getCollaboratorPermissionLevel: [ - "GET /repos/{owner}/{repo}/collaborators/{username}/permission" + getUserInstallation: ["GET /users/{username}/installation"], + getWebhookConfigForApp: ["GET /app/hook/config"], + getWebhookDelivery: ["GET /app/hook/deliveries/{delivery_id}"], + listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"], + listAccountsForPlanStubbed: [ + "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts" ], - getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"], - getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"], - getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"], - getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"], - getCommitSignatureProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + listInstallationReposForAuthenticatedUser: [ + "GET /user/installations/{installation_id}/repositories" ], - getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"], - getContent: ["GET /repos/{owner}/{repo}/contents/{path}"], - getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"], - getCustomDeploymentProtectionRule: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" + listInstallationRequestsForAuthenticatedApp: [ + "GET /app/installation-requests" ], - getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"], - getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"], - getDeploymentBranchPolicy: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + listInstallations: ["GET /app/installations"], + listInstallationsForAuthenticatedUser: ["GET /user/installations"], + listPlans: ["GET /marketplace_listing/plans"], + listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"], + listReposAccessibleToInstallation: ["GET /installation/repositories"], + listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"], + listSubscriptionsForAuthenticatedUserStubbed: [ + "GET /user/marketplace_purchases/stubbed" ], - getDeploymentStatus: [ - "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}" + listWebhookDeliveries: ["GET /app/hook/deliveries"], + redeliverWebhookDelivery: [ + "POST /app/hook/deliveries/{delivery_id}/attempts" ], - getEnvironment: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}" + removeRepoFromInstallation: [ + "DELETE /user/installations/{installation_id}/repositories/{repository_id}", + {}, + { renamed: ["apps", "removeRepoFromInstallationForAuthenticatedUser"] } ], - getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], - getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], - getOrgRuleSuite: ["GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}"], - getOrgRuleSuites: ["GET /orgs/{org}/rulesets/rule-suites"], - getOrgRuleset: ["GET /orgs/{org}/rulesets/{ruleset_id}"], - getOrgRulesets: ["GET /orgs/{org}/rulesets"], - getPages: ["GET /repos/{owner}/{repo}/pages"], - getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"], - getPagesDeployment: [ - "GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}" + removeRepoFromInstallationForAuthenticatedUser: [ + "DELETE /user/installations/{installation_id}/repositories/{repository_id}" ], - getPagesHealthCheck: ["GET /repos/{owner}/{repo}/pages/health"], - getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"], - getPullRequestReviewProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + resetToken: ["PATCH /applications/{client_id}/token"], + revokeInstallationAccessToken: ["DELETE /installation/token"], + scopeToken: ["POST /applications/{client_id}/token/scoped"], + suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"], + unsuspendInstallation: [ + "DELETE /app/installations/{installation_id}/suspended" ], - getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"], - getReadme: ["GET /repos/{owner}/{repo}/readme"], - getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"], - getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"], - getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"], - getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"], - getRepoRuleSuite: [ - "GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}" + updateWebhookConfigForApp: ["PATCH /app/hook/config"] + }, + billing: { + getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"], + getGithubActionsBillingUser: [ + "GET /users/{username}/settings/billing/actions" ], - getRepoRuleSuites: ["GET /repos/{owner}/{repo}/rulesets/rule-suites"], - getRepoRuleset: ["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}"], - getRepoRulesetHistory: [ - "GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history" + getGithubBillingPremiumRequestUsageReportOrg: [ + "GET /organizations/{org}/settings/billing/premium_request/usage" ], - getRepoRulesetVersion: [ - "GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history/{version_id}" + getGithubBillingPremiumRequestUsageReportUser: [ + "GET /users/{username}/settings/billing/premium_request/usage" ], - getRepoRulesets: ["GET /repos/{owner}/{repo}/rulesets"], - getStatusChecksProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + getGithubBillingUsageReportOrg: [ + "GET /organizations/{org}/settings/billing/usage" ], - getTeamsWithAccessToProtectedBranch: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams" + getGithubBillingUsageReportUser: [ + "GET /users/{username}/settings/billing/usage" ], - getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"], - getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"], - getUsersWithAccessToProtectedBranch: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users" + getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"], + getGithubPackagesBillingUser: [ + "GET /users/{username}/settings/billing/packages" ], - getViews: ["GET /repos/{owner}/{repo}/traffic/views"], - getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"], - getWebhookConfigForRepo: [ - "GET /repos/{owner}/{repo}/hooks/{hook_id}/config" + getSharedStorageBillingOrg: [ + "GET /orgs/{org}/settings/billing/shared-storage" ], - getWebhookDelivery: [ - "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}" + getSharedStorageBillingUser: [ + "GET /users/{username}/settings/billing/shared-storage" + ] + }, + campaigns: { + createCampaign: ["POST /orgs/{org}/campaigns"], + deleteCampaign: ["DELETE /orgs/{org}/campaigns/{campaign_number}"], + getCampaignSummary: ["GET /orgs/{org}/campaigns/{campaign_number}"], + listOrgCampaigns: ["GET /orgs/{org}/campaigns"], + updateCampaign: ["PATCH /orgs/{org}/campaigns/{campaign_number}"] + }, + checks: { + create: ["POST /repos/{owner}/{repo}/check-runs"], + createSuite: ["POST /repos/{owner}/{repo}/check-suites"], + get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"], + getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"], + listAnnotations: [ + "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations" ], - listActivities: ["GET /repos/{owner}/{repo}/activity"], - listAttestations: [ - "GET /repos/{owner}/{repo}/attestations/{subject_digest}" + listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"], + listForSuite: [ + "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs" ], - listAutolinks: ["GET /repos/{owner}/{repo}/autolinks"], - listBranches: ["GET /repos/{owner}/{repo}/branches"], - listBranchesForHeadCommit: [ - "GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head" + listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"], + rerequestRun: [ + "POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest" ], - listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"], - listCommentsForCommit: [ - "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments" + rerequestSuite: [ + "POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest" ], - listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"], - listCommitStatusesForRef: [ - "GET /repos/{owner}/{repo}/commits/{ref}/statuses" + setSuitesPreferences: [ + "PATCH /repos/{owner}/{repo}/check-suites/preferences" ], - listCommits: ["GET /repos/{owner}/{repo}/commits"], - listContributors: ["GET /repos/{owner}/{repo}/contributors"], - listCustomDeploymentRuleIntegrations: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps" + update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"] + }, + codeScanning: { + commitAutofix: [ + "POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix/commits" ], - listDeployKeys: ["GET /repos/{owner}/{repo}/keys"], - listDeploymentBranchPolicies: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" + createAutofix: [ + "POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix" ], - listDeploymentStatuses: [ - "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" + createVariantAnalysis: [ + "POST /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses" ], - listDeployments: ["GET /repos/{owner}/{repo}/deployments"], - listForAuthenticatedUser: ["GET /user/repos"], - listForOrg: ["GET /orgs/{org}/repos"], - listForUser: ["GET /users/{username}/repos"], - listForks: ["GET /repos/{owner}/{repo}/forks"], - listInvitations: ["GET /repos/{owner}/{repo}/invitations"], - listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"], - listLanguages: ["GET /repos/{owner}/{repo}/languages"], - listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"], - listPublic: ["GET /repositories"], - listPullRequestsAssociatedWithCommit: [ - "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls" + deleteAnalysis: [ + "DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}" ], - listReleaseAssets: [ - "GET /repos/{owner}/{repo}/releases/{release_id}/assets" + deleteCodeqlDatabase: [ + "DELETE /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}" ], - listReleases: ["GET /repos/{owner}/{repo}/releases"], - listTags: ["GET /repos/{owner}/{repo}/tags"], - listTeams: ["GET /repos/{owner}/{repo}/teams"], - listWebhookDeliveries: [ - "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries" + getAlert: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", + {}, + { renamedParameters: { alert_id: "alert_number" } } ], - listWebhooks: ["GET /repos/{owner}/{repo}/hooks"], - merge: ["POST /repos/{owner}/{repo}/merges"], - mergeUpstream: ["POST /repos/{owner}/{repo}/merge-upstream"], - pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"], - redeliverWebhookDelivery: [ - "POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" + getAnalysis: [ + "GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}" + ], + getAutofix: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix" ], - removeAppAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", - {}, - { mapToData: "apps" } + getCodeqlDatabase: [ + "GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}" ], - removeCollaborator: [ - "DELETE /repos/{owner}/{repo}/collaborators/{username}" + getDefaultSetup: ["GET /repos/{owner}/{repo}/code-scanning/default-setup"], + getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"], + getVariantAnalysis: [ + "GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}" ], - removeStatusCheckContexts: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", - {}, - { mapToData: "contexts" } + getVariantAnalysisRepoTask: [ + "GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}/repos/{repo_owner}/{repo_name}" ], - removeStatusCheckProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + listAlertInstances: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances" ], - removeTeamAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + listAlertsForOrg: ["GET /orgs/{org}/code-scanning/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"], + listAlertsInstances: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", {}, - { mapToData: "teams" } + { renamed: ["codeScanning", "listAlertInstances"] } ], - removeUserAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", - {}, - { mapToData: "users" } + listCodeqlDatabases: [ + "GET /repos/{owner}/{repo}/code-scanning/codeql/databases" ], - renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"], - replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics"], - requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"], - setAdminBranchProtection: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}" ], - setAppAccessRestrictions: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", - {}, - { mapToData: "apps" } + updateDefaultSetup: [ + "PATCH /repos/{owner}/{repo}/code-scanning/default-setup" ], - setStatusCheckContexts: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", - {}, - { mapToData: "contexts" } + uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"] + }, + codeSecurity: { + attachConfiguration: [ + "POST /orgs/{org}/code-security/configurations/{configuration_id}/attach" ], - setTeamAccessRestrictions: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", - {}, - { mapToData: "teams" } + attachEnterpriseConfiguration: [ + "POST /enterprises/{enterprise}/code-security/configurations/{configuration_id}/attach" ], - setUserAccessRestrictions: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", - {}, - { mapToData: "users" } + createConfiguration: ["POST /orgs/{org}/code-security/configurations"], + createConfigurationForEnterprise: [ + "POST /enterprises/{enterprise}/code-security/configurations" ], - testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"], - transfer: ["POST /repos/{owner}/{repo}/transfer"], - update: ["PATCH /repos/{owner}/{repo}"], - updateBranchProtection: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection" + deleteConfiguration: [ + "DELETE /orgs/{org}/code-security/configurations/{configuration_id}" ], - updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"], - updateDeploymentBranchPolicy: [ - "PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + deleteConfigurationForEnterprise: [ + "DELETE /enterprises/{enterprise}/code-security/configurations/{configuration_id}" ], - updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"], - updateInvitation: [ - "PATCH /repos/{owner}/{repo}/invitations/{invitation_id}" + detachConfiguration: [ + "DELETE /orgs/{org}/code-security/configurations/detach" ], - updateOrgRuleset: ["PUT /orgs/{org}/rulesets/{ruleset_id}"], - updatePullRequestReviewProtection: [ - "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + getConfiguration: [ + "GET /orgs/{org}/code-security/configurations/{configuration_id}" ], - updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"], - updateReleaseAsset: [ - "PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}" + getConfigurationForRepository: [ + "GET /repos/{owner}/{repo}/code-security-configuration" ], - updateRepoRuleset: ["PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}"], - updateStatusCheckPotection: [ - "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", - {}, - { renamed: ["repos", "updateStatusCheckProtection"] } + getConfigurationsForEnterprise: [ + "GET /enterprises/{enterprise}/code-security/configurations" ], - updateStatusCheckProtection: [ - "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + getConfigurationsForOrg: ["GET /orgs/{org}/code-security/configurations"], + getDefaultConfigurations: [ + "GET /orgs/{org}/code-security/configurations/defaults" ], - updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"], - updateWebhookConfigForRepo: [ - "PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config" + getDefaultConfigurationsForEnterprise: [ + "GET /enterprises/{enterprise}/code-security/configurations/defaults" ], - uploadReleaseAsset: [ - "POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", - { baseUrl: "https://uploads.github.com" } - ] - }, - search: { - code: ["GET /search/code"], - commits: ["GET /search/commits"], - issuesAndPullRequests: ["GET /search/issues"], - labels: ["GET /search/labels"], - repos: ["GET /search/repositories"], - topics: ["GET /search/topics"], - users: ["GET /search/users"] - }, - secretScanning: { - createPushProtectionBypass: [ - "POST /repos/{owner}/{repo}/secret-scanning/push-protection-bypasses" + getRepositoriesForConfiguration: [ + "GET /orgs/{org}/code-security/configurations/{configuration_id}/repositories" ], - getAlert: [ - "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" + getRepositoriesForEnterpriseConfiguration: [ + "GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}/repositories" ], - getScanHistory: ["GET /repos/{owner}/{repo}/secret-scanning/scan-history"], - listAlertsForOrg: ["GET /orgs/{org}/secret-scanning/alerts"], - listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"], - listLocationsForAlert: [ - "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations" + getSingleConfigurationForEnterprise: [ + "GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}" ], - listOrgPatternConfigs: [ - "GET /orgs/{org}/secret-scanning/pattern-configurations" + setConfigurationAsDefault: [ + "PUT /orgs/{org}/code-security/configurations/{configuration_id}/defaults" ], - updateAlert: [ - "PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" + setConfigurationAsDefaultForEnterprise: [ + "PUT /enterprises/{enterprise}/code-security/configurations/{configuration_id}/defaults" ], - updateOrgPatternConfigs: [ - "PATCH /orgs/{org}/secret-scanning/pattern-configurations" + updateConfiguration: [ + "PATCH /orgs/{org}/code-security/configurations/{configuration_id}" + ], + updateEnterpriseConfiguration: [ + "PATCH /enterprises/{enterprise}/code-security/configurations/{configuration_id}" ] }, - securityAdvisories: { - createFork: [ - "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks" + codesOfConduct: { + getAllCodesOfConduct: ["GET /codes_of_conduct"], + getConductCode: ["GET /codes_of_conduct/{key}"] + }, + codespaces: { + addRepositoryForSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" ], - createPrivateVulnerabilityReport: [ - "POST /repos/{owner}/{repo}/security-advisories/reports" + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" ], - createRepositoryAdvisory: [ - "POST /repos/{owner}/{repo}/security-advisories" + checkPermissionsForDevcontainer: [ + "GET /repos/{owner}/{repo}/codespaces/permissions_check" ], - createRepositoryAdvisoryCveRequest: [ - "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve" + codespaceMachinesForAuthenticatedUser: [ + "GET /user/codespaces/{codespace_name}/machines" ], - getGlobalAdvisory: ["GET /advisories/{ghsa_id}"], - getRepositoryAdvisory: [ - "GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}" + createForAuthenticatedUser: ["POST /user/codespaces"], + createOrUpdateOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}" ], - listGlobalAdvisories: ["GET /advisories"], - listOrgRepositoryAdvisories: ["GET /orgs/{org}/security-advisories"], - listRepositoryAdvisories: ["GET /repos/{owner}/{repo}/security-advisories"], - updateRepositoryAdvisory: [ - "PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}" - ] - }, - teams: { - addOrUpdateMembershipForUserInOrg: [ - "PUT /orgs/{org}/teams/{team_slug}/memberships/{username}" + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" ], - addOrUpdateRepoPermissionsInOrg: [ - "PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + createOrUpdateSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}" ], - checkPermissionsForRepoInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + createWithPrForAuthenticatedUser: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces" ], - create: ["POST /orgs/{org}/teams"], - createDiscussionCommentInOrg: [ - "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" + createWithRepoForAuthenticatedUser: [ + "POST /repos/{owner}/{repo}/codespaces" ], - createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"], - deleteDiscussionCommentInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + deleteForAuthenticatedUser: ["DELETE /user/codespaces/{codespace_name}"], + deleteFromOrganization: [ + "DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}" ], - deleteDiscussionInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + deleteOrgSecret: ["DELETE /orgs/{org}/codespaces/secrets/{secret_name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" ], - deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"], - getByName: ["GET /orgs/{org}/teams/{team_slug}"], - getDiscussionCommentInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + deleteSecretForAuthenticatedUser: [ + "DELETE /user/codespaces/secrets/{secret_name}" ], - getDiscussionInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + exportForAuthenticatedUser: [ + "POST /user/codespaces/{codespace_name}/exports" ], - getMembershipForUserInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/memberships/{username}" + getCodespacesForUserInOrg: [ + "GET /orgs/{org}/members/{username}/codespaces" ], - list: ["GET /orgs/{org}/teams"], - listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"], - listDiscussionCommentsInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" + getExportDetailsForAuthenticatedUser: [ + "GET /user/codespaces/{codespace_name}/exports/{export_id}" ], - listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"], - listForAuthenticatedUser: ["GET /user/teams"], - listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"], - listPendingInvitationsInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/invitations" + getForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}"], + getOrgPublicKey: ["GET /orgs/{org}/codespaces/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/codespaces/secrets/{secret_name}"], + getPublicKeyForAuthenticatedUser: [ + "GET /user/codespaces/secrets/public-key" ], - listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"], - removeMembershipForUserInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}" + getRepoPublicKey: [ + "GET /repos/{owner}/{repo}/codespaces/secrets/public-key" ], - removeRepoInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + getRepoSecret: [ + "GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" ], - updateDiscussionCommentInOrg: [ - "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + getSecretForAuthenticatedUser: [ + "GET /user/codespaces/secrets/{secret_name}" ], - updateDiscussionInOrg: [ - "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + listDevcontainersInRepositoryForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/devcontainers" ], - updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"] - }, - users: { - addEmailForAuthenticated: [ - "POST /user/emails", + listForAuthenticatedUser: ["GET /user/codespaces"], + listInOrganization: [ + "GET /orgs/{org}/codespaces", {}, - { renamed: ["users", "addEmailForAuthenticatedUser"] } + { renamedParameters: { org_id: "org" } } ], - addEmailForAuthenticatedUser: ["POST /user/emails"], - addSocialAccountForAuthenticatedUser: ["POST /user/social_accounts"], - block: ["PUT /user/blocks/{username}"], - checkBlocked: ["GET /user/blocks/{username}"], - checkFollowingForUser: ["GET /users/{username}/following/{target_user}"], - checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"], - createGpgKeyForAuthenticated: [ - "POST /user/gpg_keys", - {}, - { renamed: ["users", "createGpgKeyForAuthenticatedUser"] } + listInRepositoryForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces" ], - createGpgKeyForAuthenticatedUser: ["POST /user/gpg_keys"], - createPublicSshKeyForAuthenticated: [ - "POST /user/keys", - {}, - { renamed: ["users", "createPublicSshKeyForAuthenticatedUser"] } + listOrgSecrets: ["GET /orgs/{org}/codespaces/secrets"], + listRepoSecrets: ["GET /repos/{owner}/{repo}/codespaces/secrets"], + listRepositoriesForSecretForAuthenticatedUser: [ + "GET /user/codespaces/secrets/{secret_name}/repositories" ], - createPublicSshKeyForAuthenticatedUser: ["POST /user/keys"], - createSshSigningKeyForAuthenticatedUser: ["POST /user/ssh_signing_keys"], - deleteAttestationsBulk: [ - "POST /users/{username}/attestations/delete-request" + listSecretsForAuthenticatedUser: ["GET /user/codespaces/secrets"], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories" ], - deleteAttestationsById: [ - "DELETE /users/{username}/attestations/{attestation_id}" + preFlightWithRepoForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/new" ], - deleteAttestationsBySubjectDigest: [ - "DELETE /users/{username}/attestations/digest/{subject_digest}" + publishForAuthenticatedUser: [ + "POST /user/codespaces/{codespace_name}/publish" ], - deleteEmailForAuthenticated: [ - "DELETE /user/emails", - {}, - { renamed: ["users", "deleteEmailForAuthenticatedUser"] } + removeRepositoryForSecretForAuthenticatedUser: [ + "DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" ], - deleteEmailForAuthenticatedUser: ["DELETE /user/emails"], - deleteGpgKeyForAuthenticated: [ - "DELETE /user/gpg_keys/{gpg_key_id}", - {}, - { renamed: ["users", "deleteGpgKeyForAuthenticatedUser"] } + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" ], - deleteGpgKeyForAuthenticatedUser: ["DELETE /user/gpg_keys/{gpg_key_id}"], - deletePublicSshKeyForAuthenticated: [ - "DELETE /user/keys/{key_id}", - {}, - { renamed: ["users", "deletePublicSshKeyForAuthenticatedUser"] } + repoMachinesForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/machines" ], - deletePublicSshKeyForAuthenticatedUser: ["DELETE /user/keys/{key_id}"], - deleteSocialAccountForAuthenticatedUser: ["DELETE /user/social_accounts"], - deleteSshSigningKeyForAuthenticatedUser: [ - "DELETE /user/ssh_signing_keys/{ssh_signing_key_id}" + setRepositoriesForSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}/repositories" ], - follow: ["PUT /user/following/{username}"], - getAuthenticated: ["GET /user"], - getById: ["GET /user/{account_id}"], - getByUsername: ["GET /users/{username}"], - getContextForUser: ["GET /users/{username}/hovercard"], - getGpgKeyForAuthenticated: [ - "GET /user/gpg_keys/{gpg_key_id}", - {}, - { renamed: ["users", "getGpgKeyForAuthenticatedUser"] } + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories" ], - getGpgKeyForAuthenticatedUser: ["GET /user/gpg_keys/{gpg_key_id}"], - getPublicSshKeyForAuthenticated: [ - "GET /user/keys/{key_id}", - {}, - { renamed: ["users", "getPublicSshKeyForAuthenticatedUser"] } + startForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/start"], + stopForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/stop"], + stopInOrganization: [ + "POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop" ], - getPublicSshKeyForAuthenticatedUser: ["GET /user/keys/{key_id}"], - getSshSigningKeyForAuthenticatedUser: [ - "GET /user/ssh_signing_keys/{ssh_signing_key_id}" + updateForAuthenticatedUser: ["PATCH /user/codespaces/{codespace_name}"] + }, + copilot: { + addCopilotSeatsForTeams: [ + "POST /orgs/{org}/copilot/billing/selected_teams" ], - list: ["GET /users"], - listAttestations: ["GET /users/{username}/attestations/{subject_digest}"], - listAttestationsBulk: [ - "POST /users/{username}/attestations/bulk-list{?per_page,before,after}" + addCopilotSeatsForUsers: [ + "POST /orgs/{org}/copilot/billing/selected_users" ], - listBlockedByAuthenticated: [ - "GET /user/blocks", - {}, - { renamed: ["users", "listBlockedByAuthenticatedUser"] } + cancelCopilotSeatAssignmentForTeams: [ + "DELETE /orgs/{org}/copilot/billing/selected_teams" ], - listBlockedByAuthenticatedUser: ["GET /user/blocks"], - listEmailsForAuthenticated: [ - "GET /user/emails", - {}, - { renamed: ["users", "listEmailsForAuthenticatedUser"] } + cancelCopilotSeatAssignmentForUsers: [ + "DELETE /orgs/{org}/copilot/billing/selected_users" ], - listEmailsForAuthenticatedUser: ["GET /user/emails"], - listFollowedByAuthenticated: [ - "GET /user/following", - {}, - { renamed: ["users", "listFollowedByAuthenticatedUser"] } + copilotMetricsForOrganization: ["GET /orgs/{org}/copilot/metrics"], + copilotMetricsForTeam: ["GET /orgs/{org}/team/{team_slug}/copilot/metrics"], + getCopilotOrganizationDetails: ["GET /orgs/{org}/copilot/billing"], + getCopilotSeatDetailsForUser: [ + "GET /orgs/{org}/members/{username}/copilot" ], - listFollowedByAuthenticatedUser: ["GET /user/following"], - listFollowersForAuthenticatedUser: ["GET /user/followers"], - listFollowersForUser: ["GET /users/{username}/followers"], - listFollowingForUser: ["GET /users/{username}/following"], - listGpgKeysForAuthenticated: [ - "GET /user/gpg_keys", - {}, - { renamed: ["users", "listGpgKeysForAuthenticatedUser"] } + listCopilotSeats: ["GET /orgs/{org}/copilot/billing/seats"] + }, + credentials: { revoke: ["POST /credentials/revoke"] }, + dependabot: { + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" ], - listGpgKeysForAuthenticatedUser: ["GET /user/gpg_keys"], - listGpgKeysForUser: ["GET /users/{username}/gpg_keys"], - listPublicEmailsForAuthenticated: [ - "GET /user/public_emails", - {}, - { renamed: ["users", "listPublicEmailsForAuthenticatedUser"] } + createOrUpdateOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}" ], - listPublicEmailsForAuthenticatedUser: ["GET /user/public_emails"], - listPublicKeysForUser: ["GET /users/{username}/keys"], - listPublicSshKeysForAuthenticated: [ - "GET /user/keys", - {}, - { renamed: ["users", "listPublicSshKeysForAuthenticatedUser"] } + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" ], - listPublicSshKeysForAuthenticatedUser: ["GET /user/keys"], - listSocialAccountsForAuthenticatedUser: ["GET /user/social_accounts"], - listSocialAccountsForUser: ["GET /users/{username}/social_accounts"], - listSshSigningKeysForAuthenticatedUser: ["GET /user/ssh_signing_keys"], - listSshSigningKeysForUser: ["GET /users/{username}/ssh_signing_keys"], - setPrimaryEmailVisibilityForAuthenticated: [ - "PATCH /user/email/visibility", - {}, - { renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"] } + deleteOrgSecret: ["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" ], - setPrimaryEmailVisibilityForAuthenticatedUser: [ - "PATCH /user/email/visibility" + getAlert: ["GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"], + getOrgPublicKey: ["GET /orgs/{org}/dependabot/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/dependabot/secrets/{secret_name}"], + getRepoPublicKey: [ + "GET /repos/{owner}/{repo}/dependabot/secrets/public-key" ], - unblock: ["DELETE /user/blocks/{username}"], - unfollow: ["DELETE /user/following/{username}"], - updateAuthenticated: ["PATCH /user"] - } -}; -var endpoints_default = Endpoints; - -// node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/endpoints-to-methods.js -var endpointMethodsMap = /* @__PURE__ */ new Map(); -for (const [scope, endpoints] of Object.entries(endpoints_default)) { - for (const [methodName, endpoint2] of Object.entries(endpoints)) { - const [route, defaults2, decorations] = endpoint2; - const [method, url] = route.split(/ /); - const endpointDefaults = Object.assign( - { - method, - url - }, - defaults2 - ); - if (!endpointMethodsMap.has(scope)) { - endpointMethodsMap.set(scope, /* @__PURE__ */ new Map()); - } - endpointMethodsMap.get(scope).set(methodName, { - scope, - methodName, - endpointDefaults, - decorations - }); - } -} -var handler = { - has({ scope }, methodName) { - return endpointMethodsMap.get(scope).has(methodName); - }, - getOwnPropertyDescriptor(target, methodName) { - return { - value: this.get(target, methodName), - // ensures method is in the cache - configurable: true, - writable: true, - enumerable: true - }; - }, - defineProperty(target, methodName, descriptor) { - Object.defineProperty(target.cache, methodName, descriptor); - return true; - }, - deleteProperty(target, methodName) { - delete target.cache[methodName]; - return true; + getRepoSecret: [ + "GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" + ], + listAlertsForEnterprise: [ + "GET /enterprises/{enterprise}/dependabot/alerts" + ], + listAlertsForOrg: ["GET /orgs/{org}/dependabot/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/dependabot/alerts"], + listOrgSecrets: ["GET /orgs/{org}/dependabot/secrets"], + listRepoSecrets: ["GET /repos/{owner}/{repo}/dependabot/secrets"], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories" + ], + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" + ], + repositoryAccessForOrg: [ + "GET /organizations/{org}/dependabot/repository-access" + ], + setRepositoryAccessDefaultLevel: [ + "PUT /organizations/{org}/dependabot/repository-access/default-level" + ], + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories" + ], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}" + ], + updateRepositoryAccessForOrg: [ + "PATCH /organizations/{org}/dependabot/repository-access" + ] }, - ownKeys({ scope }) { - return [...endpointMethodsMap.get(scope).keys()]; + dependencyGraph: { + createRepositorySnapshot: [ + "POST /repos/{owner}/{repo}/dependency-graph/snapshots" + ], + diffRange: [ + "GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}" + ], + exportSbom: ["GET /repos/{owner}/{repo}/dependency-graph/sbom"] }, - set(target, methodName, value) { - return target.cache[methodName] = value; + emojis: { get: ["GET /emojis"] }, + enterpriseTeamMemberships: { + add: [ + "PUT /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}" + ], + bulkAdd: [ + "POST /enterprises/{enterprise}/teams/{enterprise-team}/memberships/add" + ], + bulkRemove: [ + "POST /enterprises/{enterprise}/teams/{enterprise-team}/memberships/remove" + ], + get: [ + "GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}" + ], + list: ["GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships"], + remove: [ + "DELETE /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}" + ] }, - get({ octokit, scope, cache }, methodName) { - if (cache[methodName]) { - return cache[methodName]; - } - const method = endpointMethodsMap.get(scope).get(methodName); - if (!method) { - return void 0; - } - const { endpointDefaults, decorations } = method; - if (decorations) { - cache[methodName] = decorate( - octokit, - scope, - methodName, - endpointDefaults, - decorations - ); - } else { - cache[methodName] = octokit.request.defaults(endpointDefaults); - } - return cache[methodName]; - } -}; -function endpointsToMethods(octokit) { - const newMethods = {}; - for (const scope of endpointMethodsMap.keys()) { - newMethods[scope] = new Proxy({ octokit, scope, cache: {} }, handler); - } - return newMethods; -} -function decorate(octokit, scope, methodName, defaults2, decorations) { - const requestWithDefaults = octokit.request.defaults(defaults2); - function withDecorations(...args) { - let options = requestWithDefaults.endpoint.merge(...args); - if (decorations.mapToData) { - options = Object.assign({}, options, { - data: options[decorations.mapToData], - [decorations.mapToData]: void 0 - }); - return requestWithDefaults(options); - } - if (decorations.renamed) { - const [newScope, newMethodName] = decorations.renamed; - octokit.log.warn( - `octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()` - ); - } - if (decorations.deprecated) { - octokit.log.warn(decorations.deprecated); - } - if (decorations.renamedParameters) { - const options2 = requestWithDefaults.endpoint.merge(...args); - for (const [name, alias] of Object.entries( - decorations.renamedParameters - )) { - if (name in options2) { - octokit.log.warn( - `"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead` - ); - if (!(alias in options2)) { - options2[alias] = options2[name]; - } - delete options2[name]; - } - } - return requestWithDefaults(options2); - } - return requestWithDefaults(...args); - } - return Object.assign(withDecorations, requestWithDefaults); -} - -// node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/index.js -function restEndpointMethods(octokit) { - const api = endpointsToMethods(octokit); - return { - rest: api - }; -} -restEndpointMethods.VERSION = VERSION5; -function legacyRestEndpointMethods(octokit) { - const api = endpointsToMethods(octokit); - return { - ...api, - rest: api - }; -} -legacyRestEndpointMethods.VERSION = VERSION5; - -// node_modules/@octokit/plugin-paginate-rest/dist-bundle/index.js -var VERSION6 = "0.0.0-development"; -function normalizePaginatedListResponse(response) { - if (!response.data) { - return { - ...response, - data: [] - }; - } - const responseNeedsNormalization = ("total_count" in response.data || "total_commits" in response.data) && !("url" in response.data); - if (!responseNeedsNormalization) return response; - const incompleteResults = response.data.incomplete_results; - const repositorySelection = response.data.repository_selection; - const totalCount = response.data.total_count; - const totalCommits = response.data.total_commits; - delete response.data.incomplete_results; - delete response.data.repository_selection; - delete response.data.total_count; - delete response.data.total_commits; - const namespaceKey = Object.keys(response.data)[0]; - const data = response.data[namespaceKey]; - response.data = data; - if (typeof incompleteResults !== "undefined") { - response.data.incomplete_results = incompleteResults; - } - if (typeof repositorySelection !== "undefined") { - response.data.repository_selection = repositorySelection; - } - response.data.total_count = totalCount; - response.data.total_commits = totalCommits; - return response; -} -function iterator(octokit, route, parameters) { - const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters); - const requestMethod = typeof route === "function" ? route : octokit.request; - const method = options.method; - const headers = options.headers; - let url = options.url; - return { - [Symbol.asyncIterator]: () => ({ - async next() { - if (!url) return { done: true }; - try { - const response = await requestMethod({ method, url, headers }); - const normalizedResponse = normalizePaginatedListResponse(response); - url = ((normalizedResponse.headers.link || "").match( - /<([^<>]+)>;\s*rel="next"/ - ) || [])[1]; - if (!url && "total_commits" in normalizedResponse.data) { - const parsedUrl = new URL(normalizedResponse.url); - const params = parsedUrl.searchParams; - const page = parseInt(params.get("page") || "1", 10); - const per_page = parseInt(params.get("per_page") || "250", 10); - if (page * per_page < normalizedResponse.data.total_commits) { - params.set("page", String(page + 1)); - url = parsedUrl.toString(); - } - } - return { value: normalizedResponse }; - } catch (error3) { - if (error3.status !== 409) throw error3; - url = ""; - return { - value: { - status: 200, - headers: {}, - data: [] - } - }; - } - } - }) - }; -} -function paginate(octokit, route, parameters, mapFn) { - if (typeof parameters === "function") { - mapFn = parameters; - parameters = void 0; - } - return gather( - octokit, - [], - iterator(octokit, route, parameters)[Symbol.asyncIterator](), - mapFn - ); -} -function gather(octokit, results, iterator2, mapFn) { - return iterator2.next().then((result) => { - if (result.done) { - return results; - } - let earlyExit = false; - function done() { - earlyExit = true; - } - results = results.concat( - mapFn ? mapFn(result.value, done) : result.value.data - ); - if (earlyExit) { - return results; - } - return gather(octokit, results, iterator2, mapFn); - }); -} -var composePaginateRest = Object.assign(paginate, { - iterator -}); -function paginateRest(octokit) { - return { - paginate: Object.assign(paginate.bind(null, octokit), { - iterator: iterator.bind(null, octokit) - }) - }; -} -paginateRest.VERSION = VERSION6; - -// node_modules/@actions/github/lib/utils.js -var context = new Context(); -var baseUrl = getApiBaseUrl(); -var defaults = { - baseUrl, - request: { - agent: getProxyAgent(baseUrl), - fetch: getProxyFetch(baseUrl) - } -}; -var GitHub = Octokit.plugin(restEndpointMethods, paginateRest).defaults(defaults); - -// node_modules/@actions/github/lib/github.js -var context2 = new Context(); - -// node_modules/@actions/http-client/lib/index.js -var http = __toESM(require("http"), 1); -var https = __toESM(require("https"), 1); - -// node_modules/@actions/http-client/lib/proxy.js -function getProxyUrl(reqUrl) { - const usingSsl = reqUrl.protocol === "https:"; - if (checkBypass(reqUrl)) { - return void 0; - } - const proxyVar = (() => { - if (usingSsl) { - return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; - } else { - return process.env["http_proxy"] || process.env["HTTP_PROXY"]; - } - })(); - if (proxyVar) { - try { - return new DecodedURL(proxyVar); - } catch (_a) { - if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) - return new DecodedURL(`http://${proxyVar}`); - } - } else { - return void 0; - } -} -function checkBypass(reqUrl) { - if (!reqUrl.hostname) { - return false; - } - const reqHost = reqUrl.hostname; - if (isLoopbackAddress(reqHost)) { - return true; - } - const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; - if (!noProxy) { - return false; - } - let reqPort; - if (reqUrl.port) { - reqPort = Number(reqUrl.port); - } else if (reqUrl.protocol === "http:") { - reqPort = 80; - } else if (reqUrl.protocol === "https:") { - reqPort = 443; - } - const upperReqHosts = [reqUrl.hostname.toUpperCase()]; - if (typeof reqPort === "number") { - upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); - } - for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { - if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { - return true; - } - } - return false; -} -function isLoopbackAddress(host) { - const hostLower = host.toLowerCase(); - return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); -} -var DecodedURL = class extends URL { - constructor(url, base) { - super(url, base); - this._decodedUsername = decodeURIComponent(super.username); - this._decodedPassword = decodeURIComponent(super.password); - } - get username() { - return this._decodedUsername; - } - get password() { - return this._decodedPassword; - } -}; - -// node_modules/@actions/http-client/lib/index.js -var tunnel = __toESM(require_tunnel2(), 1); -var import_undici2 = __toESM(require_undici(), 1); -var __awaiter2 = function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); - } - return new (P || (P = 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 HttpCodes; -(function(HttpCodes2) { - HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; - HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; - HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; - HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; - HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; - HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; - HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; - HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; - HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; - HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; - HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; - HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; - HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; - HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; - HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; - HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; - HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; - HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; - HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; - HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; - HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; - HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; - HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; - HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; - HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; - HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; - HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; -})(HttpCodes || (HttpCodes = {})); -var Headers; -(function(Headers2) { - Headers2["Accept"] = "accept"; - Headers2["ContentType"] = "content-type"; -})(Headers || (Headers = {})); -var MediaTypes; -(function(MediaTypes2) { - MediaTypes2["ApplicationJson"] = "application/json"; -})(MediaTypes || (MediaTypes = {})); -var HttpRedirectCodes = [ - HttpCodes.MovedPermanently, - HttpCodes.ResourceMoved, - HttpCodes.SeeOther, - HttpCodes.TemporaryRedirect, - HttpCodes.PermanentRedirect -]; -var HttpResponseRetryCodes = [ - HttpCodes.BadGateway, - HttpCodes.ServiceUnavailable, - HttpCodes.GatewayTimeout -]; -var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; -var ExponentialBackoffCeiling = 10; -var ExponentialBackoffTimeSlice = 5; -var HttpClientError = class _HttpClientError extends Error { - constructor(message, statusCode) { - super(message); - this.name = "HttpClientError"; - this.statusCode = statusCode; - Object.setPrototypeOf(this, _HttpClientError.prototype); - } -}; -var HttpClientResponse = class { - constructor(message) { - this.message = message; - } - readBody() { - return __awaiter2(this, void 0, void 0, function* () { - return new Promise((resolve) => __awaiter2(this, void 0, void 0, function* () { - let output = Buffer.alloc(0); - this.message.on("data", (chunk) => { - output = Buffer.concat([output, chunk]); - }); - this.message.on("end", () => { - resolve(output.toString()); - }); - })); - }); - } - readBodyBuffer() { - return __awaiter2(this, void 0, void 0, function* () { - return new Promise((resolve) => __awaiter2(this, void 0, void 0, function* () { - const chunks = []; - this.message.on("data", (chunk) => { - chunks.push(chunk); - }); - this.message.on("end", () => { - resolve(Buffer.concat(chunks)); - }); - })); - }); - } -}; -var HttpClient2 = class { - constructor(userAgent2, handlers, requestOptions) { - this._ignoreSslError = false; - this._allowRedirects = true; - this._allowRedirectDowngrade = false; - this._maxRedirects = 50; - this._allowRetries = false; - this._maxRetries = 1; - this._keepAlive = false; - this._disposed = false; - this.userAgent = this._getUserAgentWithOrchestrationId(userAgent2); - this.handlers = handlers || []; - this.requestOptions = requestOptions; - if (requestOptions) { - if (requestOptions.ignoreSslError != null) { - this._ignoreSslError = requestOptions.ignoreSslError; - } - this._socketTimeout = requestOptions.socketTimeout; - if (requestOptions.allowRedirects != null) { - this._allowRedirects = requestOptions.allowRedirects; - } - if (requestOptions.allowRedirectDowngrade != null) { - this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; - } - if (requestOptions.maxRedirects != null) { - this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); - } - if (requestOptions.keepAlive != null) { - this._keepAlive = requestOptions.keepAlive; + enterpriseTeamOrganizations: { + add: [ + "PUT /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}" + ], + bulkAdd: [ + "POST /enterprises/{enterprise}/teams/{enterprise-team}/organizations/add" + ], + bulkRemove: [ + "POST /enterprises/{enterprise}/teams/{enterprise-team}/organizations/remove" + ], + delete: [ + "DELETE /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}" + ], + getAssignment: [ + "GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}" + ], + getAssignments: [ + "GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations" + ] + }, + enterpriseTeams: { + create: ["POST /enterprises/{enterprise}/teams"], + delete: ["DELETE /enterprises/{enterprise}/teams/{team_slug}"], + get: ["GET /enterprises/{enterprise}/teams/{team_slug}"], + list: ["GET /enterprises/{enterprise}/teams"], + update: ["PATCH /enterprises/{enterprise}/teams/{team_slug}"] + }, + gists: { + checkIsStarred: ["GET /gists/{gist_id}/star"], + create: ["POST /gists"], + createComment: ["POST /gists/{gist_id}/comments"], + delete: ["DELETE /gists/{gist_id}"], + deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"], + fork: ["POST /gists/{gist_id}/forks"], + get: ["GET /gists/{gist_id}"], + getComment: ["GET /gists/{gist_id}/comments/{comment_id}"], + getRevision: ["GET /gists/{gist_id}/{sha}"], + list: ["GET /gists"], + listComments: ["GET /gists/{gist_id}/comments"], + listCommits: ["GET /gists/{gist_id}/commits"], + listForUser: ["GET /users/{username}/gists"], + listForks: ["GET /gists/{gist_id}/forks"], + listPublic: ["GET /gists/public"], + listStarred: ["GET /gists/starred"], + star: ["PUT /gists/{gist_id}/star"], + unstar: ["DELETE /gists/{gist_id}/star"], + update: ["PATCH /gists/{gist_id}"], + updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"] + }, + git: { + createBlob: ["POST /repos/{owner}/{repo}/git/blobs"], + createCommit: ["POST /repos/{owner}/{repo}/git/commits"], + createRef: ["POST /repos/{owner}/{repo}/git/refs"], + createTag: ["POST /repos/{owner}/{repo}/git/tags"], + createTree: ["POST /repos/{owner}/{repo}/git/trees"], + deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"], + getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"], + getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"], + getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"], + getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"], + getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"], + listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"], + updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"] + }, + gitignore: { + getAllTemplates: ["GET /gitignore/templates"], + getTemplate: ["GET /gitignore/templates/{name}"] + }, + hostedCompute: { + createNetworkConfigurationForOrg: [ + "POST /orgs/{org}/settings/network-configurations" + ], + deleteNetworkConfigurationFromOrg: [ + "DELETE /orgs/{org}/settings/network-configurations/{network_configuration_id}" + ], + getNetworkConfigurationForOrg: [ + "GET /orgs/{org}/settings/network-configurations/{network_configuration_id}" + ], + getNetworkSettingsForOrg: [ + "GET /orgs/{org}/settings/network-settings/{network_settings_id}" + ], + listNetworkConfigurationsForOrg: [ + "GET /orgs/{org}/settings/network-configurations" + ], + updateNetworkConfigurationForOrg: [ + "PATCH /orgs/{org}/settings/network-configurations/{network_configuration_id}" + ] + }, + interactions: { + getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"], + getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"], + getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"], + getRestrictionsForYourPublicRepos: [ + "GET /user/interaction-limits", + {}, + { renamed: ["interactions", "getRestrictionsForAuthenticatedUser"] } + ], + removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"], + removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"], + removeRestrictionsForRepo: [ + "DELETE /repos/{owner}/{repo}/interaction-limits" + ], + removeRestrictionsForYourPublicRepos: [ + "DELETE /user/interaction-limits", + {}, + { renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"] } + ], + setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"], + setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"], + setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"], + setRestrictionsForYourPublicRepos: [ + "PUT /user/interaction-limits", + {}, + { renamed: ["interactions", "setRestrictionsForAuthenticatedUser"] } + ] + }, + issues: { + addAssignees: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/assignees" + ], + addBlockedByDependency: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by" + ], + addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"], + addSubIssue: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/sub_issues" + ], + checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"], + checkUserCanBeAssignedToIssue: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}" + ], + create: ["POST /repos/{owner}/{repo}/issues"], + createComment: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/comments" + ], + createLabel: ["POST /repos/{owner}/{repo}/labels"], + createMilestone: ["POST /repos/{owner}/{repo}/milestones"], + deleteComment: [ + "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}" + ], + deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"], + deleteMilestone: [ + "DELETE /repos/{owner}/{repo}/milestones/{milestone_number}" + ], + get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"], + getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"], + getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"], + getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"], + getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"], + getParent: ["GET /repos/{owner}/{repo}/issues/{issue_number}/parent"], + list: ["GET /issues"], + listAssignees: ["GET /repos/{owner}/{repo}/assignees"], + listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"], + listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"], + listDependenciesBlockedBy: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by" + ], + listDependenciesBlocking: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocking" + ], + listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"], + listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"], + listEventsForTimeline: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline" + ], + listForAuthenticatedUser: ["GET /user/issues"], + listForOrg: ["GET /orgs/{org}/issues"], + listForRepo: ["GET /repos/{owner}/{repo}/issues"], + listLabelsForMilestone: [ + "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels" + ], + listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"], + listLabelsOnIssue: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/labels" + ], + listMilestones: ["GET /repos/{owner}/{repo}/milestones"], + listSubIssues: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/sub_issues" + ], + lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"], + removeAllLabels: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels" + ], + removeAssignees: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees" + ], + removeDependencyBlockedBy: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by/{issue_id}" + ], + removeLabel: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}" + ], + removeSubIssue: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/sub_issue" + ], + reprioritizeSubIssue: [ + "PATCH /repos/{owner}/{repo}/issues/{issue_number}/sub_issues/priority" + ], + setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"], + unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"], + update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"], + updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"], + updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"], + updateMilestone: [ + "PATCH /repos/{owner}/{repo}/milestones/{milestone_number}" + ] + }, + licenses: { + get: ["GET /licenses/{license}"], + getAllCommonlyUsed: ["GET /licenses"], + getForRepo: ["GET /repos/{owner}/{repo}/license"] + }, + markdown: { + render: ["POST /markdown"], + renderRaw: [ + "POST /markdown/raw", + { headers: { "content-type": "text/plain; charset=utf-8" } } + ] + }, + meta: { + get: ["GET /meta"], + getAllVersions: ["GET /versions"], + getOctocat: ["GET /octocat"], + getZen: ["GET /zen"], + root: ["GET /"] + }, + migrations: { + deleteArchiveForAuthenticatedUser: [ + "DELETE /user/migrations/{migration_id}/archive" + ], + deleteArchiveForOrg: [ + "DELETE /orgs/{org}/migrations/{migration_id}/archive" + ], + downloadArchiveForOrg: [ + "GET /orgs/{org}/migrations/{migration_id}/archive" + ], + getArchiveForAuthenticatedUser: [ + "GET /user/migrations/{migration_id}/archive" + ], + getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"], + getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"], + listForAuthenticatedUser: ["GET /user/migrations"], + listForOrg: ["GET /orgs/{org}/migrations"], + listReposForAuthenticatedUser: [ + "GET /user/migrations/{migration_id}/repositories" + ], + listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories"], + listReposForUser: [ + "GET /user/migrations/{migration_id}/repositories", + {}, + { renamed: ["migrations", "listReposForAuthenticatedUser"] } + ], + startForAuthenticatedUser: ["POST /user/migrations"], + startForOrg: ["POST /orgs/{org}/migrations"], + unlockRepoForAuthenticatedUser: [ + "DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock" + ], + unlockRepoForOrg: [ + "DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock" + ] + }, + oidc: { + getOidcCustomSubTemplateForOrg: [ + "GET /orgs/{org}/actions/oidc/customization/sub" + ], + updateOidcCustomSubTemplateForOrg: [ + "PUT /orgs/{org}/actions/oidc/customization/sub" + ] + }, + orgs: { + addSecurityManagerTeam: [ + "PUT /orgs/{org}/security-managers/teams/{team_slug}", + {}, + { + deprecated: "octokit.rest.orgs.addSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#add-a-security-manager-team" } - if (requestOptions.allowRetries != null) { - this._allowRetries = requestOptions.allowRetries; + ], + assignTeamToOrgRole: [ + "PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" + ], + assignUserToOrgRole: [ + "PUT /orgs/{org}/organization-roles/users/{username}/{role_id}" + ], + blockUser: ["PUT /orgs/{org}/blocks/{username}"], + cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"], + checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"], + checkMembershipForUser: ["GET /orgs/{org}/members/{username}"], + checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"], + convertMemberToOutsideCollaborator: [ + "PUT /orgs/{org}/outside_collaborators/{username}" + ], + createArtifactStorageRecord: [ + "POST /orgs/{org}/artifacts/metadata/storage-record" + ], + createInvitation: ["POST /orgs/{org}/invitations"], + createIssueType: ["POST /orgs/{org}/issue-types"], + createWebhook: ["POST /orgs/{org}/hooks"], + customPropertiesForOrgsCreateOrUpdateOrganizationValues: [ + "PATCH /organizations/{org}/org-properties/values" + ], + customPropertiesForOrgsGetOrganizationValues: [ + "GET /organizations/{org}/org-properties/values" + ], + customPropertiesForReposCreateOrUpdateOrganizationDefinition: [ + "PUT /orgs/{org}/properties/schema/{custom_property_name}" + ], + customPropertiesForReposCreateOrUpdateOrganizationDefinitions: [ + "PATCH /orgs/{org}/properties/schema" + ], + customPropertiesForReposCreateOrUpdateOrganizationValues: [ + "PATCH /orgs/{org}/properties/values" + ], + customPropertiesForReposDeleteOrganizationDefinition: [ + "DELETE /orgs/{org}/properties/schema/{custom_property_name}" + ], + customPropertiesForReposGetOrganizationDefinition: [ + "GET /orgs/{org}/properties/schema/{custom_property_name}" + ], + customPropertiesForReposGetOrganizationDefinitions: [ + "GET /orgs/{org}/properties/schema" + ], + customPropertiesForReposGetOrganizationValues: [ + "GET /orgs/{org}/properties/values" + ], + delete: ["DELETE /orgs/{org}"], + deleteAttestationsBulk: ["POST /orgs/{org}/attestations/delete-request"], + deleteAttestationsById: [ + "DELETE /orgs/{org}/attestations/{attestation_id}" + ], + deleteAttestationsBySubjectDigest: [ + "DELETE /orgs/{org}/attestations/digest/{subject_digest}" + ], + deleteIssueType: ["DELETE /orgs/{org}/issue-types/{issue_type_id}"], + deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], + disableSelectedRepositoryImmutableReleasesOrganization: [ + "DELETE /orgs/{org}/settings/immutable-releases/repositories/{repository_id}" + ], + enableSelectedRepositoryImmutableReleasesOrganization: [ + "PUT /orgs/{org}/settings/immutable-releases/repositories/{repository_id}" + ], + get: ["GET /orgs/{org}"], + getImmutableReleasesSettings: [ + "GET /orgs/{org}/settings/immutable-releases" + ], + getImmutableReleasesSettingsRepositories: [ + "GET /orgs/{org}/settings/immutable-releases/repositories" + ], + getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], + getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], + getOrgRole: ["GET /orgs/{org}/organization-roles/{role_id}"], + getOrgRulesetHistory: ["GET /orgs/{org}/rulesets/{ruleset_id}/history"], + getOrgRulesetVersion: [ + "GET /orgs/{org}/rulesets/{ruleset_id}/history/{version_id}" + ], + getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], + getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"], + getWebhookDelivery: [ + "GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}" + ], + list: ["GET /organizations"], + listAppInstallations: ["GET /orgs/{org}/installations"], + listArtifactStorageRecords: [ + "GET /orgs/{org}/artifacts/{subject_digest}/metadata/storage-records" + ], + listAttestationRepositories: ["GET /orgs/{org}/attestations/repositories"], + listAttestations: ["GET /orgs/{org}/attestations/{subject_digest}"], + listAttestationsBulk: [ + "POST /orgs/{org}/attestations/bulk-list{?per_page,before,after}" + ], + listBlockedUsers: ["GET /orgs/{org}/blocks"], + listFailedInvitations: ["GET /orgs/{org}/failed_invitations"], + listForAuthenticatedUser: ["GET /user/orgs"], + listForUser: ["GET /users/{username}/orgs"], + listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"], + listIssueTypes: ["GET /orgs/{org}/issue-types"], + listMembers: ["GET /orgs/{org}/members"], + listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"], + listOrgRoleTeams: ["GET /orgs/{org}/organization-roles/{role_id}/teams"], + listOrgRoleUsers: ["GET /orgs/{org}/organization-roles/{role_id}/users"], + listOrgRoles: ["GET /orgs/{org}/organization-roles"], + listOrganizationFineGrainedPermissions: [ + "GET /orgs/{org}/organization-fine-grained-permissions" + ], + listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"], + listPatGrantRepositories: [ + "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories" + ], + listPatGrantRequestRepositories: [ + "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories" + ], + listPatGrantRequests: ["GET /orgs/{org}/personal-access-token-requests"], + listPatGrants: ["GET /orgs/{org}/personal-access-tokens"], + listPendingInvitations: ["GET /orgs/{org}/invitations"], + listPublicMembers: ["GET /orgs/{org}/public_members"], + listSecurityManagerTeams: [ + "GET /orgs/{org}/security-managers", + {}, + { + deprecated: "octokit.rest.orgs.listSecurityManagerTeams() is deprecated, see https://docs.github.com/rest/orgs/security-managers#list-security-manager-teams" } - if (requestOptions.maxRetries != null) { - this._maxRetries = requestOptions.maxRetries; + ], + listWebhookDeliveries: ["GET /orgs/{org}/hooks/{hook_id}/deliveries"], + listWebhooks: ["GET /orgs/{org}/hooks"], + pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"], + redeliverWebhookDelivery: [ + "POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" + ], + removeMember: ["DELETE /orgs/{org}/members/{username}"], + removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], + removeOutsideCollaborator: [ + "DELETE /orgs/{org}/outside_collaborators/{username}" + ], + removePublicMembershipForAuthenticatedUser: [ + "DELETE /orgs/{org}/public_members/{username}" + ], + removeSecurityManagerTeam: [ + "DELETE /orgs/{org}/security-managers/teams/{team_slug}", + {}, + { + deprecated: "octokit.rest.orgs.removeSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#remove-a-security-manager-team" } - } - } - options(requestUrl, additionalHeaders) { - return __awaiter2(this, void 0, void 0, function* () { - return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); - }); - } - get(requestUrl, additionalHeaders) { - return __awaiter2(this, void 0, void 0, function* () { - return this.request("GET", requestUrl, null, additionalHeaders || {}); - }); - } - del(requestUrl, additionalHeaders) { - return __awaiter2(this, void 0, void 0, function* () { - return this.request("DELETE", requestUrl, null, additionalHeaders || {}); - }); - } - post(requestUrl, data, additionalHeaders) { - return __awaiter2(this, void 0, void 0, function* () { - return this.request("POST", requestUrl, data, additionalHeaders || {}); - }); - } - patch(requestUrl, data, additionalHeaders) { - return __awaiter2(this, void 0, void 0, function* () { - return this.request("PATCH", requestUrl, data, additionalHeaders || {}); - }); - } - put(requestUrl, data, additionalHeaders) { - return __awaiter2(this, void 0, void 0, function* () { - return this.request("PUT", requestUrl, data, additionalHeaders || {}); - }); - } - head(requestUrl, additionalHeaders) { - return __awaiter2(this, void 0, void 0, function* () { - return this.request("HEAD", requestUrl, null, additionalHeaders || {}); - }); - } - sendStream(verb, requestUrl, stream2, additionalHeaders) { - return __awaiter2(this, void 0, void 0, function* () { - return this.request(verb, requestUrl, stream2, additionalHeaders); - }); - } - /** - * Gets a typed object from an endpoint - * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise - */ - getJson(requestUrl_1) { - return __awaiter2(this, arguments, void 0, function* (requestUrl, additionalHeaders = {}) { - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - const res = yield this.get(requestUrl, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - postJson(requestUrl_1, obj_1) { - return __awaiter2(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); - const res = yield this.post(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - putJson(requestUrl_1, obj_1) { - return __awaiter2(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); - const res = yield this.put(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - patchJson(requestUrl_1, obj_1) { - return __awaiter2(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); - const res = yield this.patch(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - /** - * Makes a raw http request. - * All other methods such as get, post, patch, and request ultimately call this. - * Prefer get, del, post and patch - */ - request(verb, requestUrl, data, headers) { - return __awaiter2(this, void 0, void 0, function* () { - if (this._disposed) { - throw new Error("Client has already been disposed."); + ], + reviewPatGrantRequest: [ + "POST /orgs/{org}/personal-access-token-requests/{pat_request_id}" + ], + reviewPatGrantRequestsInBulk: [ + "POST /orgs/{org}/personal-access-token-requests" + ], + revokeAllOrgRolesTeam: [ + "DELETE /orgs/{org}/organization-roles/teams/{team_slug}" + ], + revokeAllOrgRolesUser: [ + "DELETE /orgs/{org}/organization-roles/users/{username}" + ], + revokeOrgRoleTeam: [ + "DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" + ], + revokeOrgRoleUser: [ + "DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}" + ], + setImmutableReleasesSettings: [ + "PUT /orgs/{org}/settings/immutable-releases" + ], + setImmutableReleasesSettingsRepositories: [ + "PUT /orgs/{org}/settings/immutable-releases/repositories" + ], + setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"], + setPublicMembershipForAuthenticatedUser: [ + "PUT /orgs/{org}/public_members/{username}" + ], + unblockUser: ["DELETE /orgs/{org}/blocks/{username}"], + update: ["PATCH /orgs/{org}"], + updateIssueType: ["PUT /orgs/{org}/issue-types/{issue_type_id}"], + updateMembershipForAuthenticatedUser: [ + "PATCH /user/memberships/orgs/{org}" + ], + updatePatAccess: ["POST /orgs/{org}/personal-access-tokens/{pat_id}"], + updatePatAccesses: ["POST /orgs/{org}/personal-access-tokens"], + updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"], + updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"] + }, + packages: { + deletePackageForAuthenticatedUser: [ + "DELETE /user/packages/{package_type}/{package_name}" + ], + deletePackageForOrg: [ + "DELETE /orgs/{org}/packages/{package_type}/{package_name}" + ], + deletePackageForUser: [ + "DELETE /users/{username}/packages/{package_type}/{package_name}" + ], + deletePackageVersionForAuthenticatedUser: [ + "DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + deletePackageVersionForOrg: [ + "DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + deletePackageVersionForUser: [ + "DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getAllPackageVersionsForAPackageOwnedByAnOrg: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", + {}, + { renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"] } + ], + getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions", + {}, + { + renamed: [ + "packages", + "getAllPackageVersionsForPackageOwnedByAuthenticatedUser" + ] } - const parsedUrl = new URL(requestUrl); - let info8 = this._prepareRequest(verb, parsedUrl, headers); - const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; - let numTries = 0; - let response; - do { - response = yield this.requestRaw(info8, data); - if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { - let authenticationHandler; - for (const handler2 of this.handlers) { - if (handler2.canHandleAuthentication(response)) { - authenticationHandler = handler2; - break; - } - } - if (authenticationHandler) { - return authenticationHandler.handleAuthentication(this, info8, data); - } else { - return response; - } - } - let redirectsRemaining = this._maxRedirects; - while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { - const redirectUrl = response.message.headers["location"]; - if (!redirectUrl) { - break; - } - const parsedRedirectUrl = new URL(redirectUrl); - if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { - throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); - } - yield response.readBody(); - if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { - for (const header in headers) { - if (header.toLowerCase() === "authorization") { - delete headers[header]; - } - } - } - info8 = this._prepareRequest(verb, parsedRedirectUrl, headers); - response = yield this.requestRaw(info8, data); - redirectsRemaining--; - } - if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { - return response; - } - numTries += 1; - if (numTries < maxTries) { - yield response.readBody(); - yield this._performExponentialBackoff(numTries); - } - } while (numTries < maxTries); - return response; - }); - } - /** - * Needs to be called if keepAlive is set to true in request options. - */ - dispose() { - if (this._agent) { - this._agent.destroy(); - } - this._disposed = true; - } - /** - * Raw request. - * @param info - * @param data - */ - requestRaw(info8, data) { - return __awaiter2(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => { - function callbackForResult(err, res) { - if (err) { - reject(err); - } else if (!res) { - reject(new Error("Unknown error")); - } else { - resolve(res); - } - } - this.requestRawWithCallback(info8, data, callbackForResult); - }); - }); + ], + getAllPackageVersionsForPackageOwnedByAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions" + ], + getAllPackageVersionsForPackageOwnedByOrg: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions" + ], + getAllPackageVersionsForPackageOwnedByUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}/versions" + ], + getPackageForAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}" + ], + getPackageForOrganization: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}" + ], + getPackageForUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}" + ], + getPackageVersionForAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getPackageVersionForOrganization: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getPackageVersionForUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + listDockerMigrationConflictingPackagesForAuthenticatedUser: [ + "GET /user/docker/conflicts" + ], + listDockerMigrationConflictingPackagesForOrganization: [ + "GET /orgs/{org}/docker/conflicts" + ], + listDockerMigrationConflictingPackagesForUser: [ + "GET /users/{username}/docker/conflicts" + ], + listPackagesForAuthenticatedUser: ["GET /user/packages"], + listPackagesForOrganization: ["GET /orgs/{org}/packages"], + listPackagesForUser: ["GET /users/{username}/packages"], + restorePackageForAuthenticatedUser: [ + "POST /user/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageForOrg: [ + "POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageForUser: [ + "POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageVersionForAuthenticatedUser: [ + "POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ], + restorePackageVersionForOrg: [ + "POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ], + restorePackageVersionForUser: [ + "POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ] + }, + privateRegistries: { + createOrgPrivateRegistry: ["POST /orgs/{org}/private-registries"], + deleteOrgPrivateRegistry: [ + "DELETE /orgs/{org}/private-registries/{secret_name}" + ], + getOrgPrivateRegistry: ["GET /orgs/{org}/private-registries/{secret_name}"], + getOrgPublicKey: ["GET /orgs/{org}/private-registries/public-key"], + listOrgPrivateRegistries: ["GET /orgs/{org}/private-registries"], + updateOrgPrivateRegistry: [ + "PATCH /orgs/{org}/private-registries/{secret_name}" + ] + }, + projects: { + addItemForOrg: ["POST /orgs/{org}/projectsV2/{project_number}/items"], + addItemForUser: [ + "POST /users/{username}/projectsV2/{project_number}/items" + ], + deleteItemForOrg: [ + "DELETE /orgs/{org}/projectsV2/{project_number}/items/{item_id}" + ], + deleteItemForUser: [ + "DELETE /users/{username}/projectsV2/{project_number}/items/{item_id}" + ], + getFieldForOrg: [ + "GET /orgs/{org}/projectsV2/{project_number}/fields/{field_id}" + ], + getFieldForUser: [ + "GET /users/{username}/projectsV2/{project_number}/fields/{field_id}" + ], + getForOrg: ["GET /orgs/{org}/projectsV2/{project_number}"], + getForUser: ["GET /users/{username}/projectsV2/{project_number}"], + getOrgItem: ["GET /orgs/{org}/projectsV2/{project_number}/items/{item_id}"], + getUserItem: [ + "GET /users/{username}/projectsV2/{project_number}/items/{item_id}" + ], + listFieldsForOrg: ["GET /orgs/{org}/projectsV2/{project_number}/fields"], + listFieldsForUser: [ + "GET /users/{username}/projectsV2/{project_number}/fields" + ], + listForOrg: ["GET /orgs/{org}/projectsV2"], + listForUser: ["GET /users/{username}/projectsV2"], + listItemsForOrg: ["GET /orgs/{org}/projectsV2/{project_number}/items"], + listItemsForUser: [ + "GET /users/{username}/projectsV2/{project_number}/items" + ], + updateItemForOrg: [ + "PATCH /orgs/{org}/projectsV2/{project_number}/items/{item_id}" + ], + updateItemForUser: [ + "PATCH /users/{username}/projectsV2/{project_number}/items/{item_id}" + ] + }, + pulls: { + checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"], + create: ["POST /repos/{owner}/{repo}/pulls"], + createReplyForReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies" + ], + createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], + createReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments" + ], + deletePendingReview: [ + "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], + deleteReviewComment: [ + "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}" + ], + dismissReview: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals" + ], + get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"], + getReview: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], + getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"], + list: ["GET /repos/{owner}/{repo}/pulls"], + listCommentsForReview: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments" + ], + listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"], + listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"], + listRequestedReviewers: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + listReviewComments: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments" + ], + listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"], + listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], + merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"], + removeRequestedReviewers: [ + "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + requestReviewers: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + submitReview: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events" + ], + update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"], + updateBranch: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch" + ], + updateReview: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], + updateReviewComment: [ + "PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}" + ] + }, + rateLimit: { get: ["GET /rate_limit"] }, + reactions: { + createForCommitComment: [ + "POST /repos/{owner}/{repo}/comments/{comment_id}/reactions" + ], + createForIssue: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/reactions" + ], + createForIssueComment: [ + "POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" + ], + createForPullRequestReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" + ], + createForRelease: [ + "POST /repos/{owner}/{repo}/releases/{release_id}/reactions" + ], + createForTeamDiscussionCommentInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" + ], + createForTeamDiscussionInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" + ], + deleteForCommitComment: [ + "DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForIssue: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}" + ], + deleteForIssueComment: [ + "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForPullRequestComment: [ + "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForRelease: [ + "DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}" + ], + deleteForTeamDiscussion: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}" + ], + deleteForTeamDiscussionComment: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}" + ], + listForCommitComment: [ + "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions" + ], + listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"], + listForIssueComment: [ + "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" + ], + listForPullRequestReviewComment: [ + "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" + ], + listForRelease: [ + "GET /repos/{owner}/{repo}/releases/{release_id}/reactions" + ], + listForTeamDiscussionCommentInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" + ], + listForTeamDiscussionInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" + ] + }, + repos: { + acceptInvitation: [ + "PATCH /user/repository_invitations/{invitation_id}", + {}, + { renamed: ["repos", "acceptInvitationForAuthenticatedUser"] } + ], + acceptInvitationForAuthenticatedUser: [ + "PATCH /user/repository_invitations/{invitation_id}" + ], + addAppAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], + addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"], + addStatusCheckContexts: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + addTeamAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + addUserAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], + cancelPagesDeployment: [ + "POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel" + ], + checkAutomatedSecurityFixes: [ + "GET /repos/{owner}/{repo}/automated-security-fixes" + ], + checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"], + checkImmutableReleases: ["GET /repos/{owner}/{repo}/immutable-releases"], + checkPrivateVulnerabilityReporting: [ + "GET /repos/{owner}/{repo}/private-vulnerability-reporting" + ], + checkVulnerabilityAlerts: [ + "GET /repos/{owner}/{repo}/vulnerability-alerts" + ], + codeownersErrors: ["GET /repos/{owner}/{repo}/codeowners/errors"], + compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"], + compareCommitsWithBasehead: [ + "GET /repos/{owner}/{repo}/compare/{basehead}" + ], + createAttestation: ["POST /repos/{owner}/{repo}/attestations"], + createAutolink: ["POST /repos/{owner}/{repo}/autolinks"], + createCommitComment: [ + "POST /repos/{owner}/{repo}/commits/{commit_sha}/comments" + ], + createCommitSignatureProtection: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], + createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"], + createDeployKey: ["POST /repos/{owner}/{repo}/keys"], + createDeployment: ["POST /repos/{owner}/{repo}/deployments"], + createDeploymentBranchPolicy: [ + "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" + ], + createDeploymentProtectionRule: [ + "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" + ], + createDeploymentStatus: [ + "POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" + ], + createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"], + createForAuthenticatedUser: ["POST /user/repos"], + createFork: ["POST /repos/{owner}/{repo}/forks"], + createInOrg: ["POST /orgs/{org}/repos"], + createOrUpdateEnvironment: [ + "PUT /repos/{owner}/{repo}/environments/{environment_name}" + ], + createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"], + createOrgRuleset: ["POST /orgs/{org}/rulesets"], + createPagesDeployment: ["POST /repos/{owner}/{repo}/pages/deployments"], + createPagesSite: ["POST /repos/{owner}/{repo}/pages"], + createRelease: ["POST /repos/{owner}/{repo}/releases"], + createRepoRuleset: ["POST /repos/{owner}/{repo}/rulesets"], + createUsingTemplate: [ + "POST /repos/{template_owner}/{template_repo}/generate" + ], + createWebhook: ["POST /repos/{owner}/{repo}/hooks"], + customPropertiesForReposCreateOrUpdateRepositoryValues: [ + "PATCH /repos/{owner}/{repo}/properties/values" + ], + customPropertiesForReposGetRepositoryValues: [ + "GET /repos/{owner}/{repo}/properties/values" + ], + declineInvitation: [ + "DELETE /user/repository_invitations/{invitation_id}", + {}, + { renamed: ["repos", "declineInvitationForAuthenticatedUser"] } + ], + declineInvitationForAuthenticatedUser: [ + "DELETE /user/repository_invitations/{invitation_id}" + ], + delete: ["DELETE /repos/{owner}/{repo}"], + deleteAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" + ], + deleteAdminBranchProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + deleteAnEnvironment: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}" + ], + deleteAutolink: ["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"], + deleteBranchProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection" + ], + deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"], + deleteCommitSignatureProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], + deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"], + deleteDeployment: [ + "DELETE /repos/{owner}/{repo}/deployments/{deployment_id}" + ], + deleteDeploymentBranchPolicy: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], + deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"], + deleteInvitation: [ + "DELETE /repos/{owner}/{repo}/invitations/{invitation_id}" + ], + deleteOrgRuleset: ["DELETE /orgs/{org}/rulesets/{ruleset_id}"], + deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages"], + deletePullRequestReviewProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], + deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"], + deleteReleaseAsset: [ + "DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}" + ], + deleteRepoRuleset: ["DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"], + disableAutomatedSecurityFixes: [ + "DELETE /repos/{owner}/{repo}/automated-security-fixes" + ], + disableDeploymentProtectionRule: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" + ], + disableImmutableReleases: [ + "DELETE /repos/{owner}/{repo}/immutable-releases" + ], + disablePrivateVulnerabilityReporting: [ + "DELETE /repos/{owner}/{repo}/private-vulnerability-reporting" + ], + disableVulnerabilityAlerts: [ + "DELETE /repos/{owner}/{repo}/vulnerability-alerts" + ], + downloadArchive: [ + "GET /repos/{owner}/{repo}/zipball/{ref}", + {}, + { renamed: ["repos", "downloadZipballArchive"] } + ], + downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"], + downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"], + enableAutomatedSecurityFixes: [ + "PUT /repos/{owner}/{repo}/automated-security-fixes" + ], + enableImmutableReleases: ["PUT /repos/{owner}/{repo}/immutable-releases"], + enablePrivateVulnerabilityReporting: [ + "PUT /repos/{owner}/{repo}/private-vulnerability-reporting" + ], + enableVulnerabilityAlerts: [ + "PUT /repos/{owner}/{repo}/vulnerability-alerts" + ], + generateReleaseNotes: [ + "POST /repos/{owner}/{repo}/releases/generate-notes" + ], + get: ["GET /repos/{owner}/{repo}"], + getAccessRestrictions: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" + ], + getAdminBranchProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + getAllDeploymentProtectionRules: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" + ], + getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"], + getAllStatusCheckContexts: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts" + ], + getAllTopics: ["GET /repos/{owner}/{repo}/topics"], + getAppsWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps" + ], + getAutolink: ["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"], + getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"], + getBranchProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection" + ], + getBranchRules: ["GET /repos/{owner}/{repo}/rules/branches/{branch}"], + getClones: ["GET /repos/{owner}/{repo}/traffic/clones"], + getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"], + getCollaboratorPermissionLevel: [ + "GET /repos/{owner}/{repo}/collaborators/{username}/permission" + ], + getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"], + getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"], + getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"], + getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"], + getCommitSignatureProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], + getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"], + getContent: ["GET /repos/{owner}/{repo}/contents/{path}"], + getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"], + getCustomDeploymentProtectionRule: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" + ], + getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"], + getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"], + getDeploymentBranchPolicy: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], + getDeploymentStatus: [ + "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}" + ], + getEnvironment: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}" + ], + getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], + getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], + getOrgRuleSuite: ["GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}"], + getOrgRuleSuites: ["GET /orgs/{org}/rulesets/rule-suites"], + getOrgRuleset: ["GET /orgs/{org}/rulesets/{ruleset_id}"], + getOrgRulesets: ["GET /orgs/{org}/rulesets"], + getPages: ["GET /repos/{owner}/{repo}/pages"], + getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"], + getPagesDeployment: [ + "GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}" + ], + getPagesHealthCheck: ["GET /repos/{owner}/{repo}/pages/health"], + getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"], + getPullRequestReviewProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], + getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"], + getReadme: ["GET /repos/{owner}/{repo}/readme"], + getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"], + getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"], + getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"], + getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"], + getRepoRuleSuite: [ + "GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}" + ], + getRepoRuleSuites: ["GET /repos/{owner}/{repo}/rulesets/rule-suites"], + getRepoRuleset: ["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + getRepoRulesetHistory: [ + "GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history" + ], + getRepoRulesetVersion: [ + "GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history/{version_id}" + ], + getRepoRulesets: ["GET /repos/{owner}/{repo}/rulesets"], + getStatusChecksProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], + getTeamsWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams" + ], + getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"], + getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"], + getUsersWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users" + ], + getViews: ["GET /repos/{owner}/{repo}/traffic/views"], + getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"], + getWebhookConfigForRepo: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/config" + ], + getWebhookDelivery: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}" + ], + listActivities: ["GET /repos/{owner}/{repo}/activity"], + listAttestations: [ + "GET /repos/{owner}/{repo}/attestations/{subject_digest}" + ], + listAutolinks: ["GET /repos/{owner}/{repo}/autolinks"], + listBranches: ["GET /repos/{owner}/{repo}/branches"], + listBranchesForHeadCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head" + ], + listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"], + listCommentsForCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments" + ], + listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"], + listCommitStatusesForRef: [ + "GET /repos/{owner}/{repo}/commits/{ref}/statuses" + ], + listCommits: ["GET /repos/{owner}/{repo}/commits"], + listContributors: ["GET /repos/{owner}/{repo}/contributors"], + listCustomDeploymentRuleIntegrations: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps" + ], + listDeployKeys: ["GET /repos/{owner}/{repo}/keys"], + listDeploymentBranchPolicies: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" + ], + listDeploymentStatuses: [ + "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" + ], + listDeployments: ["GET /repos/{owner}/{repo}/deployments"], + listForAuthenticatedUser: ["GET /user/repos"], + listForOrg: ["GET /orgs/{org}/repos"], + listForUser: ["GET /users/{username}/repos"], + listForks: ["GET /repos/{owner}/{repo}/forks"], + listInvitations: ["GET /repos/{owner}/{repo}/invitations"], + listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"], + listLanguages: ["GET /repos/{owner}/{repo}/languages"], + listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"], + listPublic: ["GET /repositories"], + listPullRequestsAssociatedWithCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls" + ], + listReleaseAssets: [ + "GET /repos/{owner}/{repo}/releases/{release_id}/assets" + ], + listReleases: ["GET /repos/{owner}/{repo}/releases"], + listTags: ["GET /repos/{owner}/{repo}/tags"], + listTeams: ["GET /repos/{owner}/{repo}/teams"], + listWebhookDeliveries: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries" + ], + listWebhooks: ["GET /repos/{owner}/{repo}/hooks"], + merge: ["POST /repos/{owner}/{repo}/merges"], + mergeUpstream: ["POST /repos/{owner}/{repo}/merge-upstream"], + pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"], + redeliverWebhookDelivery: [ + "POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" + ], + removeAppAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], + removeCollaborator: [ + "DELETE /repos/{owner}/{repo}/collaborators/{username}" + ], + removeStatusCheckContexts: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + removeStatusCheckProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], + removeTeamAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + removeUserAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], + renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"], + replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics"], + requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"], + setAdminBranchProtection: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + setAppAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], + setStatusCheckContexts: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + setTeamAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + setUserAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], + testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"], + transfer: ["POST /repos/{owner}/{repo}/transfer"], + update: ["PATCH /repos/{owner}/{repo}"], + updateBranchProtection: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection" + ], + updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"], + updateDeploymentBranchPolicy: [ + "PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], + updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"], + updateInvitation: [ + "PATCH /repos/{owner}/{repo}/invitations/{invitation_id}" + ], + updateOrgRuleset: ["PUT /orgs/{org}/rulesets/{ruleset_id}"], + updatePullRequestReviewProtection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], + updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"], + updateReleaseAsset: [ + "PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}" + ], + updateRepoRuleset: ["PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + updateStatusCheckPotection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", + {}, + { renamed: ["repos", "updateStatusCheckProtection"] } + ], + updateStatusCheckProtection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], + updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"], + updateWebhookConfigForRepo: [ + "PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config" + ], + uploadReleaseAsset: [ + "POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", + { baseUrl: "https://uploads.github.com" } + ] + }, + search: { + code: ["GET /search/code"], + commits: ["GET /search/commits"], + issuesAndPullRequests: ["GET /search/issues"], + labels: ["GET /search/labels"], + repos: ["GET /search/repositories"], + topics: ["GET /search/topics"], + users: ["GET /search/users"] + }, + secretScanning: { + createPushProtectionBypass: [ + "POST /repos/{owner}/{repo}/secret-scanning/push-protection-bypasses" + ], + getAlert: [ + "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" + ], + getScanHistory: ["GET /repos/{owner}/{repo}/secret-scanning/scan-history"], + listAlertsForOrg: ["GET /orgs/{org}/secret-scanning/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"], + listLocationsForAlert: [ + "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations" + ], + listOrgPatternConfigs: [ + "GET /orgs/{org}/secret-scanning/pattern-configurations" + ], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" + ], + updateOrgPatternConfigs: [ + "PATCH /orgs/{org}/secret-scanning/pattern-configurations" + ] + }, + securityAdvisories: { + createFork: [ + "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks" + ], + createPrivateVulnerabilityReport: [ + "POST /repos/{owner}/{repo}/security-advisories/reports" + ], + createRepositoryAdvisory: [ + "POST /repos/{owner}/{repo}/security-advisories" + ], + createRepositoryAdvisoryCveRequest: [ + "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve" + ], + getGlobalAdvisory: ["GET /advisories/{ghsa_id}"], + getRepositoryAdvisory: [ + "GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}" + ], + listGlobalAdvisories: ["GET /advisories"], + listOrgRepositoryAdvisories: ["GET /orgs/{org}/security-advisories"], + listRepositoryAdvisories: ["GET /repos/{owner}/{repo}/security-advisories"], + updateRepositoryAdvisory: [ + "PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}" + ] + }, + teams: { + addOrUpdateMembershipForUserInOrg: [ + "PUT /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], + addOrUpdateRepoPermissionsInOrg: [ + "PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], + checkPermissionsForRepoInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], + create: ["POST /orgs/{org}/teams"], + createDiscussionCommentInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" + ], + createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"], + deleteDiscussionCommentInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + deleteDiscussionInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], + deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"], + getByName: ["GET /orgs/{org}/teams/{team_slug}"], + getDiscussionCommentInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + getDiscussionInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], + getMembershipForUserInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], + list: ["GET /orgs/{org}/teams"], + listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"], + listDiscussionCommentsInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" + ], + listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"], + listForAuthenticatedUser: ["GET /user/teams"], + listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"], + listPendingInvitationsInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/invitations" + ], + listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"], + removeMembershipForUserInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], + removeRepoInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], + updateDiscussionCommentInOrg: [ + "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + updateDiscussionInOrg: [ + "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], + updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"] + }, + users: { + addEmailForAuthenticated: [ + "POST /user/emails", + {}, + { renamed: ["users", "addEmailForAuthenticatedUser"] } + ], + addEmailForAuthenticatedUser: ["POST /user/emails"], + addSocialAccountForAuthenticatedUser: ["POST /user/social_accounts"], + block: ["PUT /user/blocks/{username}"], + checkBlocked: ["GET /user/blocks/{username}"], + checkFollowingForUser: ["GET /users/{username}/following/{target_user}"], + checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"], + createGpgKeyForAuthenticated: [ + "POST /user/gpg_keys", + {}, + { renamed: ["users", "createGpgKeyForAuthenticatedUser"] } + ], + createGpgKeyForAuthenticatedUser: ["POST /user/gpg_keys"], + createPublicSshKeyForAuthenticated: [ + "POST /user/keys", + {}, + { renamed: ["users", "createPublicSshKeyForAuthenticatedUser"] } + ], + createPublicSshKeyForAuthenticatedUser: ["POST /user/keys"], + createSshSigningKeyForAuthenticatedUser: ["POST /user/ssh_signing_keys"], + deleteAttestationsBulk: [ + "POST /users/{username}/attestations/delete-request" + ], + deleteAttestationsById: [ + "DELETE /users/{username}/attestations/{attestation_id}" + ], + deleteAttestationsBySubjectDigest: [ + "DELETE /users/{username}/attestations/digest/{subject_digest}" + ], + deleteEmailForAuthenticated: [ + "DELETE /user/emails", + {}, + { renamed: ["users", "deleteEmailForAuthenticatedUser"] } + ], + deleteEmailForAuthenticatedUser: ["DELETE /user/emails"], + deleteGpgKeyForAuthenticated: [ + "DELETE /user/gpg_keys/{gpg_key_id}", + {}, + { renamed: ["users", "deleteGpgKeyForAuthenticatedUser"] } + ], + deleteGpgKeyForAuthenticatedUser: ["DELETE /user/gpg_keys/{gpg_key_id}"], + deletePublicSshKeyForAuthenticated: [ + "DELETE /user/keys/{key_id}", + {}, + { renamed: ["users", "deletePublicSshKeyForAuthenticatedUser"] } + ], + deletePublicSshKeyForAuthenticatedUser: ["DELETE /user/keys/{key_id}"], + deleteSocialAccountForAuthenticatedUser: ["DELETE /user/social_accounts"], + deleteSshSigningKeyForAuthenticatedUser: [ + "DELETE /user/ssh_signing_keys/{ssh_signing_key_id}" + ], + follow: ["PUT /user/following/{username}"], + getAuthenticated: ["GET /user"], + getById: ["GET /user/{account_id}"], + getByUsername: ["GET /users/{username}"], + getContextForUser: ["GET /users/{username}/hovercard"], + getGpgKeyForAuthenticated: [ + "GET /user/gpg_keys/{gpg_key_id}", + {}, + { renamed: ["users", "getGpgKeyForAuthenticatedUser"] } + ], + getGpgKeyForAuthenticatedUser: ["GET /user/gpg_keys/{gpg_key_id}"], + getPublicSshKeyForAuthenticated: [ + "GET /user/keys/{key_id}", + {}, + { renamed: ["users", "getPublicSshKeyForAuthenticatedUser"] } + ], + getPublicSshKeyForAuthenticatedUser: ["GET /user/keys/{key_id}"], + getSshSigningKeyForAuthenticatedUser: [ + "GET /user/ssh_signing_keys/{ssh_signing_key_id}" + ], + list: ["GET /users"], + listAttestations: ["GET /users/{username}/attestations/{subject_digest}"], + listAttestationsBulk: [ + "POST /users/{username}/attestations/bulk-list{?per_page,before,after}" + ], + listBlockedByAuthenticated: [ + "GET /user/blocks", + {}, + { renamed: ["users", "listBlockedByAuthenticatedUser"] } + ], + listBlockedByAuthenticatedUser: ["GET /user/blocks"], + listEmailsForAuthenticated: [ + "GET /user/emails", + {}, + { renamed: ["users", "listEmailsForAuthenticatedUser"] } + ], + listEmailsForAuthenticatedUser: ["GET /user/emails"], + listFollowedByAuthenticated: [ + "GET /user/following", + {}, + { renamed: ["users", "listFollowedByAuthenticatedUser"] } + ], + listFollowedByAuthenticatedUser: ["GET /user/following"], + listFollowersForAuthenticatedUser: ["GET /user/followers"], + listFollowersForUser: ["GET /users/{username}/followers"], + listFollowingForUser: ["GET /users/{username}/following"], + listGpgKeysForAuthenticated: [ + "GET /user/gpg_keys", + {}, + { renamed: ["users", "listGpgKeysForAuthenticatedUser"] } + ], + listGpgKeysForAuthenticatedUser: ["GET /user/gpg_keys"], + listGpgKeysForUser: ["GET /users/{username}/gpg_keys"], + listPublicEmailsForAuthenticated: [ + "GET /user/public_emails", + {}, + { renamed: ["users", "listPublicEmailsForAuthenticatedUser"] } + ], + listPublicEmailsForAuthenticatedUser: ["GET /user/public_emails"], + listPublicKeysForUser: ["GET /users/{username}/keys"], + listPublicSshKeysForAuthenticated: [ + "GET /user/keys", + {}, + { renamed: ["users", "listPublicSshKeysForAuthenticatedUser"] } + ], + listPublicSshKeysForAuthenticatedUser: ["GET /user/keys"], + listSocialAccountsForAuthenticatedUser: ["GET /user/social_accounts"], + listSocialAccountsForUser: ["GET /users/{username}/social_accounts"], + listSshSigningKeysForAuthenticatedUser: ["GET /user/ssh_signing_keys"], + listSshSigningKeysForUser: ["GET /users/{username}/ssh_signing_keys"], + setPrimaryEmailVisibilityForAuthenticated: [ + "PATCH /user/email/visibility", + {}, + { renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"] } + ], + setPrimaryEmailVisibilityForAuthenticatedUser: [ + "PATCH /user/email/visibility" + ], + unblock: ["DELETE /user/blocks/{username}"], + unfollow: ["DELETE /user/following/{username}"], + updateAuthenticated: ["PATCH /user"] } - /** - * Raw request with callback. - * @param info - * @param data - * @param onResult - */ - requestRawWithCallback(info8, data, onResult) { - if (typeof data === "string") { - if (!info8.options.headers) { - info8.options.headers = {}; - } - info8.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); - } - let callbackCalled = false; - function handleResult(err, res) { - if (!callbackCalled) { - callbackCalled = true; - onResult(err, res); - } +}; +var endpoints_default = Endpoints; + +// node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/endpoints-to-methods.js +var endpointMethodsMap = /* @__PURE__ */ new Map(); +for (const [scope, endpoints] of Object.entries(endpoints_default)) { + for (const [methodName, endpoint2] of Object.entries(endpoints)) { + const [route, defaults2, decorations] = endpoint2; + const [method, url] = route.split(/ /); + const endpointDefaults = Object.assign( + { + method, + url + }, + defaults2 + ); + if (!endpointMethodsMap.has(scope)) { + endpointMethodsMap.set(scope, /* @__PURE__ */ new Map()); } - const req = info8.httpModule.request(info8.options, (msg) => { - const res = new HttpClientResponse(msg); - handleResult(void 0, res); - }); - let socket; - req.on("socket", (sock) => { - socket = sock; - }); - req.setTimeout(this._socketTimeout || 3 * 6e4, () => { - if (socket) { - socket.end(); - } - handleResult(new Error(`Request timeout: ${info8.options.path}`)); - }); - req.on("error", function(err) { - handleResult(err); + endpointMethodsMap.get(scope).set(methodName, { + scope, + methodName, + endpointDefaults, + decorations }); - if (data && typeof data === "string") { - req.write(data, "utf8"); - } - if (data && typeof data !== "string") { - data.on("close", function() { - req.end(); - }); - data.pipe(req); - } else { - req.end(); - } - } - /** - * Gets an http agent. This function is useful when you need an http agent that handles - * routing through a proxy server - depending upon the url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com - */ - getAgent(serverUrl) { - const parsedUrl = new URL(serverUrl); - return this._getAgent(parsedUrl); } - getAgentDispatcher(serverUrl) { - const parsedUrl = new URL(serverUrl); - const proxyUrl = getProxyUrl(parsedUrl); - const useProxy = proxyUrl && proxyUrl.hostname; - if (!useProxy) { - return; +} +var handler = { + has({ scope }, methodName) { + return endpointMethodsMap.get(scope).has(methodName); + }, + getOwnPropertyDescriptor(target, methodName) { + return { + value: this.get(target, methodName), + // ensures method is in the cache + configurable: true, + writable: true, + enumerable: true + }; + }, + defineProperty(target, methodName, descriptor) { + Object.defineProperty(target.cache, methodName, descriptor); + return true; + }, + deleteProperty(target, methodName) { + delete target.cache[methodName]; + return true; + }, + ownKeys({ scope }) { + return [...endpointMethodsMap.get(scope).keys()]; + }, + set(target, methodName, value) { + return target.cache[methodName] = value; + }, + get({ octokit, scope, cache }, methodName) { + if (cache[methodName]) { + return cache[methodName]; } - return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); - } - _prepareRequest(method, requestUrl, headers) { - const info8 = {}; - info8.parsedUrl = requestUrl; - const usingSsl = info8.parsedUrl.protocol === "https:"; - info8.httpModule = usingSsl ? https : http; - const defaultPort = usingSsl ? 443 : 80; - info8.options = {}; - info8.options.host = info8.parsedUrl.hostname; - info8.options.port = info8.parsedUrl.port ? parseInt(info8.parsedUrl.port) : defaultPort; - info8.options.path = (info8.parsedUrl.pathname || "") + (info8.parsedUrl.search || ""); - info8.options.method = method; - info8.options.headers = this._mergeHeaders(headers); - if (this.userAgent != null) { - info8.options.headers["user-agent"] = this.userAgent; + const method = endpointMethodsMap.get(scope).get(methodName); + if (!method) { + return void 0; } - info8.options.agent = this._getAgent(info8.parsedUrl); - if (this.handlers) { - for (const handler2 of this.handlers) { - handler2.prepareRequest(info8.options); - } + const { endpointDefaults, decorations } = method; + if (decorations) { + cache[methodName] = decorate( + octokit, + scope, + methodName, + endpointDefaults, + decorations + ); + } else { + cache[methodName] = octokit.request.defaults(endpointDefaults); } - return info8; + return cache[methodName]; } - _mergeHeaders(headers) { - if (this.requestOptions && this.requestOptions.headers) { - return Object.assign({}, lowercaseKeys2(this.requestOptions.headers), lowercaseKeys2(headers || {})); - } - return lowercaseKeys2(headers || {}); +}; +function endpointsToMethods(octokit) { + const newMethods = {}; + for (const scope of endpointMethodsMap.keys()) { + newMethods[scope] = new Proxy({ octokit, scope, cache: {} }, handler); } - /** - * Gets an existing header value or returns a default. - * Handles converting number header values to strings since HTTP headers must be strings. - * Note: This returns string | string[] since some headers can have multiple values. - * For headers that must always be a single string (like Content-Type), use the - * specialized _getExistingOrDefaultContentTypeHeader method instead. - */ - _getExistingOrDefaultHeader(additionalHeaders, header, _default) { - let clientHeader; - if (this.requestOptions && this.requestOptions.headers) { - const headerValue = lowercaseKeys2(this.requestOptions.headers)[header]; - if (headerValue) { - clientHeader = typeof headerValue === "number" ? headerValue.toString() : headerValue; - } + return newMethods; +} +function decorate(octokit, scope, methodName, defaults2, decorations) { + const requestWithDefaults = octokit.request.defaults(defaults2); + function withDecorations(...args) { + let options = requestWithDefaults.endpoint.merge(...args); + if (decorations.mapToData) { + options = Object.assign({}, options, { + data: options[decorations.mapToData], + [decorations.mapToData]: void 0 + }); + return requestWithDefaults(options); } - const additionalValue = additionalHeaders[header]; - if (additionalValue !== void 0) { - return typeof additionalValue === "number" ? additionalValue.toString() : additionalValue; + if (decorations.renamed) { + const [newScope, newMethodName] = decorations.renamed; + octokit.log.warn( + `octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()` + ); } - if (clientHeader !== void 0) { - return clientHeader; + if (decorations.deprecated) { + octokit.log.warn(decorations.deprecated); } - return _default; - } - /** - * Specialized version of _getExistingOrDefaultHeader for Content-Type header. - * Always returns a single string (not an array) since Content-Type should be a single value. - * Converts arrays to comma-separated strings and numbers to strings to ensure type safety. - * This was split from _getExistingOrDefaultHeader to provide stricter typing for callers - * that assign the result to places expecting a string (e.g., additionalHeaders[Headers.ContentType]). - */ - _getExistingOrDefaultContentTypeHeader(additionalHeaders, _default) { - let clientHeader; - if (this.requestOptions && this.requestOptions.headers) { - const headerValue = lowercaseKeys2(this.requestOptions.headers)[Headers.ContentType]; - if (headerValue) { - if (typeof headerValue === "number") { - clientHeader = String(headerValue); - } else if (Array.isArray(headerValue)) { - clientHeader = headerValue.join(", "); - } else { - clientHeader = headerValue; + if (decorations.renamedParameters) { + const options2 = requestWithDefaults.endpoint.merge(...args); + for (const [name, alias] of Object.entries( + decorations.renamedParameters + )) { + if (name in options2) { + octokit.log.warn( + `"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead` + ); + if (!(alias in options2)) { + options2[alias] = options2[name]; + } + delete options2[name]; } } + return requestWithDefaults(options2); } - const additionalValue = additionalHeaders[Headers.ContentType]; - if (additionalValue !== void 0) { - if (typeof additionalValue === "number") { - return String(additionalValue); - } else if (Array.isArray(additionalValue)) { - return additionalValue.join(", "); - } else { - return additionalValue; - } - } - if (clientHeader !== void 0) { - return clientHeader; - } - return _default; - } - _getAgent(parsedUrl) { - let agent; - const proxyUrl = getProxyUrl(parsedUrl); - const useProxy = proxyUrl && proxyUrl.hostname; - if (this._keepAlive && useProxy) { - agent = this._proxyAgent; - } - if (!useProxy) { - agent = this._agent; - } - if (agent) { - return agent; - } - const usingSsl = parsedUrl.protocol === "https:"; - let maxSockets = 100; - if (this.requestOptions) { - maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; - } - if (proxyUrl && proxyUrl.hostname) { - const agentOptions = { - maxSockets, - keepAlive: this._keepAlive, - proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { - proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` - }), { host: proxyUrl.hostname, port: proxyUrl.port }) - }; - let tunnelAgent; - const overHttps = proxyUrl.protocol === "https:"; - if (usingSsl) { - tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; - } else { - tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; - } - agent = tunnelAgent(agentOptions); - this._proxyAgent = agent; - } - if (!agent) { - const options = { keepAlive: this._keepAlive, maxSockets }; - agent = usingSsl ? new https.Agent(options) : new http.Agent(options); - this._agent = agent; - } - if (usingSsl && this._ignoreSslError) { - agent.options = Object.assign(agent.options || {}, { - rejectUnauthorized: false - }); - } - return agent; + return requestWithDefaults(...args); } - _getProxyAgentDispatcher(parsedUrl, proxyUrl) { - let proxyAgent; - if (this._keepAlive) { - proxyAgent = this._proxyAgentDispatcher; - } - if (proxyAgent) { - return proxyAgent; - } - const usingSsl = parsedUrl.protocol === "https:"; - proxyAgent = new import_undici2.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { - token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` - })); - this._proxyAgentDispatcher = proxyAgent; - if (usingSsl && this._ignoreSslError) { - proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { - rejectUnauthorized: false - }); - } - return proxyAgent; + return Object.assign(withDecorations, requestWithDefaults); +} + +// node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/index.js +function restEndpointMethods(octokit) { + const api = endpointsToMethods(octokit); + return { + rest: api + }; +} +restEndpointMethods.VERSION = VERSION5; +function legacyRestEndpointMethods(octokit) { + const api = endpointsToMethods(octokit); + return { + ...api, + rest: api + }; +} +legacyRestEndpointMethods.VERSION = VERSION5; + +// node_modules/@octokit/plugin-paginate-rest/dist-bundle/index.js +var VERSION6 = "0.0.0-development"; +function normalizePaginatedListResponse(response) { + if (!response.data) { + return { + ...response, + data: [] + }; } - _getUserAgentWithOrchestrationId(userAgent2) { - const baseUserAgent = userAgent2 || "actions/http-client"; - const orchId = process.env["ACTIONS_ORCHESTRATION_ID"]; - if (orchId) { - const sanitizedId = orchId.replace(/[^a-z0-9_.-]/gi, "_"); - return `${baseUserAgent} actions_orchestration_id/${sanitizedId}`; - } - return baseUserAgent; + const responseNeedsNormalization = ("total_count" in response.data || "total_commits" in response.data) && !("url" in response.data); + if (!responseNeedsNormalization) return response; + const incompleteResults = response.data.incomplete_results; + const repositorySelection = response.data.repository_selection; + const totalCount = response.data.total_count; + const totalCommits = response.data.total_commits; + delete response.data.incomplete_results; + delete response.data.repository_selection; + delete response.data.total_count; + delete response.data.total_commits; + const namespaceKey = Object.keys(response.data)[0]; + const data = response.data[namespaceKey]; + response.data = data; + if (typeof incompleteResults !== "undefined") { + response.data.incomplete_results = incompleteResults; } - _performExponentialBackoff(retryNumber) { - return __awaiter2(this, void 0, void 0, function* () { - retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); - const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); - return new Promise((resolve) => setTimeout(() => resolve(), ms)); - }); + if (typeof repositorySelection !== "undefined") { + response.data.repository_selection = repositorySelection; } - _processResponse(res, options) { - return __awaiter2(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => __awaiter2(this, void 0, void 0, function* () { - const statusCode = res.message.statusCode || 0; - const response = { - statusCode, - result: null, - headers: {} - }; - if (statusCode === HttpCodes.NotFound) { - resolve(response); - } - function dateTimeDeserializer(key, value) { - if (typeof value === "string") { - const a = new Date(value); - if (!isNaN(a.valueOf())) { - return a; - } - } - return value; - } - let obj; - let contents; + response.data.total_count = totalCount; + response.data.total_commits = totalCommits; + return response; +} +function iterator(octokit, route, parameters) { + const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters); + const requestMethod = typeof route === "function" ? route : octokit.request; + const method = options.method; + const headers = options.headers; + let url = options.url; + return { + [Symbol.asyncIterator]: () => ({ + async next() { + if (!url) return { done: true }; try { - contents = yield res.readBody(); - if (contents && contents.length > 0) { - if (options && options.deserializeDates) { - obj = JSON.parse(contents, dateTimeDeserializer); - } else { - obj = JSON.parse(contents); + const response = await requestMethod({ method, url, headers }); + const normalizedResponse = normalizePaginatedListResponse(response); + url = ((normalizedResponse.headers.link || "").match( + /<([^<>]+)>;\s*rel="next"/ + ) || [])[1]; + if (!url && "total_commits" in normalizedResponse.data) { + const parsedUrl = new URL(normalizedResponse.url); + const params = parsedUrl.searchParams; + const page = parseInt(params.get("page") || "1", 10); + const per_page = parseInt(params.get("per_page") || "250", 10); + if (page * per_page < normalizedResponse.data.total_commits) { + params.set("page", String(page + 1)); + url = parsedUrl.toString(); } - response.result = obj; - } - response.headers = res.message.headers; - } catch (err) { - } - if (statusCode > 299) { - let msg; - if (obj && obj.message) { - msg = obj.message; - } else if (contents && contents.length > 0) { - msg = contents; - } else { - msg = `Failed request: (${statusCode})`; } - const err = new HttpClientError(msg, statusCode); - err.result = response.result; - reject(err); - } else { - resolve(response); + return { value: normalizedResponse }; + } catch (error2) { + if (error2.status !== 409) throw error2; + url = ""; + return { + value: { + status: 200, + headers: {}, + data: [] + } + }; } - })); - }); + } + }) + }; +} +function paginate(octokit, route, parameters, mapFn) { + if (typeof parameters === "function") { + mapFn = parameters; + parameters = void 0; + } + return gather( + octokit, + [], + iterator(octokit, route, parameters)[Symbol.asyncIterator](), + mapFn + ); +} +function gather(octokit, results, iterator2, mapFn) { + return iterator2.next().then((result) => { + if (result.done) { + return results; + } + let earlyExit = false; + function done() { + earlyExit = true; + } + results = results.concat( + mapFn ? mapFn(result.value, done) : result.value.data + ); + if (earlyExit) { + return results; + } + return gather(octokit, results, iterator2, mapFn); + }); +} +var composePaginateRest = Object.assign(paginate, { + iterator +}); +function paginateRest(octokit) { + return { + paginate: Object.assign(paginate.bind(null, octokit), { + iterator: iterator.bind(null, octokit) + }) + }; +} +paginateRest.VERSION = VERSION6; + +// node_modules/@actions/github/lib/utils.js +var context = new Context(); +var baseUrl = getApiBaseUrl(); +var defaults = { + baseUrl, + request: { + agent: getProxyAgent(baseUrl), + fetch: getProxyFetch(baseUrl) } }; -var lowercaseKeys2 = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); +var GitHub = Octokit.plugin(restEndpointMethods, paginateRest).defaults(defaults); + +// node_modules/@actions/github/lib/github.js +var context2 = new Context(); // src/api-client.ts -var core = __toESM(require_core()); var JobDetailsFetchingError = class extends Error { }; var CredentialFetchingError = class extends Error { @@ -102151,19 +99588,19 @@ var ApiClient = class { ); } return res.result.data.attributes; - } catch (error3) { - if (error3 instanceof JobDetailsFetchingError) { - throw error3; - } else if (error3 instanceof HttpClientError) { + } catch (error2) { + if (error2 instanceof JobDetailsFetchingError) { + throw error2; + } else if (error2 instanceof HttpClientError) { throw new JobDetailsFetchingError( - `fetching job details: unexpected status code: ${error3.statusCode}: ${error3.message}` + `fetching job details: unexpected status code: ${error2.statusCode}: ${error2.message}` ); - } else if (error3 instanceof Error) { + } else if (error2 instanceof Error) { throw new JobDetailsFetchingError( - `fetching job details: ${error3.name}: ${error3.message}` + `fetching job details: ${error2.name}: ${error2.message}` ); } - throw error3; + throw error2; } } async getCredentials() { @@ -102185,36 +99622,36 @@ var ApiClient = class { } for (const credential of res.result.data.attributes.credentials) { if (credential.password) { - core.setSecret(credential.password); + setSecret(credential.password); } if (credential.token) { - core.setSecret(credential.token); + setSecret(credential.token); } if (credential["auth-key"]) { - core.setSecret(credential["auth-key"]); + setSecret(credential["auth-key"]); } } return res.result.data.attributes.credentials; - } catch (error3) { - if (error3 instanceof CredentialFetchingError) { - throw error3; - } else if (error3 instanceof HttpClientError) { + } catch (error2) { + if (error2 instanceof CredentialFetchingError) { + throw error2; + } else if (error2 instanceof HttpClientError) { throw new CredentialFetchingError( - `fetching credentials: unexpected status code: ${error3.statusCode}: ${error3.message}` + `fetching credentials: unexpected status code: ${error2.statusCode}: ${error2.message}` ); - } else if (error3 instanceof Error) { + } else if (error2 instanceof Error) { throw new CredentialFetchingError( - `fetching credentials: ${error3.name}: ${error3.message}` + `fetching credentials: ${error2.name}: ${error2.message}` ); } - throw error3; + throw error2; } } - async reportJobError(error3) { + async reportJobError(error2) { const recordErrorURL = `${this.params.dependabotApiUrl}/update_jobs/${this.params.jobId}/record_update_job_error`; const res = await this.client.postJson( recordErrorURL, - { data: error3 }, + { data: error2 }, { ["Authorization"]: this.jobToken } @@ -102248,11 +99685,11 @@ var ApiClient = class { } ] }); - core.info( + info( `Successfully sent metric (dependabot.action.${name}) to remote API endpoint` ); - } catch (error3) { - core.warning(`Metrics reporting failed: ${error3.message}`); + } catch (error2) { + warning(`Metrics reporting failed: ${error2.message}`); } } async reportMetrics(metricsData) { @@ -102271,14 +99708,14 @@ var ApiClient = class { return await this.client.getJson(url, { ["Authorization"]: token }); - } catch (error3) { - if (error3 instanceof HttpClientError) { - if (error3.statusCode >= 500 && error3.statusCode <= 599) { + } catch (error2) { + if (error2 instanceof HttpClientError) { + if (error2.statusCode >= 500 && error2.statusCode <= 599) { if (attempt >= 3) { - throw error3; + throw error2; } - core.warning( - `Retrying failed request with status code: ${error3.statusCode}` + warning( + `Retrying failed request with status code: ${error2.statusCode}` ); const delayMs = 1e3 * 2 ** attempt; await new Promise((resolve) => setTimeout(resolve, delayMs)); @@ -102286,7 +99723,7 @@ var ApiClient = class { return execute(); } } - throw error3; + throw error2; } }; return execute(); @@ -102338,7 +99775,6 @@ function updaterImageName(packageManager) { } // src/image-service.ts -var core2 = __toESM(require_core()); var import_dockerode = __toESM(require_docker()); var import_stream2 = require("stream"); @@ -102400,7 +99836,7 @@ var ImageService = { try { const image = await docker.getImage(imageName).inspect(); if (!force) { - core2.info(`Resolved ${imageName} to existing ${image.RepoDigests}`); + info(`Resolved ${imageName} to existing ${image.RepoDigests}`); return; } } catch (e) { @@ -102416,7 +99852,7 @@ var ImageService = { let attempt = 0; while (attempt < MAX_RETRIES) { try { - core2.info(`Pulling image ${imageName} (attempt ${attempt + 1})...`); + info(`Pulling image ${imageName} (attempt ${attempt + 1})...`); if (sendMetric) { await sendMetric("ghcr_image_pull", "increment", 1, { org @@ -102424,28 +99860,28 @@ var ImageService = { } const stream2 = await docker.pull(imageName, { authconfig: auth2 }); await endOfStream(docker, new import_stream2.Readable().wrap(stream2)); - core2.info(`Pulled image ${imageName}`); + info(`Pulled image ${imageName}`); return; - } catch (error3) { - if (!(error3 instanceof Error)) throw error3; - if (error3.message.includes("429 Too Many Requests") || error3.message.toLowerCase().includes("too many requests")) { + } catch (error2) { + if (!(error2 instanceof Error)) throw error2; + if (error2.message.includes("429 Too Many Requests") || error2.message.toLowerCase().includes("too many requests")) { attempt++; if (attempt >= MAX_RETRIES) { - core2.error( + error( `Failed to pull image ${imageName} after ${MAX_RETRIES} attempts.` ); - throw error3; + throw error2; } const baseDelay = INITIAL_DELAY_MS * Math.pow(2, attempt); const jitter = Math.random() * baseDelay; const delay = baseDelay / 2 + jitter; - core2.warning( + warning( `Received Too Many Requests error. Retrying in ${(delay / 1e3).toFixed(2)} seconds...` ); await sleep(delay); } else { - core2.error(`Fatal error pulling image ${imageName}: ${error3.message}`); - throw error3; + error(`Fatal error pulling image ${imageName}: ${error2.message}`); + throw error2; } } } @@ -102453,7 +99889,6 @@ var ImageService = { }; // src/inputs.ts -var core3 = __toESM(require_core()); var DYNAMIC = "dynamic"; var DEPENDABOT_ACTOR = "dependabot[bot]"; var JobParameters = class { @@ -102475,13 +99910,13 @@ var JobParameters = class { function getJobParameters(ctx) { checkEnvironmentAndContext(ctx); if (ctx.actor !== DEPENDABOT_ACTOR) { - core3.warning( + warning( `This workflow can only be triggered by Dependabot. Actor was '${ctx.actor}'.` ); return null; } if (process.env.GITHUB_TRIGGERING_ACTOR && process.env.GITHUB_TRIGGERING_ACTOR !== DEPENDABOT_ACTOR) { - core3.warning( + warning( "Dependabot workflows cannot be re-run. Retrigger this update via Dependabot instead." ); return null; @@ -102489,7 +99924,7 @@ function getJobParameters(ctx) { if (ctx.eventName === DYNAMIC) { return fromWorkflowInputs(ctx); } else { - core3.warning( + warning( `Dependabot Updater Action does not support '${ctx.eventName}' events.` ); return null; @@ -102498,11 +99933,11 @@ function getJobParameters(ctx) { function checkEnvironmentAndContext(ctx) { let valid = true; if (!ctx.actor) { - core3.error("GITHUB_ACTOR is not defined"); + error("GITHUB_ACTOR is not defined"); valid = false; } if (!ctx.eventName) { - core3.error("GITHUB_EVENT_NAME is not defined"); + error("GITHUB_EVENT_NAME is not defined"); valid = false; } if (!valid) { @@ -102528,12 +99963,10 @@ function fromWorkflowInputs(ctx) { } // src/updater.ts -var core7 = __toESM(require_core()); var import_dockerode2 = __toESM(require_docker()); // src/container-service.ts -var core4 = __toESM(require_core()); -var fs = __toESM(require("fs")); +var fs2 = __toESM(require("fs")); var import_tar_stream = __toESM(require_tar_stream2()); var ContainerRuntimeError = class extends Error { }; @@ -102554,7 +99987,7 @@ var ContainerService = { async run(container, command) { try { await container.start(); - core4.info(`Started container ${container.id}`); + info(`Started container ${container.id}`); const containerInfo = await container.inspect(); const isDependabotContainer = containerInfo.Config?.Env?.some( (env) => env.startsWith("DEPENDABOT_JOB_ID=") @@ -102593,17 +100026,17 @@ var ContainerService = { } } return true; - } catch (error3) { - core4.info(`Failure running container ${container.id}: ${error3}`); + } catch (error2) { + info(`Failure running container ${container.id}: ${error2}`); throw new ContainerRuntimeError( "The updater encountered one or more errors." ); } finally { try { await container.remove({ v: true, force: true }); - core4.info(`Cleaned up container ${container.id}`); - } catch (error3) { - core4.info(`Failed to clean up container ${container.id}: ${error3}`); + info(`Cleaned up container ${container.id}`); + } catch (error2) { + info(`Failed to clean up container ${container.id}: ${error2}`); } } }, @@ -102624,8 +100057,8 @@ var ContainerService = { stream2.on("end", () => { resolve(); }); - stream2.on("error", (error3) => { - reject(error3); + stream2.on("error", (error2) => { + reject(error2); }); }); await new Promise((resolve) => setTimeout(resolve, 100)); @@ -102659,19 +100092,18 @@ var ContainerService = { archiveStream.pipe(extractor); }); if (content.length > 0) { - fs.appendFileSync(stepSummaryPath, content); - core4.info("Job summary written to GITHUB_STEP_SUMMARY"); + fs2.appendFileSync(stepSummaryPath, content); + info("Job summary written to GITHUB_STEP_SUMMARY"); } } catch { - core4.debug("No job summary file found in container"); + debug("No job summary file found in container"); } } }; // src/proxy.ts -var core5 = __toESM(require_core()); -var import_fs2 = __toESM(require("fs")); -var import_node_forge = __toESM(require_lib6()); +var import_fs3 = __toESM(require("fs")); +var import_node_forge = __toESM(require_lib5()); var KEY_SIZE = 2048; var KEY_EXPIRY_YEARS = 2; var CONFIG_FILE_PATH = "/"; @@ -102739,8 +100171,8 @@ var ProxyBuilder = class { ); const customCAPath = this.customCAPath(); if (customCAPath) { - core5.info("Detected custom CA certificate, adding to proxy"); - const customCert = import_fs2.default.readFileSync(customCAPath, "utf8").toString(); + info("Detected custom CA certificate, adding to proxy"); + const customCert = import_fs3.default.readFileSync(customCAPath, "utf8").toString(); await ContainerService.storeCert( CUSTOM_CA_CERT_NAME, CA_CERT_INPUT_PATH, @@ -102782,10 +100214,10 @@ var ProxyBuilder = class { ], "root" ); - } catch (error3) { + } catch (error2) { throw new Error( `Proxy did not start accepting connections on port 1080 within ${PROXY_READY_TIMEOUT_SECONDS} seconds`, - { cause: error3 } + { cause: error2 } ); } }; @@ -102800,15 +100232,15 @@ var ProxyBuilder = class { const cleanupErrors = []; try { await container.stop(); - } catch (error3) { - if (typeof error3 !== "object" || error3 === null || !("statusCode" in error3) || error3.statusCode !== 304) { - cleanupErrors.push(error3); + } catch (error2) { + if (typeof error2 !== "object" || error2 === null || !("statusCode" in error2) || error2.statusCode !== 304) { + cleanupErrors.push(error2); } } try { await container.remove(); - } catch (error3) { - cleanupErrors.push(error3); + } catch (error2) { + cleanupErrors.push(error2); } const networkCleanupResults = await Promise.allSettled([ externalNetwork.remove(), @@ -102925,7 +100357,7 @@ var ProxyBuilder = class { } }); await externalNetwork.connect({ Container: container.id }); - core5.info(`Created proxy container: ${container.id}`); + info(`Created proxy container: ${container.id}`); return container; } customCAPath() { @@ -102937,7 +100369,6 @@ var ProxyBuilder = class { }; // src/updater-builder.ts -var core6 = __toESM(require_core()); var JOB_OUTPUT_FILENAME = "output.json"; var JOB_OUTPUT_PATH = "/home/dependabot/dependabot-updater/output"; var JOB_INPUT_FILENAME = "job.json"; @@ -103021,7 +100452,7 @@ var UpdaterBuilder = class { container, this.input ); - core6.info(`Created container: ${container.id}`); + info(`Created container: ${container.id}`); return container; } }; @@ -103063,18 +100494,18 @@ var Updater = class { try { await proxy.waitUntilReady(); await this.runUpdate(proxy); - } catch (error3) { + } catch (error2) { try { await this.cleanup(proxy); } catch (cleanupError) { const cleanupErrors = cleanupError instanceof AggregateError ? cleanupError.errors : [cleanupError]; for (const cleanupFailure of cleanupErrors) { - core7.info( + info( `Failed to clean up proxy after update failure: ${cleanupFailure}` ); } } - throw error3; + throw error2; } await this.cleanup(proxy); return true; @@ -103206,21 +100637,21 @@ async function run(context3) { if (!jobToken) { const errorMessage = "Github Dependabot job token is not set"; botSay(`finished: ${errorMessage}`); - core8.setFailed(errorMessage); + setFailed(errorMessage); return; } if (!credentialsToken) { const errorMessage = "Github Dependabot credentials token is not set"; botSay(`finished: ${errorMessage}`); - core8.setFailed(errorMessage); + setFailed(errorMessage); return; } jobId = params.jobId; - core8.setSecret(jobToken); - core8.setSecret(credentialsToken); - const client = new HttpClient2("github/dependabot-action"); + setSecret(jobToken); + setSecret(credentialsToken); + const client = new HttpClient("github/dependabot-action"); const apiClient = new ApiClient(client, params, jobToken, credentialsToken); - core8.info("Fetching job details"); + info("Fetching job details"); const details = await apiClient.getJobDetails(); let updaterImage = params.updaterImage || updaterImageName(details["package-manager"]); let proxyImage = PROXY_IMAGE_NAME; @@ -103230,9 +100661,9 @@ async function run(context3) { package_manager: details["package-manager"], ...additionalTags }); - } catch (error3) { - core8.warning( - `Metric sending failed for ${name}: ${error3.message}` + } catch (error2) { + warning( + `Metric sending failed for ${name}: ${error2.message}` ); } }; @@ -103242,10 +100673,10 @@ async function run(context3) { credentials.push(...registryCredentials); const packagesCred = getPackagesCredential(details, context3.actor); if (packagesCred !== null) { - core8.info("Adding GitHub Packages credential"); + info("Adding GitHub Packages credential"); credentials.push(packagesCred); } - core8.startGroup("Pulling updater images"); + startGroup("Pulling updater images"); let imagesPulled = false; let pullError = new Error("No image source was configured"); const experiments = details?.experiments || {}; @@ -103254,23 +100685,23 @@ async function run(context3) { await ImageService.pull(updaterImage, sendMetricsWithPackageManager); await ImageService.pull(proxyImage, sendMetricsWithPackageManager); imagesPulled = true; - } catch (error3) { - if (error3 instanceof Error) { - pullError = error3; + } catch (error2) { + if (error2 instanceof Error) { + pullError = error2; } } } if (!imagesPulled && experiments[FEATURE_PULL_FROM_AZURE]) { - core8.warning("Primary image pull failed, attempting fallback"); + warning("Primary image pull failed, attempting fallback"); updaterImage = `${FALLBACK_CONTAINER_REGISTRY}/${updaterImage}`; proxyImage = `${FALLBACK_CONTAINER_REGISTRY}/${proxyImage}`; try { await ImageService.pull(updaterImage, sendMetricsWithPackageManager); await ImageService.pull(proxyImage, sendMetricsWithPackageManager); imagesPulled = true; - } catch (error3) { - if (error3 instanceof Error) { - pullError = error3; + } catch (error2) { + if (error2 instanceof Error) { + pullError = error2; } } } @@ -103283,9 +100714,9 @@ async function run(context3) { ); return; } - core8.endGroup(); + endGroup(); try { - core8.info("Starting update process"); + info("Starting update process"); const updater = new Updater( updaterImage, proxyImage, @@ -103294,38 +100725,38 @@ async function run(context3) { credentials ); await updater.runUpdater(); - } catch (error3) { - if (error3 instanceof Error) { + } catch (error2) { + if (error2 instanceof Error) { await failJob( apiClient, "Dependabot encountered an error performing the update", - error3, + error2, "actions_workflow_updater" /* UpdateRun */ ); return; } } botSay("finished"); - } catch (error3) { - if (error3 instanceof CredentialFetchingError) { + } catch (error2) { + if (error2 instanceof CredentialFetchingError) { await failJob( apiClient, "Dependabot was unable to retrieve job credentials", - error3, + error2, "actions_workflow_updater" /* UpdateRun */ ); - } else if (error3 instanceof Error) { + } else if (error2 instanceof Error) { await failJob( apiClient, "Dependabot was unable to start the update", - error3 + error2 ); } return; } - } catch (error3) { - if (error3 instanceof Error) { - setFailed2("Dependabot encountered an unexpected problem", error3); + } catch (error2) { + if (error2 instanceof Error) { + setFailed2("Dependabot encountered an unexpected problem", error2); botSay("finished: unexpected error"); } } @@ -103340,12 +100771,12 @@ function getPackagesCredential(jobDetails, actor) { } const githubToken = process.env.GITHUB_TOKEN; if (!githubToken) { - core8.warning( + warning( "GITHUB_TOKEN is not set; cannot create GitHub Packages credential" ); return null; } - core8.setSecret(githubToken); + setSecret(githubToken); let credential = null; switch (jobDetails["package-manager"]) { case "bundler": @@ -103444,25 +100875,25 @@ function getNuGetPackagesCredential(jobDetails, actor, githubToken) { password: githubToken }; } -async function failJob(apiClient, message, error3, errorType = "actions_workflow_unknown" /* Unknown */) { +async function failJob(apiClient, message, error2, errorType = "actions_workflow_unknown" /* Unknown */) { await apiClient.reportJobError({ "error-type": errorType, "error-details": { - "action-error": error3.message + "action-error": error2.message } }); await apiClient.markJobAsProcessed(); - setFailed2(message, error3); + setFailed2(message, error2); botSay("finished: error reported to Dependabot"); } function botSay(message) { - core8.info(`\u{1F916} ~ ${message} ~`); + info(`\u{1F916} ~ ${message} ~`); } -function setFailed2(message, error3) { +function setFailed2(message, error2) { if (jobId) { - message = [message, error3, dependabotJobHelp()].filter(Boolean).join("\n\n"); + message = [message, error2, dependabotJobHelp()].filter(Boolean).join("\n\n"); } - core8.setFailed(message); + setFailed(message); } function dependabotJobHelp() { if (jobId) { @@ -103508,7 +100939,7 @@ function credentialsFromEnv() { for (const e of parsed) { for (const key of Object.keys(e)) { if (!nonSecrets.includes(key)) { - core8.setSecret(e[key]); + setSecret(e[key]); } } } diff --git a/jest.config.js b/jest.config.js index 08b057a4e..27705f597 100644 --- a/jest.config.js +++ b/jest.config.js @@ -6,11 +6,18 @@ module.exports = { testRunner: 'jest-circus/runner', moduleNameMapper: { '^@actions/github$': '/__mocks__/@actions/github.js', - '^@actions/http-client$': - '/node_modules/@actions/core/node_modules/@actions/http-client/lib/index.js' + '^@actions/core$': '/node_modules/@actions/core', + '^@actions/exec$': '/node_modules/@actions/exec', + '^@actions/http-client$': '/node_modules/@actions/http-client', + '^@actions/http-client/lib/(.*?)(?:\\.js)?$': + '/node_modules/@actions/http-client/lib/$1.js', + '^@actions/io$': '/node_modules/@actions/io', + '^@actions/io/lib/(.*?)(?:\\.js)?$': + '/node_modules/@actions/io/lib/$1.js' }, + transformIgnorePatterns: ['/node_modules/(?!@actions/(core|exec|http-client|io)/)'], transform: { - '^.+\\.ts$': 'ts-jest' + '^.+\\.[jt]s$': ['ts-jest', {tsconfig: {allowJs: true, module: 'commonjs'}}] }, verbose: true } \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index c9b38eda6..bbaeda8c8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,7 +9,7 @@ "version": "3.2.0", "license": "MIT", "dependencies": { - "@actions/core": "^2.0.2", + "@actions/core": "^3.0.1", "@actions/github": "^9.1.1", "@actions/http-client": "^4.0.1", "@octokit/webhooks-types": "^7.6.1", @@ -57,30 +57,22 @@ } }, "node_modules/@actions/core": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/@actions/core/-/core-2.0.2.tgz", - "integrity": "sha512-Ast1V7yHbGAhplAsuVlnb/5J8Mtr/Zl6byPPL+Qjq3lmfIgWF1ak1iYfF/079cRERiuTALTXkSuEUdZeDCfGtA==", - "dependencies": { - "@actions/exec": "^2.0.0", - "@actions/http-client": "^3.0.1" - } - }, - "node_modules/@actions/core/node_modules/@actions/http-client": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-3.0.2.tgz", - "integrity": "sha512-JP38FYYpyqvUsz+Igqlc/JG6YO9PaKuvqjM3iGvaLqFnJ7TFmcLyy2IDrY0bI0qCQug8E9K+elv5ZNfw62ZJzA==", + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@actions/core/-/core-3.0.1.tgz", + "integrity": "sha512-a6d/Nwahm9fliVGRhdhofo40HjHQasUPusmc7vBfyky+7Z+P2A1J68zyFVaNcEclc/Se+eO595oAr5nwEIoIUA==", "license": "MIT", "dependencies": { - "tunnel": "^0.0.6", - "undici": "^6.23.0" + "@actions/exec": "^3.0.0", + "@actions/http-client": "^4.0.0" } }, "node_modules/@actions/exec": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@actions/exec/-/exec-2.0.0.tgz", - "integrity": "sha512-k8ngrX2voJ/RIN6r9xB82NVqKpnMRtxDoiO+g3olkIUpQNqjArXrCQceduQZCQj3P3xm32pChRLqRrtXTlqhIw==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@actions/exec/-/exec-3.0.0.tgz", + "integrity": "sha512-6xH/puSoNBXb72VPlZVm7vQ+svQpFyA96qdDBvhB8eNZOE8LtPf9L4oAsfzK/crCL8YZ+19fKYVnM63Sl+Xzlw==", + "license": "MIT", "dependencies": { - "@actions/io": "^2.0.0" + "@actions/io": "^3.0.2" } }, "node_modules/@actions/github": { @@ -119,9 +111,10 @@ } }, "node_modules/@actions/io": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@actions/io/-/io-2.0.0.tgz", - "integrity": "sha512-Jv33IN09XLO+0HS79aaODsvIRyduiF7NY/F6LYeK5oeUmrsz7aFdRphQjFoESF4jS7lMauDOttKALcpapVDIAg==" + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@actions/io/-/io-3.0.2.tgz", + "integrity": "sha512-nRBchcMM+QK1pdjO7/idu86rbJI5YHUKCvKs0KxnSYbVe3F51UfGxuZX4Qy/fWlp6l7gWFwIkrOzN+oUK03kfw==", + "license": "MIT" }, "node_modules/@babel/code-frame": { "version": "7.27.1", @@ -11043,31 +11036,20 @@ "dev": true }, "@actions/core": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/@actions/core/-/core-2.0.2.tgz", - "integrity": "sha512-Ast1V7yHbGAhplAsuVlnb/5J8Mtr/Zl6byPPL+Qjq3lmfIgWF1ak1iYfF/079cRERiuTALTXkSuEUdZeDCfGtA==", + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@actions/core/-/core-3.0.1.tgz", + "integrity": "sha512-a6d/Nwahm9fliVGRhdhofo40HjHQasUPusmc7vBfyky+7Z+P2A1J68zyFVaNcEclc/Se+eO595oAr5nwEIoIUA==", "requires": { - "@actions/exec": "^2.0.0", - "@actions/http-client": "^3.0.1" - }, - "dependencies": { - "@actions/http-client": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-3.0.2.tgz", - "integrity": "sha512-JP38FYYpyqvUsz+Igqlc/JG6YO9PaKuvqjM3iGvaLqFnJ7TFmcLyy2IDrY0bI0qCQug8E9K+elv5ZNfw62ZJzA==", - "requires": { - "tunnel": "^0.0.6", - "undici": "^6.23.0" - } - } + "@actions/exec": "^3.0.0", + "@actions/http-client": "^4.0.0" } }, "@actions/exec": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@actions/exec/-/exec-2.0.0.tgz", - "integrity": "sha512-k8ngrX2voJ/RIN6r9xB82NVqKpnMRtxDoiO+g3olkIUpQNqjArXrCQceduQZCQj3P3xm32pChRLqRrtXTlqhIw==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@actions/exec/-/exec-3.0.0.tgz", + "integrity": "sha512-6xH/puSoNBXb72VPlZVm7vQ+svQpFyA96qdDBvhB8eNZOE8LtPf9L4oAsfzK/crCL8YZ+19fKYVnM63Sl+Xzlw==", "requires": { - "@actions/io": "^2.0.0" + "@actions/io": "^3.0.2" } }, "@actions/github": { @@ -11105,9 +11087,9 @@ } }, "@actions/io": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@actions/io/-/io-2.0.0.tgz", - "integrity": "sha512-Jv33IN09XLO+0HS79aaODsvIRyduiF7NY/F6LYeK5oeUmrsz7aFdRphQjFoESF4jS7lMauDOttKALcpapVDIAg==" + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@actions/io/-/io-3.0.2.tgz", + "integrity": "sha512-nRBchcMM+QK1pdjO7/idu86rbJI5YHUKCvKs0KxnSYbVe3F51UfGxuZX4Qy/fWlp6l7gWFwIkrOzN+oUK03kfw==" }, "@babel/code-frame": { "version": "7.27.1", diff --git a/package.json b/package.json index d712a6a42..9b42a92ad 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,7 @@ "test-integration": "jest --detectOpenHandles 'integration'", "prepare": "husky install", "dependabot": "ts-node src/cli.ts", - "fetch-images": "ts-node src/fetch-images.ts", + "fetch-images": "esbuild src/fetch-images.ts --bundle --platform=node --target=node24 --loader:.node=empty --outfile=tmp/fetch-images.js && node tmp/fetch-images.js", "cleanup-docker": "ts-node src/cleanup.ts", "update-container-manifest": "ts-node src/update-containers.ts" }, @@ -31,7 +31,7 @@ "author": "GitHub", "license": "MIT", "dependencies": { - "@actions/core": "^2.0.2", + "@actions/core": "^3.0.1", "@actions/github": "^9.1.1", "@actions/http-client": "^4.0.1", "@octokit/webhooks-types": "^7.6.1",