diff --git a/.gitignore b/.gitignore index b512c09..b5e838f 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,3 @@ -node_modules \ No newline at end of file +node_modules +deno.lock +.idea \ No newline at end of file diff --git a/LICENSE b/LICENSE index 5cb2d0b..eb4e593 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2023 Mason Reed +Copyright (c) 2025 Vector 35 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index 25588a5..a26be07 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,15 @@ # Setup Binary Ninja action -This action installs [Binary Ninja] for testing and building both native and python plugins within Github CI. NOTE: This only supports Linux, if you want to run on windows or mac runners you will need to manually create a headless version of [Binary NInja] and pass in the `download-url`. +This action installs [Binary Ninja] for testing and building both native and python plugins within GitHub CI. + +This only supports Linux, if you want to run on Windows or MACOS runners you will need to manually create a headless version of [Binary NInja] and pass in the `download-url`. ## Example usage When using this action it should be noted that the license input should basically always be a secret. ```yaml -uses: emesare/setup-binary-ninja@v1-beta +uses: Vector35/setup-binary-ninja@v1 with: license: '${{ secrets.BN_SERIAL }}' ``` @@ -32,11 +34,11 @@ Override the default download process. This is for advanced use cases where you ### `dev-branch` -Whether or not to use the developer branch of [Binary Ninja]. Default is `false`. +Whether to use the development branch of [Binary Ninja]. Default is `false`. ### `python-support` -Whether or not to expose [Binary Ninja] to the runners python installation, i.e. the ability to `import binaryninja` in python. Make sure you have setup python **before** this action is run. Default is `true`. +Whether or not to expose [Binary Ninja] to the runners python installation, i.e. the ability to `import binaryninja` in python. Make sure you have set up python **before** this action is run. Default is `true`. ## Outputs @@ -48,7 +50,7 @@ The installation directory. ### Building -Github actions must not import remote packages, thus a bundler is required to pack all dependencies into a single script. To regenerate the bundle (dist/index.js) run `npm run build`. +GitHub actions must not import remote packages, thus a bundler is required to pack all dependencies into a single script. To regenerate the bundle (dist/index.js) run `npm run build`. ### Testing @@ -60,7 +62,7 @@ act push -s BN_SERIAL=yourserial -P ubuntu-latest=catthehacker/ubuntu:act-latest ### Commiting -Oddly enough github actions requires the distributed bundle to be in-tree, when commiting changes ensure that the bundle you have built is up-to-date with any changes made to the source. +Oddly enough GitHub actions requires the distributed bundle to be in-tree, when commiting changes ensure that the bundle you have built is up-to-date with any changes made to the source. [Binary Ninja]: https://binary.ninja [act]: https://github.com/nektos/act diff --git a/action.yml b/action.yml index ae13628..f8353d6 100644 --- a/action.yml +++ b/action.yml @@ -1,6 +1,6 @@ name: 'Setup Binary Ninja environment' description: 'Setup Binary Ninja within your github actions runner' -author: 'emesare' +author: 'Vector35' branding: icon: 'bold' color: 'red' @@ -22,5 +22,5 @@ outputs: install-path: description: "Where Binary Ninja was installed" runs: - using: "node16" + using: "node20" main: "dist/index.js" \ No newline at end of file diff --git a/dist/index.js b/dist/index.js index 0c19e18..97f1508 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,13 +1,17 @@ import { createRequire as __WEBPACK_EXTERNAL_createRequire } from "module"; /******/ var __webpack_modules__ = ({ -/***/ 7351: +/***/ 4914: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[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 === undefined) k2 = k; o[k2] = m[k]; @@ -20,14 +24,14 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.issue = exports.issueCommand = void 0; -const os = __importStar(__nccwpck_require__(2037)); -const utils_1 = __nccwpck_require__(5278); +const os = __importStar(__nccwpck_require__(857)); +const utils_1 = __nccwpck_require__(302); /** * Commands * @@ -82,13 +86,13 @@ class Command { } } function escapeData(s) { - return utils_1.toCommandValue(s) + return (0, utils_1.toCommandValue)(s) .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A'); } function escapeProperty(s) { - return utils_1.toCommandValue(s) + return (0, utils_1.toCommandValue)(s) .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A') @@ -99,13 +103,17 @@ function escapeProperty(s) { /***/ }), -/***/ 2186: +/***/ 7484: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[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 === undefined) k2 = k; o[k2] = m[k]; @@ -118,7 +126,7 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; @@ -132,13 +140,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; -const command_1 = __nccwpck_require__(7351); -const file_command_1 = __nccwpck_require__(717); -const utils_1 = __nccwpck_require__(5278); -const os = __importStar(__nccwpck_require__(2037)); -const path = __importStar(__nccwpck_require__(1017)); -const oidc_utils_1 = __nccwpck_require__(8041); +exports.platform = exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = exports.markdownSummary = exports.summary = exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; +const command_1 = __nccwpck_require__(4914); +const file_command_1 = __nccwpck_require__(4753); +const utils_1 = __nccwpck_require__(302); +const os = __importStar(__nccwpck_require__(857)); +const path = __importStar(__nccwpck_require__(6928)); +const oidc_utils_1 = __nccwpck_require__(5306); /** * The code to exit an action */ @@ -152,7 +160,7 @@ var ExitCode; * A code indicating that the action was a failure */ ExitCode[ExitCode["Failure"] = 1] = "Failure"; -})(ExitCode = exports.ExitCode || (exports.ExitCode = {})); +})(ExitCode || (exports.ExitCode = ExitCode = {})); //----------------------------------------------------------------------- // Variables //----------------------------------------------------------------------- @@ -163,13 +171,13 @@ var ExitCode; */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function exportVariable(name, val) { - const convertedVal = utils_1.toCommandValue(val); + const convertedVal = (0, utils_1.toCommandValue)(val); process.env[name] = convertedVal; const filePath = process.env['GITHUB_ENV'] || ''; if (filePath) { - return file_command_1.issueFileCommand('ENV', file_command_1.prepareKeyValueMessage(name, val)); + return (0, file_command_1.issueFileCommand)('ENV', (0, file_command_1.prepareKeyValueMessage)(name, val)); } - command_1.issueCommand('set-env', { name }, convertedVal); + (0, command_1.issueCommand)('set-env', { name }, convertedVal); } exports.exportVariable = exportVariable; /** @@ -177,7 +185,7 @@ exports.exportVariable = exportVariable; * @param secret value of the secret */ function setSecret(secret) { - command_1.issueCommand('add-mask', {}, secret); + (0, command_1.issueCommand)('add-mask', {}, secret); } exports.setSecret = setSecret; /** @@ -187,10 +195,10 @@ exports.setSecret = setSecret; function addPath(inputPath) { const filePath = process.env['GITHUB_PATH'] || ''; if (filePath) { - file_command_1.issueFileCommand('PATH', inputPath); + (0, file_command_1.issueFileCommand)('PATH', inputPath); } else { - command_1.issueCommand('add-path', {}, inputPath); + (0, command_1.issueCommand)('add-path', {}, inputPath); } process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; } @@ -265,10 +273,10 @@ exports.getBooleanInput = getBooleanInput; function setOutput(name, value) { const filePath = process.env['GITHUB_OUTPUT'] || ''; if (filePath) { - return file_command_1.issueFileCommand('OUTPUT', file_command_1.prepareKeyValueMessage(name, value)); + return (0, file_command_1.issueFileCommand)('OUTPUT', (0, file_command_1.prepareKeyValueMessage)(name, value)); } process.stdout.write(os.EOL); - command_1.issueCommand('set-output', { name }, utils_1.toCommandValue(value)); + (0, command_1.issueCommand)('set-output', { name }, (0, utils_1.toCommandValue)(value)); } exports.setOutput = setOutput; /** @@ -277,7 +285,7 @@ exports.setOutput = setOutput; * */ function setCommandEcho(enabled) { - command_1.issue('echo', enabled ? 'on' : 'off'); + (0, command_1.issue)('echo', enabled ? 'on' : 'off'); } exports.setCommandEcho = setCommandEcho; //----------------------------------------------------------------------- @@ -308,7 +316,7 @@ exports.isDebug = isDebug; * @param message debug message */ function debug(message) { - command_1.issueCommand('debug', {}, message); + (0, command_1.issueCommand)('debug', {}, message); } exports.debug = debug; /** @@ -317,7 +325,7 @@ exports.debug = debug; * @param properties optional properties to add to the annotation. */ function error(message, properties = {}) { - command_1.issueCommand('error', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); + (0, command_1.issueCommand)('error', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); } exports.error = error; /** @@ -326,7 +334,7 @@ exports.error = error; * @param properties optional properties to add to the annotation. */ function warning(message, properties = {}) { - command_1.issueCommand('warning', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); + (0, command_1.issueCommand)('warning', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); } exports.warning = warning; /** @@ -335,7 +343,7 @@ exports.warning = warning; * @param properties optional properties to add to the annotation. */ function notice(message, properties = {}) { - command_1.issueCommand('notice', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); + (0, command_1.issueCommand)('notice', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); } exports.notice = notice; /** @@ -354,14 +362,14 @@ exports.info = info; * @param name The name of the output group */ function startGroup(name) { - command_1.issue('group', name); + (0, command_1.issue)('group', name); } exports.startGroup = startGroup; /** * End an output group. */ function endGroup() { - command_1.issue('endgroup'); + (0, command_1.issue)('endgroup'); } exports.endGroup = endGroup; /** @@ -399,9 +407,9 @@ exports.group = group; function saveState(name, value) { const filePath = process.env['GITHUB_STATE'] || ''; if (filePath) { - return file_command_1.issueFileCommand('STATE', file_command_1.prepareKeyValueMessage(name, value)); + return (0, file_command_1.issueFileCommand)('STATE', (0, file_command_1.prepareKeyValueMessage)(name, value)); } - command_1.issueCommand('save-state', { name }, utils_1.toCommandValue(value)); + (0, command_1.issueCommand)('save-state', { name }, (0, utils_1.toCommandValue)(value)); } exports.saveState = saveState; /** @@ -423,32 +431,40 @@ exports.getIDToken = getIDToken; /** * Summary exports */ -var summary_1 = __nccwpck_require__(1327); +var summary_1 = __nccwpck_require__(1847); Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); /** * @deprecated use core.summary */ -var summary_2 = __nccwpck_require__(1327); +var summary_2 = __nccwpck_require__(1847); Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } })); /** * Path exports */ -var path_utils_1 = __nccwpck_require__(2981); +var path_utils_1 = __nccwpck_require__(1976); Object.defineProperty(exports, "toPosixPath", ({ enumerable: true, get: function () { return path_utils_1.toPosixPath; } })); Object.defineProperty(exports, "toWin32Path", ({ enumerable: true, get: function () { return path_utils_1.toWin32Path; } })); Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: function () { return path_utils_1.toPlatformPath; } })); +/** + * Platform utilities exports + */ +exports.platform = __importStar(__nccwpck_require__(8968)); //# sourceMappingURL=core.js.map /***/ }), -/***/ 717: +/***/ 4753: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { // For internal use, subject to change. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[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 === undefined) k2 = k; o[k2] = m[k]; @@ -461,7 +477,7 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; @@ -469,10 +485,10 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.prepareKeyValueMessage = exports.issueFileCommand = void 0; // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ -const fs = __importStar(__nccwpck_require__(7147)); -const os = __importStar(__nccwpck_require__(2037)); -const uuid_1 = __nccwpck_require__(5840); -const utils_1 = __nccwpck_require__(5278); +const crypto = __importStar(__nccwpck_require__(6982)); +const fs = __importStar(__nccwpck_require__(9896)); +const os = __importStar(__nccwpck_require__(857)); +const utils_1 = __nccwpck_require__(302); function issueFileCommand(command, message) { const filePath = process.env[`GITHUB_${command}`]; if (!filePath) { @@ -481,14 +497,14 @@ function issueFileCommand(command, message) { if (!fs.existsSync(filePath)) { throw new Error(`Missing file at path: ${filePath}`); } - fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, { + fs.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os.EOL}`, { encoding: 'utf8' }); } exports.issueFileCommand = issueFileCommand; function prepareKeyValueMessage(key, value) { - const delimiter = `ghadelimiter_${uuid_1.v4()}`; - const convertedValue = utils_1.toCommandValue(value); + const delimiter = `ghadelimiter_${crypto.randomUUID()}`; + const convertedValue = (0, utils_1.toCommandValue)(value); // These should realistically never happen, but just in case someone finds a // way to exploit uuid generation let's not allow keys or values that contain // the delimiter. @@ -505,7 +521,7 @@ exports.prepareKeyValueMessage = prepareKeyValueMessage; /***/ }), -/***/ 8041: +/***/ 5306: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { @@ -520,9 +536,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.OidcClient = void 0; -const http_client_1 = __nccwpck_require__(6255); -const auth_1 = __nccwpck_require__(5526); -const core_1 = __nccwpck_require__(2186); +const http_client_1 = __nccwpck_require__(4844); +const auth_1 = __nccwpck_require__(4552); +const core_1 = __nccwpck_require__(7484); class OidcClient { static createHttpClient(allowRetry = true, maxRetry = 10) { const requestOptions = { @@ -554,7 +570,7 @@ class OidcClient { .catch(error => { throw new Error(`Failed to get ID Token. \n Error Code : ${error.statusCode}\n - Error Message: ${error.result.message}`); + Error Message: ${error.message}`); }); const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; if (!id_token) { @@ -572,9 +588,9 @@ class OidcClient { const encodedAudience = encodeURIComponent(audience); id_token_url = `${id_token_url}&audience=${encodedAudience}`; } - core_1.debug(`ID token url is ${id_token_url}`); + (0, core_1.debug)(`ID token url is ${id_token_url}`); const id_token = yield OidcClient.getCall(id_token_url); - core_1.setSecret(id_token); + (0, core_1.setSecret)(id_token); return id_token; } catch (error) { @@ -588,13 +604,17 @@ exports.OidcClient = OidcClient; /***/ }), -/***/ 2981: +/***/ 1976: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[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 === undefined) k2 = k; o[k2] = m[k]; @@ -607,13 +627,13 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; -const path = __importStar(__nccwpck_require__(1017)); +const path = __importStar(__nccwpck_require__(6928)); /** * toPosixPath converts the given path to the posix form. On Windows, \\ will be * replaced with /. @@ -652,7 +672,107 @@ exports.toPlatformPath = toPlatformPath; /***/ }), -/***/ 1327: +/***/ 8968: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) 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 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__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 = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getDetails = exports.isLinux = exports.isMacOS = exports.isWindows = exports.arch = exports.platform = void 0; +const os_1 = __importDefault(__nccwpck_require__(857)); +const exec = __importStar(__nccwpck_require__(5236)); +const getWindowsInfo = () => __awaiter(void 0, void 0, void 0, function* () { + const { stdout: version } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Version"', undefined, { + silent: true + }); + const { stdout: name } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Caption"', undefined, { + silent: true + }); + return { + name: name.trim(), + version: version.trim() + }; +}); +const getMacOsInfo = () => __awaiter(void 0, void 0, void 0, function* () { + var _a, _b, _c, _d; + const { stdout } = yield exec.getExecOutput('sw_vers', undefined, { + 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 + }; +}); +const 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 + }; +}); +exports.platform = os_1.default.platform(); +exports.arch = os_1.default.arch(); +exports.isWindows = exports.platform === 'win32'; +exports.isMacOS = exports.platform === 'darwin'; +exports.isLinux = exports.platform === 'linux'; +function getDetails() { + return __awaiter(this, void 0, void 0, function* () { + return Object.assign(Object.assign({}, (yield (exports.isWindows + ? getWindowsInfo() + : exports.isMacOS + ? getMacOsInfo() + : getLinuxInfo()))), { platform: exports.platform, + arch: exports.arch, + isWindows: exports.isWindows, + isMacOS: exports.isMacOS, + isLinux: exports.isLinux }); + }); +} +exports.getDetails = getDetails; +//# sourceMappingURL=platform.js.map + +/***/ }), + +/***/ 1847: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { @@ -667,8 +787,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0; -const os_1 = __nccwpck_require__(2037); -const fs_1 = __nccwpck_require__(7147); +const os_1 = __nccwpck_require__(857); +const fs_1 = __nccwpck_require__(9896); const { access, appendFile, writeFile } = fs_1.promises; exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY'; exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary'; @@ -941,7 +1061,7 @@ exports.summary = _summary; /***/ }), -/***/ 5278: +/***/ 302: /***/ ((__unused_webpack_module, exports) => { @@ -987,10 +1107,29 @@ exports.toCommandProperties = toCommandProperties; /***/ }), -/***/ 5526: -/***/ (function(__unused_webpack_module, exports) { +/***/ 5236: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; var __awaiter = (this && this.__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) { @@ -1001,84 +1140,86 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0; -class BasicCredentialHandler { - 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'); - }); - } -} -exports.BasicCredentialHandler = BasicCredentialHandler; -class BearerCredentialHandler { - 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'); - }); - } +exports.getExecOutput = exports.exec = void 0; +const string_decoder_1 = __nccwpck_require__(3193); +const tr = __importStar(__nccwpck_require__(6665)); +/** + * Exec a command. + * Output will be streamed to the live console. + * Returns promise with return code + * + * @param commandLine command to execute (can include additional args). Must be correctly escaped. + * @param args optional arguments for tool. Escaping is handled by the lib. + * @param options optional exec options. See ExecOptions + * @returns Promise exit code + */ +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.`); + } + // Path to tool to execute should be first arg + const toolPath = commandArgs[0]; + args = commandArgs.slice(1).concat(args || []); + const runner = new tr.ToolRunner(toolPath, args, options); + return runner.exec(); + }); } -exports.BearerCredentialHandler = BearerCredentialHandler; -class PersonalAccessTokenCredentialHandler { - 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'); - }); - } +exports.exec = exec; +/** + * Exec a command and get the output. + * Output will be streamed to the live console. + * Returns promise with the exit code and collected stdout and stderr + * + * @param commandLine command to execute (can include additional args). Must be correctly escaped. + * @param args optional arguments for tool. Escaping is handled by the lib. + * @param options optional exec options. See ExecOptions + * @returns Promise exit code, stdout, and stderr + */ +function getExecOutput(commandLine, args, options) { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + let stdout = ''; + let stderr = ''; + //Using string decoder covers the case where a mult-byte character is split + 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 })); + //flush any remaining characters + stdout += stdoutDecoder.end(); + stderr += stderrDecoder.end(); + return { + exitCode, + stdout, + stderr + }; + }); } -exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; -//# sourceMappingURL=auth.js.map +exports.getExecOutput = getExecOutput; +//# sourceMappingURL=exec.js.map /***/ }), -/***/ 6255: +/***/ 6665: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -/* eslint-disable @typescript-eslint/no-explicit-any */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); @@ -1108,204 +1249,934 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; -const http = __importStar(__nccwpck_require__(3685)); -const https = __importStar(__nccwpck_require__(5687)); -const pm = __importStar(__nccwpck_require__(9835)); -const tunnel = __importStar(__nccwpck_require__(4294)); -var HttpCodes; -(function (HttpCodes) { - HttpCodes[HttpCodes["OK"] = 200] = "OK"; - HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; - HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; - HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; - HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; - HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; - HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; - HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; - HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; - HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; - HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; - HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; - HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; - HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; - HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; - HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; - HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; - HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; - HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; - HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; - HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; - HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; - HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; - HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; - HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; - HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; - HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; -})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); -var Headers; -(function (Headers) { - Headers["Accept"] = "accept"; - Headers["ContentType"] = "content-type"; -})(Headers = exports.Headers || (exports.Headers = {})); -var MediaTypes; -(function (MediaTypes) { - MediaTypes["ApplicationJson"] = "application/json"; -})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {})); -/** - * Returns the proxy URL, depending upon the supplied url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com +exports.argStringToArray = exports.ToolRunner = void 0; +const os = __importStar(__nccwpck_require__(857)); +const events = __importStar(__nccwpck_require__(4434)); +const child = __importStar(__nccwpck_require__(5317)); +const path = __importStar(__nccwpck_require__(6928)); +const io = __importStar(__nccwpck_require__(4994)); +const ioUtil = __importStar(__nccwpck_require__(5207)); +const timers_1 = __nccwpck_require__(3557); +/* eslint-disable @typescript-eslint/unbound-method */ +const IS_WINDOWS = process.platform === 'win32'; +/* + * Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way. */ -function getProxyUrl(serverUrl) { - const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); - return proxyUrl ? proxyUrl.href : ''; -} -exports.getProxyUrl = getProxyUrl; -const HttpRedirectCodes = [ - HttpCodes.MovedPermanently, - HttpCodes.ResourceMoved, - HttpCodes.SeeOther, - HttpCodes.TemporaryRedirect, - HttpCodes.PermanentRedirect -]; -const HttpResponseRetryCodes = [ - HttpCodes.BadGateway, - HttpCodes.ServiceUnavailable, - HttpCodes.GatewayTimeout -]; -const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; -const ExponentialBackoffCeiling = 10; -const ExponentialBackoffTimeSlice = 5; -class HttpClientError extends Error { - constructor(message, statusCode) { - super(message); - this.name = 'HttpClientError'; - this.statusCode = statusCode; - Object.setPrototypeOf(this, HttpClientError.prototype); - } -} -exports.HttpClientError = HttpClientError; -class HttpClientResponse { - constructor(message) { - this.message = message; +class ToolRunner 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]'; // omit prefix when piped to a second tool + if (IS_WINDOWS) { + // Windows + cmd file + if (this._isCmdFile()) { + cmd += toolPath; + for (const a of args) { + cmd += ` ${a}`; + } + } + // Windows + verbatim + else if (options.windowsVerbatimArguments) { + cmd += `"${toolPath}"`; + for (const a of args) { + cmd += ` ${a}`; + } + } + // Windows (regular) + else { + cmd += this._windowsQuoteCmdArg(toolPath); + for (const a of args) { + cmd += ` ${this._windowsQuoteCmdArg(a)}`; + } + } + } + else { + // OSX/Linux - this can likely be improved with some form of quoting. + // creating processes on Unix is fundamentally different than Windows. + // on Unix, execvp() takes an arg array. + cmd += toolPath; + for (const a of args) { + cmd += ` ${a}`; + } + } + return cmd; } - readBody() { + _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); + // the rest of the string ... + s = s.substring(n + os.EOL.length); + n = s.indexOf(os.EOL); + } + return s; + } + catch (err) { + // streaming lines to console is best effort. Don't fail a build. + 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) { + // for .exe, apply the normal quoting rules that libuv applies + if (!this._isCmdFile()) { + return this._uvQuoteCmdArg(arg); + } + // otherwise apply quoting rules specific to the cmd.exe command line parser. + // the libuv rules are generic and are not designed specifically for cmd.exe + // command line parser. + // + // for a detailed description of the cmd.exe command line parser, refer to + // http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912 + // need quotes for empty arg + if (!arg) { + return '""'; + } + // determine whether the arg needs to be quoted + const cmdSpecialChars = [ + ' ', + '\t', + '&', + '(', + ')', + '[', + ']', + '{', + '}', + '^', + '=', + ';', + '!', + "'", + '+', + ',', + '`', + '~', + '|', + '<', + '>', + '"' + ]; + let needsQuotes = false; + for (const char of arg) { + if (cmdSpecialChars.some(x => x === char)) { + needsQuotes = true; + break; + } + } + // short-circuit if quotes not needed + if (!needsQuotes) { + return arg; + } + // the following quoting rules are very similar to the rules that by libuv applies. + // + // 1) wrap the string in quotes + // + // 2) double-up quotes - i.e. " => "" + // + // this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately + // doesn't work well with a cmd.exe command line. + // + // note, replacing " with "" also works well if the arg is passed to a downstream .NET console app. + // for example, the command line: + // foo.exe "myarg:""my val""" + // is parsed by a .NET console app into an arg array: + // [ "myarg:\"my val\"" ] + // which is the same end result when applying libuv quoting rules. although the actual + // command line from libuv quoting rules would look like: + // foo.exe "myarg:\"my val\"" + // + // 3) double-up slashes that precede a quote, + // e.g. hello \world => "hello \world" + // hello\"world => "hello\\""world" + // hello\\"world => "hello\\\\""world" + // hello world\ => "hello world\\" + // + // technically this is not required for a cmd.exe command line, or the batch argument parser. + // the reasons for including this as a .cmd quoting rule are: + // + // a) this is optimized for the scenario where the argument is passed from the .cmd file to an + // external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule. + // + // b) it's what we've been doing previously (by deferring to node default behavior) and we + // haven't heard any complaints about that aspect. + // + // note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be + // escaped when used on the command line directly - even though within a .cmd file % can be escaped + // by using %%. + // + // the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts + // the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing. + // + // one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would + // often work, since it is unlikely that var^ would exist, and the ^ character is removed when the + // variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args + // to an external program. + // + // an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file. + // % can be escaped within a .cmd file. + let reverse = '"'; + let quoteHit = true; + for (let i = arg.length; i > 0; i--) { + // walk the string in reverse + reverse += arg[i - 1]; + if (quoteHit && arg[i - 1] === '\\') { + reverse += '\\'; // double the slash + } + else if (arg[i - 1] === '"') { + quoteHit = true; + reverse += '"'; // double the quote + } + else { + quoteHit = false; + } + } + reverse += '"'; + return reverse + .split('') + .reverse() + .join(''); + } + _uvQuoteCmdArg(arg) { + // Tool runner wraps child_process.spawn() and needs to apply the same quoting as + // Node in certain cases where the undocumented spawn option windowsVerbatimArguments + // is used. + // + // Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV, + // see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details), + // pasting copyright notice from Node within this function: + // + // Copyright Joyent, Inc. and other Node contributors. All rights reserved. + // + // Permission is hereby granted, free of charge, to any person obtaining a copy + // of this software and associated documentation files (the "Software"), to + // deal in the Software without restriction, including without limitation the + // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + // sell copies of the Software, and to permit persons to whom the Software is + // furnished to do so, subject to the following conditions: + // + // The above copyright notice and this permission notice shall be included in + // all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + // IN THE SOFTWARE. + if (!arg) { + // Need double quotation for empty argument + return '""'; + } + if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) { + // No quotation needed + return arg; + } + if (!arg.includes('"') && !arg.includes('\\')) { + // No embedded double quotes or backslashes, so I can just wrap + // quote marks around the whole thing. + return `"${arg}"`; + } + // Expected input/output: + // input : hello"world + // output: "hello\"world" + // input : hello""world + // output: "hello\"\"world" + // input : hello\world + // output: hello\world + // input : hello\\world + // output: hello\\world + // input : hello\"world + // output: "hello\\\"world" + // input : hello\\"world + // output: "hello\\\\\"world" + // input : hello world\ + // output: "hello world\\" - note the comment in libuv actually reads "hello world\" + // but it appears the comment is wrong, it should be "hello world\\" + let reverse = '"'; + let quoteHit = true; + for (let i = arg.length; i > 0; i--) { + // walk the string in reverse + 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 || 10000 + }; + 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* () { - 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]); + // root the tool path if it is unrooted and contains relative pathing + if (!ioUtil.isRooted(this.toolPath) && + (this.toolPath.includes('/') || + (IS_WINDOWS && this.toolPath.includes('\\')))) { + // prefer options.cwd if it is specified, however options.cwd may also need to be rooted + this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); + } + // if the tool is only a file name, then resolve it from the PATH + // otherwise verify it exists (add extension on Windows if necessary) + 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); }); - this.message.on('end', () => { - resolve(output.toString()); + 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', (error, exitCode) => { + if (stdbuffer.length > 0) { + this.emit('stdline', stdbuffer); + } + if (errbuffer.length > 0) { + this.emit('errline', errbuffer); + } + cp.removeAllListeners(); + if (error) { + reject(error); + } + else { + resolve(exitCode); + } }); + if (this.options.input) { + if (!cp.stdin) { + throw new Error('child process missing stdin'); + } + cp.stdin.end(this.options.input); + } })); }); } } -exports.HttpClientResponse = HttpClientResponse; -function isHttps(requestUrl) { - const parsedUrl = new URL(requestUrl); - return parsedUrl.protocol === 'https:'; -} -exports.isHttps = isHttps; -class HttpClient { - 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 = 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; +exports.ToolRunner = ToolRunner; +/** + * Convert an arg string to an array of args. Handles escaping + * + * @param argString string of arguments + * @returns string[] array of arguments + */ +function argStringToArray(argString) { + const args = []; + let inQuotes = false; + let escaped = false; + let arg = ''; + function append(c) { + // we only escape double quotes. + 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; } - if (requestOptions.allowRedirectDowngrade != null) { - this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + else { + append(c); } - if (requestOptions.maxRedirects != null) { - this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + continue; + } + if (c === '\\' && escaped) { + append(c); + continue; + } + if (c === '\\' && inQuotes) { + escaped = true; + continue; + } + if (c === ' ' && !inQuotes) { + if (arg.length > 0) { + args.push(arg); + arg = ''; } - if (requestOptions.keepAlive != null) { - this._keepAlive = requestOptions.keepAlive; + continue; + } + append(c); + } + if (arg.length > 0) { + args.push(arg.trim()); + } + return args; +} +exports.argStringToArray = argStringToArray; +class ExecState extends events.EventEmitter { + constructor(options, toolPath) { + super(); + this.processClosed = false; // tracks whether the process has exited and stdio is closed + this.processError = ''; + this.processExitCode = 0; + this.processExited = false; // tracks whether the process has exited + this.processStderr = false; // tracks whether stderr was written to + this.delay = 10000; // 10 seconds + 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 = timers_1.setTimeout(ExecState.HandleTimeout, this.delay, this); + } + } + _debug(message) { + this.emit('debug', message); + } + _setResult() { + // determine whether there is an error + let error; + if (this.processExited) { + if (this.processError) { + error = 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}`); } - if (requestOptions.allowRetries != null) { - this._allowRetries = requestOptions.allowRetries; + else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) { + error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`); } - if (requestOptions.maxRetries != null) { - this._maxRetries = requestOptions.maxRetries; + else if (this.processStderr && this.options.failOnStdErr) { + error = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`); } } + // clear the timeout + if (this.timeout) { + clearTimeout(this.timeout); + this.timeout = null; + } + this.done = true; + this.emit('done', error, this.processExitCode); } - options(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); - }); + static HandleTimeout(state) { + if (state.done) { + return; + } + if (!state.processClosed && state.processExited) { + const message = `The STDIO streams did not close within ${state.delay / + 1000} 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(); } - get(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('GET', requestUrl, null, additionalHeaders || {}); - }); +} +//# sourceMappingURL=toolrunner.js.map + +/***/ }), + +/***/ 4552: +/***/ (function(__unused_webpack_module, exports) { + + +var __awaiter = (this && this.__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(exports, "__esModule", ({ value: true })); +exports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0; +class BasicCredentialHandler { + constructor(username, password) { + this.username = username; + this.password = password; } - del(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('DELETE', requestUrl, null, additionalHeaders || {}); - }); + prepareRequest(options) { + if (!options.headers) { + throw Error('The request has no headers'); + } + options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`; } - post(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('POST', requestUrl, data, additionalHeaders || {}); - }); + // This handler cannot handle 401 + canHandleAuthentication() { + return false; } - patch(requestUrl, data, additionalHeaders) { + handleAuthentication() { return __awaiter(this, void 0, void 0, function* () { - return this.request('PATCH', requestUrl, data, additionalHeaders || {}); + throw new Error('not implemented'); }); } - put(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('PUT', requestUrl, data, additionalHeaders || {}); - }); +} +exports.BasicCredentialHandler = BasicCredentialHandler; +class BearerCredentialHandler { + constructor(token) { + this.token = token; } - head(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('HEAD', requestUrl, null, additionalHeaders || {}); - }); + // 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}`; } - sendStream(verb, requestUrl, stream, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request(verb, requestUrl, stream, additionalHeaders); - }); + // This handler cannot handle 401 + canHandleAuthentication() { + return false; } - /** - * Gets a typed object from an endpoint - * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise - */ - getJson(requestUrl, additionalHeaders = {}) { + handleAuthentication() { return __awaiter(this, void 0, void 0, function* () { - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - const res = yield this.get(requestUrl, additionalHeaders); - return this._processResponse(res, this.requestOptions); + throw new Error('not implemented'); }); } - postJson(requestUrl, obj, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - const res = yield this.post(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); +} +exports.BearerCredentialHandler = BearerCredentialHandler; +class PersonalAccessTokenCredentialHandler { + 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'); + }); + } +} +exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; +//# sourceMappingURL=auth.js.map + +/***/ }), + +/***/ 4844: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +/* eslint-disable @typescript-eslint/no-explicit-any */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) 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 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__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(exports, "__esModule", ({ value: true })); +exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; +const http = __importStar(__nccwpck_require__(8611)); +const https = __importStar(__nccwpck_require__(5692)); +const pm = __importStar(__nccwpck_require__(4988)); +const tunnel = __importStar(__nccwpck_require__(770)); +const undici_1 = __nccwpck_require__(6752); +var HttpCodes; +(function (HttpCodes) { + HttpCodes[HttpCodes["OK"] = 200] = "OK"; + HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; + HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; + HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; + HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; + HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; + HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; + HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; + HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; + HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; + HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; +})(HttpCodes || (exports.HttpCodes = HttpCodes = {})); +var Headers; +(function (Headers) { + Headers["Accept"] = "accept"; + Headers["ContentType"] = "content-type"; +})(Headers || (exports.Headers = Headers = {})); +var MediaTypes; +(function (MediaTypes) { + MediaTypes["ApplicationJson"] = "application/json"; +})(MediaTypes || (exports.MediaTypes = MediaTypes = {})); +/** + * Returns the proxy URL, depending upon the supplied url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ +function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ''; +} +exports.getProxyUrl = getProxyUrl; +const HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect +]; +const HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout +]; +const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; +const ExponentialBackoffCeiling = 10; +const ExponentialBackoffTimeSlice = 5; +class HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = 'HttpClientError'; + this.statusCode = statusCode; + Object.setPrototypeOf(this, HttpClientError.prototype); + } +} +exports.HttpClientError = HttpClientError; +class HttpClientResponse { + 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)); + }); + })); + }); + } +} +exports.HttpClientResponse = HttpClientResponse; +function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === 'https:'; +} +exports.isHttps = isHttps; +class HttpClient { + 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 = 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, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + 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, obj, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } putJson(requestUrl, obj, additionalHeaders = {}) { return __awaiter(this, void 0, void 0, function* () { @@ -1507,6 +2378,15 @@ class HttpClient { 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 info = {}; info.parsedUrl = requestUrl; @@ -1554,7 +2434,7 @@ class HttpClient { if (this._keepAlive && useProxy) { agent = this._proxyAgent; } - if (this._keepAlive && !useProxy) { + if (!useProxy) { agent = this._agent; } // if agent is already assigned use that agent. @@ -1586,16 +2466,12 @@ class HttpClient { agent = tunnelAgent(agentOptions); this._proxyAgent = agent; } - // if reusing agent across request and tunneling agent isn't assigned create a new agent - if (this._keepAlive && !agent) { + // if tunneling agent isn't assigned create a new agent + if (!agent) { const options = { keepAlive: this._keepAlive, maxSockets }; agent = usingSsl ? new https.Agent(options) : new http.Agent(options); this._agent = agent; } - // if not using private agent and tunnel agent isn't setup then use global agent - if (!agent) { - agent = usingSsl ? https.globalAgent : http.globalAgent; - } if (usingSsl && this._ignoreSslError) { // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options @@ -1606,6 +2482,30 @@ class HttpClient { } return agent; } + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + // if agent is already assigned use that agent. + 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) { + // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process + // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options + // we have to cast it to any and change it directly + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } _performExponentialBackoff(retryNumber) { return __awaiter(this, void 0, void 0, function* () { retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); @@ -1685,7 +2585,7 @@ const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCa /***/ }), -/***/ 9835: +/***/ 4988: /***/ ((__unused_webpack_module, exports) => { @@ -1705,7 +2605,13 @@ function getProxyUrl(reqUrl) { } })(); if (proxyVar) { - return new URL(proxyVar); + try { + return new DecodedURL(proxyVar); + } + catch (_a) { + if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://')) + return new DecodedURL(`http://${proxyVar}`); + } } else { return undefined; @@ -1763,1980 +2669,518 @@ function isLoopbackAddress(host) { hostLower.startsWith('[::1]') || hostLower.startsWith('[0:0:0:0:0:0:0:1]')); } +class DecodedURL 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; + } +} //# sourceMappingURL=proxy.js.map /***/ }), -/***/ 9417: -/***/ ((module) => { - - -module.exports = balanced; -function balanced(a, b, str) { - if (a instanceof RegExp) a = maybeMatch(a, str); - if (b instanceof RegExp) b = maybeMatch(b, str); +/***/ 5207: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - var r = range(a, b, str); - return r && { - start: r[0], - end: r[1], - pre: str.slice(0, r[0]), - body: str.slice(r[0] + a.length, r[1]), - post: str.slice(r[1] + b.length) - }; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__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(exports, "__esModule", ({ value: true })); +exports.getCmdPath = exports.tryGetExecutablePath = exports.isRooted = exports.isDirectory = exports.exists = exports.READONLY = exports.UV_FS_O_EXLOCK = exports.IS_WINDOWS = exports.unlink = exports.symlink = exports.stat = exports.rmdir = exports.rm = exports.rename = exports.readlink = exports.readdir = exports.open = exports.mkdir = exports.lstat = exports.copyFile = exports.chmod = void 0; +const fs = __importStar(__nccwpck_require__(9896)); +const path = __importStar(__nccwpck_require__(6928)); +_a = fs.promises +// export const {open} = 'fs' +, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.open = _a.open, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rm = _a.rm, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink; +// export const {open} = 'fs' +exports.IS_WINDOWS = process.platform === 'win32'; +// See https://github.com/nodejs/node/blob/d0153aee367422d0858105abec186da4dff0a0c5/deps/uv/include/uv/win.h#L691 +exports.UV_FS_O_EXLOCK = 0x10000000; +exports.READONLY = fs.constants.O_RDONLY; +function exists(fsPath) { + return __awaiter(this, void 0, void 0, function* () { + try { + yield exports.stat(fsPath); + } + catch (err) { + if (err.code === 'ENOENT') { + return false; + } + throw err; + } + return true; + }); } - -function maybeMatch(reg, str) { - var m = str.match(reg); - return m ? m[0] : null; +exports.exists = exists; +function isDirectory(fsPath, useStat = false) { + return __awaiter(this, void 0, void 0, function* () { + const stats = useStat ? yield exports.stat(fsPath) : yield exports.lstat(fsPath); + return stats.isDirectory(); + }); } - -balanced.range = range; -function range(a, b, str) { - var begs, beg, left, right, result; - var ai = str.indexOf(a); - var bi = str.indexOf(b, ai + 1); - var i = ai; - - if (ai >= 0 && bi > 0) { - if(a===b) { - return [ai, bi]; - } - begs = []; - left = str.length; - - while (i >= 0 && !result) { - if (i == ai) { - begs.push(i); - ai = str.indexOf(a, i + 1); - } else if (begs.length == 1) { - result = [ begs.pop(), bi ]; - } else { - beg = begs.pop(); - if (beg < left) { - left = beg; - right = bi; - } - - bi = str.indexOf(b, i + 1); - } - - i = ai < bi && ai >= 0 ? ai : bi; +exports.isDirectory = isDirectory; +/** + * On OSX/Linux, true if path starts with '/'. On Windows, true for paths like: + * \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases). + */ +function isRooted(p) { + p = normalizeSeparators(p); + if (!p) { + throw new Error('isRooted() parameter "p" cannot be empty'); } - - if (begs.length) { - result = [ left, right ]; + if (exports.IS_WINDOWS) { + return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello + ); // e.g. C: or C:\hello } - } - - return result; + return p.startsWith('/'); } - +exports.isRooted = isRooted; +/** + * Best effort attempt to determine whether a file exists and is executable. + * @param filePath file path to check + * @param extensions additional file extensions to try + * @return if file exists and is executable, returns the file path. otherwise empty string. + */ +function tryGetExecutablePath(filePath, extensions) { + return __awaiter(this, void 0, void 0, function* () { + let stats = undefined; + try { + // test file exists + stats = yield exports.stat(filePath); + } + catch (err) { + if (err.code !== 'ENOENT') { + // eslint-disable-next-line no-console + console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); + } + } + if (stats && stats.isFile()) { + if (exports.IS_WINDOWS) { + // on Windows, test for valid extension + const upperExt = path.extname(filePath).toUpperCase(); + if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) { + return filePath; + } + } + else { + if (isUnixExecutable(stats)) { + return filePath; + } + } + } + // try each extension + const originalFilePath = filePath; + for (const extension of extensions) { + filePath = originalFilePath + extension; + stats = undefined; + try { + stats = yield exports.stat(filePath); + } + catch (err) { + if (err.code !== 'ENOENT') { + // eslint-disable-next-line no-console + console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); + } + } + if (stats && stats.isFile()) { + if (exports.IS_WINDOWS) { + // preserve the case of the actual file (since an extension was appended) + try { + const directory = path.dirname(filePath); + const upperName = path.basename(filePath).toUpperCase(); + for (const actualName of yield exports.readdir(directory)) { + if (upperName === actualName.toUpperCase()) { + filePath = path.join(directory, actualName); + break; + } + } + } + catch (err) { + // eslint-disable-next-line no-console + console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`); + } + return filePath; + } + else { + if (isUnixExecutable(stats)) { + return filePath; + } + } + } + } + return ''; + }); +} +exports.tryGetExecutablePath = tryGetExecutablePath; +function normalizeSeparators(p) { + p = p || ''; + if (exports.IS_WINDOWS) { + // convert slashes on Windows + p = p.replace(/\//g, '\\'); + // remove redundant slashes + return p.replace(/\\\\+/g, '\\'); + } + // remove redundant slashes + return p.replace(/\/\/+/g, '/'); +} +// on Mac/Linux, test the execute bit +// R W X R W X R W X +// 256 128 64 32 16 8 4 2 1 +function isUnixExecutable(stats) { + return ((stats.mode & 1) > 0 || + ((stats.mode & 8) > 0 && stats.gid === process.getgid()) || + ((stats.mode & 64) > 0 && stats.uid === process.getuid())); +} +// Get the path of cmd.exe in windows +function getCmdPath() { + var _a; + return (_a = process.env['COMSPEC']) !== null && _a !== void 0 ? _a : `cmd.exe`; +} +exports.getCmdPath = getCmdPath; +//# sourceMappingURL=io-util.js.map /***/ }), -/***/ 1575: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/* module decorator */ module = __nccwpck_require__.nmd(module); -var bigInt = (function (undefined) { - "use strict"; - - var BASE = 1e7, - LOG_BASE = 7, - MAX_INT = 9007199254740992, - MAX_INT_ARR = smallToArray(MAX_INT), - DEFAULT_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz"; - - var supportsNativeBigInt = typeof BigInt === "function"; - - function Integer(v, radix, alphabet, caseSensitive) { - if (typeof v === "undefined") return Integer[0]; - if (typeof radix !== "undefined") return +radix === 10 && !alphabet ? parseValue(v) : parseBase(v, radix, alphabet, caseSensitive); - return parseValue(v); - } - - function BigInteger(value, sign) { - this.value = value; - this.sign = sign; - this.isSmall = false; - } - BigInteger.prototype = Object.create(Integer.prototype); - - function SmallInteger(value) { - this.value = value; - this.sign = value < 0; - this.isSmall = true; - } - SmallInteger.prototype = Object.create(Integer.prototype); - - function NativeBigInt(value) { - this.value = value; - } - NativeBigInt.prototype = Object.create(Integer.prototype); - - function isPrecise(n) { - return -MAX_INT < n && n < MAX_INT; - } - - function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes - if (n < 1e7) - return [n]; - if (n < 1e14) - return [n % 1e7, Math.floor(n / 1e7)]; - return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)]; - } - - function arrayToSmall(arr) { // If BASE changes this function may need to change - trim(arr); - var length = arr.length; - if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) { - switch (length) { - case 0: return 0; - case 1: return arr[0]; - case 2: return arr[0] + arr[1] * BASE; - default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE; - } - } - return arr; - } - - function trim(v) { - var i = v.length; - while (v[--i] === 0); - v.length = i + 1; - } - - function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger - var x = new Array(length); - var i = -1; - while (++i < length) { - x[i] = 0; - } - return x; - } - - function truncate(n) { - if (n > 0) return Math.floor(n); - return Math.ceil(n); - } - - function add(a, b) { // assumes a and b are arrays with a.length >= b.length - var l_a = a.length, - l_b = b.length, - r = new Array(l_a), - carry = 0, - base = BASE, - sum, i; - for (i = 0; i < l_b; i++) { - sum = a[i] + b[i] + carry; - carry = sum >= base ? 1 : 0; - r[i] = sum - carry * base; - } - while (i < l_a) { - sum = a[i] + carry; - carry = sum === base ? 1 : 0; - r[i++] = sum - carry * base; - } - if (carry > 0) r.push(carry); - return r; - } - - function addAny(a, b) { - if (a.length >= b.length) return add(a, b); - return add(b, a); - } - - function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT - var l = a.length, - r = new Array(l), - base = BASE, - sum, i; - for (i = 0; i < l; i++) { - sum = a[i] - base + carry; - carry = Math.floor(sum / base); - r[i] = sum - carry * base; - carry += 1; - } - while (carry > 0) { - r[i++] = carry % base; - carry = Math.floor(carry / base); - } - return r; - } - - BigInteger.prototype.add = function (v) { - var n = parseValue(v); - if (this.sign !== n.sign) { - return this.subtract(n.negate()); - } - var a = this.value, b = n.value; - if (n.isSmall) { - return new BigInteger(addSmall(a, Math.abs(b)), this.sign); - } - return new BigInteger(addAny(a, b), this.sign); - }; - BigInteger.prototype.plus = BigInteger.prototype.add; - - SmallInteger.prototype.add = function (v) { - var n = parseValue(v); - var a = this.value; - if (a < 0 !== n.sign) { - return this.subtract(n.negate()); - } - var b = n.value; - if (n.isSmall) { - if (isPrecise(a + b)) return new SmallInteger(a + b); - b = smallToArray(Math.abs(b)); - } - return new BigInteger(addSmall(b, Math.abs(a)), a < 0); - }; - SmallInteger.prototype.plus = SmallInteger.prototype.add; - - NativeBigInt.prototype.add = function (v) { - return new NativeBigInt(this.value + parseValue(v).value); - } - NativeBigInt.prototype.plus = NativeBigInt.prototype.add; - - function subtract(a, b) { // assumes a and b are arrays with a >= b - var a_l = a.length, - b_l = b.length, - r = new Array(a_l), - borrow = 0, - base = BASE, - i, difference; - for (i = 0; i < b_l; i++) { - difference = a[i] - borrow - b[i]; - if (difference < 0) { - difference += base; - borrow = 1; - } else borrow = 0; - r[i] = difference; - } - for (i = b_l; i < a_l; i++) { - difference = a[i] - borrow; - if (difference < 0) difference += base; - else { - r[i++] = difference; - break; - } - r[i] = difference; - } - for (; i < a_l; i++) { - r[i] = a[i]; - } - trim(r); - return r; - } - - function subtractAny(a, b, sign) { - var value; - if (compareAbs(a, b) >= 0) { - value = subtract(a, b); - } else { - value = subtract(b, a); - sign = !sign; - } - value = arrayToSmall(value); - if (typeof value === "number") { - if (sign) value = -value; - return new SmallInteger(value); - } - return new BigInteger(value, sign); - } - - function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT - var l = a.length, - r = new Array(l), - carry = -b, - base = BASE, - i, difference; - for (i = 0; i < l; i++) { - difference = a[i] + carry; - carry = Math.floor(difference / base); - difference %= base; - r[i] = difference < 0 ? difference + base : difference; - } - r = arrayToSmall(r); - if (typeof r === "number") { - if (sign) r = -r; - return new SmallInteger(r); - } return new BigInteger(r, sign); - } - - BigInteger.prototype.subtract = function (v) { - var n = parseValue(v); - if (this.sign !== n.sign) { - return this.add(n.negate()); - } - var a = this.value, b = n.value; - if (n.isSmall) - return subtractSmall(a, Math.abs(b), this.sign); - return subtractAny(a, b, this.sign); - }; - BigInteger.prototype.minus = BigInteger.prototype.subtract; - - SmallInteger.prototype.subtract = function (v) { - var n = parseValue(v); - var a = this.value; - if (a < 0 !== n.sign) { - return this.add(n.negate()); - } - var b = n.value; - if (n.isSmall) { - return new SmallInteger(a - b); - } - return subtractSmall(b, Math.abs(a), a >= 0); - }; - SmallInteger.prototype.minus = SmallInteger.prototype.subtract; - - NativeBigInt.prototype.subtract = function (v) { - return new NativeBigInt(this.value - parseValue(v).value); - } - NativeBigInt.prototype.minus = NativeBigInt.prototype.subtract; - - BigInteger.prototype.negate = function () { - return new BigInteger(this.value, !this.sign); - }; - SmallInteger.prototype.negate = function () { - var sign = this.sign; - var small = new SmallInteger(-this.value); - small.sign = !sign; - return small; - }; - NativeBigInt.prototype.negate = function () { - return new NativeBigInt(-this.value); - } - - BigInteger.prototype.abs = function () { - return new BigInteger(this.value, false); - }; - SmallInteger.prototype.abs = function () { - return new SmallInteger(Math.abs(this.value)); - }; - NativeBigInt.prototype.abs = function () { - return new NativeBigInt(this.value >= 0 ? this.value : -this.value); - } - - - function multiplyLong(a, b) { - var a_l = a.length, - b_l = b.length, - l = a_l + b_l, - r = createArray(l), - base = BASE, - product, carry, i, a_i, b_j; - for (i = 0; i < a_l; ++i) { - a_i = a[i]; - for (var j = 0; j < b_l; ++j) { - b_j = b[j]; - product = a_i * b_j + r[i + j]; - carry = Math.floor(product / base); - r[i + j] = product - carry * base; - r[i + j + 1] += carry; - } - } - trim(r); - return r; - } - - function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE - var l = a.length, - r = new Array(l), - base = BASE, - carry = 0, - product, i; - for (i = 0; i < l; i++) { - product = a[i] * b + carry; - carry = Math.floor(product / base); - r[i] = product - carry * base; - } - while (carry > 0) { - r[i++] = carry % base; - carry = Math.floor(carry / base); - } - return r; - } - - function shiftLeft(x, n) { - var r = []; - while (n-- > 0) r.push(0); - return r.concat(x); - } - - function multiplyKaratsuba(x, y) { - var n = Math.max(x.length, y.length); - - if (n <= 30) return multiplyLong(x, y); - n = Math.ceil(n / 2); - - var b = x.slice(n), - a = x.slice(0, n), - d = y.slice(n), - c = y.slice(0, n); - - var ac = multiplyKaratsuba(a, c), - bd = multiplyKaratsuba(b, d), - abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d)); - - var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n)); - trim(product); - return product; - } - - // The following function is derived from a surface fit of a graph plotting the performance difference - // between long multiplication and karatsuba multiplication versus the lengths of the two arrays. - function useKaratsuba(l1, l2) { - return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0; - } - - BigInteger.prototype.multiply = function (v) { - var n = parseValue(v), - a = this.value, b = n.value, - sign = this.sign !== n.sign, - abs; - if (n.isSmall) { - if (b === 0) return Integer[0]; - if (b === 1) return this; - if (b === -1) return this.negate(); - abs = Math.abs(b); - if (abs < BASE) { - return new BigInteger(multiplySmall(a, abs), sign); - } - b = smallToArray(abs); - } - if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes - return new BigInteger(multiplyKaratsuba(a, b), sign); - return new BigInteger(multiplyLong(a, b), sign); - }; - - BigInteger.prototype.times = BigInteger.prototype.multiply; - - function multiplySmallAndArray(a, b, sign) { // a >= 0 - if (a < BASE) { - return new BigInteger(multiplySmall(b, a), sign); - } - return new BigInteger(multiplyLong(b, smallToArray(a)), sign); - } - SmallInteger.prototype._multiplyBySmall = function (a) { - if (isPrecise(a.value * this.value)) { - return new SmallInteger(a.value * this.value); - } - return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign); - }; - BigInteger.prototype._multiplyBySmall = function (a) { - if (a.value === 0) return Integer[0]; - if (a.value === 1) return this; - if (a.value === -1) return this.negate(); - return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign); - }; - SmallInteger.prototype.multiply = function (v) { - return parseValue(v)._multiplyBySmall(this); - }; - SmallInteger.prototype.times = SmallInteger.prototype.multiply; - - NativeBigInt.prototype.multiply = function (v) { - return new NativeBigInt(this.value * parseValue(v).value); - } - NativeBigInt.prototype.times = NativeBigInt.prototype.multiply; - - function square(a) { - //console.assert(2 * BASE * BASE < MAX_INT); - var l = a.length, - r = createArray(l + l), - base = BASE, - product, carry, i, a_i, a_j; - for (i = 0; i < l; i++) { - a_i = a[i]; - carry = 0 - a_i * a_i; - for (var j = i; j < l; j++) { - a_j = a[j]; - product = 2 * (a_i * a_j) + r[i + j] + carry; - carry = Math.floor(product / base); - r[i + j] = product - carry * base; - } - r[i + l] = carry; - } - trim(r); - return r; - } - - BigInteger.prototype.square = function () { - return new BigInteger(square(this.value), false); - }; - - SmallInteger.prototype.square = function () { - var value = this.value * this.value; - if (isPrecise(value)) return new SmallInteger(value); - return new BigInteger(square(smallToArray(Math.abs(this.value))), false); - }; - - NativeBigInt.prototype.square = function (v) { - return new NativeBigInt(this.value * this.value); - } - - function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes. - var a_l = a.length, - b_l = b.length, - base = BASE, - result = createArray(b.length), - divisorMostSignificantDigit = b[b_l - 1], - // normalization - lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)), - remainder = multiplySmall(a, lambda), - divisor = multiplySmall(b, lambda), - quotientDigit, shift, carry, borrow, i, l, q; - if (remainder.length <= a_l) remainder.push(0); - divisor.push(0); - divisorMostSignificantDigit = divisor[b_l - 1]; - for (shift = a_l - b_l; shift >= 0; shift--) { - quotientDigit = base - 1; - if (remainder[shift + b_l] !== divisorMostSignificantDigit) { - quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit); - } - // quotientDigit <= base - 1 - carry = 0; - borrow = 0; - l = divisor.length; - for (i = 0; i < l; i++) { - carry += quotientDigit * divisor[i]; - q = Math.floor(carry / base); - borrow += remainder[shift + i] - (carry - q * base); - carry = q; - if (borrow < 0) { - remainder[shift + i] = borrow + base; - borrow = -1; - } else { - remainder[shift + i] = borrow; - borrow = 0; - } - } - while (borrow !== 0) { - quotientDigit -= 1; - carry = 0; - for (i = 0; i < l; i++) { - carry += remainder[shift + i] - base + divisor[i]; - if (carry < 0) { - remainder[shift + i] = carry + base; - carry = 0; - } else { - remainder[shift + i] = carry; - carry = 1; - } - } - borrow += carry; - } - result[shift] = quotientDigit; - } - // denormalization - remainder = divModSmall(remainder, lambda)[0]; - return [arrayToSmall(result), arrayToSmall(remainder)]; - } - - function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/ - // Performs faster than divMod1 on larger input sizes. - var a_l = a.length, - b_l = b.length, - result = [], - part = [], - base = BASE, - guess, xlen, highx, highy, check; - while (a_l) { - part.unshift(a[--a_l]); - trim(part); - if (compareAbs(part, b) < 0) { - result.push(0); - continue; - } - xlen = part.length; - highx = part[xlen - 1] * base + part[xlen - 2]; - highy = b[b_l - 1] * base + b[b_l - 2]; - if (xlen > b_l) { - highx = (highx + 1) * base; - } - guess = Math.ceil(highx / highy); - do { - check = multiplySmall(b, guess); - if (compareAbs(check, part) <= 0) break; - guess--; - } while (guess); - result.push(guess); - part = subtract(part, check); - } - result.reverse(); - return [arrayToSmall(result), arrayToSmall(part)]; - } - - function divModSmall(value, lambda) { - var length = value.length, - quotient = createArray(length), - base = BASE, - i, q, remainder, divisor; - remainder = 0; - for (i = length - 1; i >= 0; --i) { - divisor = remainder * base + value[i]; - q = truncate(divisor / lambda); - remainder = divisor - q * lambda; - quotient[i] = q | 0; - } - return [quotient, remainder | 0]; - } - - function divModAny(self, v) { - var value, n = parseValue(v); - if (supportsNativeBigInt) { - return [new NativeBigInt(self.value / n.value), new NativeBigInt(self.value % n.value)]; - } - var a = self.value, b = n.value; - var quotient; - if (b === 0) throw new Error("Cannot divide by zero"); - if (self.isSmall) { - if (n.isSmall) { - return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)]; - } - return [Integer[0], self]; - } - if (n.isSmall) { - if (b === 1) return [self, Integer[0]]; - if (b == -1) return [self.negate(), Integer[0]]; - var abs = Math.abs(b); - if (abs < BASE) { - value = divModSmall(a, abs); - quotient = arrayToSmall(value[0]); - var remainder = value[1]; - if (self.sign) remainder = -remainder; - if (typeof quotient === "number") { - if (self.sign !== n.sign) quotient = -quotient; - return [new SmallInteger(quotient), new SmallInteger(remainder)]; - } - return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)]; - } - b = smallToArray(abs); - } - var comparison = compareAbs(a, b); - if (comparison === -1) return [Integer[0], self]; - if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]]; - - // divMod1 is faster on smaller input sizes - if (a.length + b.length <= 200) - value = divMod1(a, b); - else value = divMod2(a, b); - - quotient = value[0]; - var qSign = self.sign !== n.sign, - mod = value[1], - mSign = self.sign; - if (typeof quotient === "number") { - if (qSign) quotient = -quotient; - quotient = new SmallInteger(quotient); - } else quotient = new BigInteger(quotient, qSign); - if (typeof mod === "number") { - if (mSign) mod = -mod; - mod = new SmallInteger(mod); - } else mod = new BigInteger(mod, mSign); - return [quotient, mod]; - } - - BigInteger.prototype.divmod = function (v) { - var result = divModAny(this, v); - return { - quotient: result[0], - remainder: result[1] - }; - }; - NativeBigInt.prototype.divmod = SmallInteger.prototype.divmod = BigInteger.prototype.divmod; - - - BigInteger.prototype.divide = function (v) { - return divModAny(this, v)[0]; - }; - NativeBigInt.prototype.over = NativeBigInt.prototype.divide = function (v) { - return new NativeBigInt(this.value / parseValue(v).value); - }; - SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide; - - BigInteger.prototype.mod = function (v) { - return divModAny(this, v)[1]; - }; - NativeBigInt.prototype.mod = NativeBigInt.prototype.remainder = function (v) { - return new NativeBigInt(this.value % parseValue(v).value); - }; - SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod; - - BigInteger.prototype.pow = function (v) { - var n = parseValue(v), - a = this.value, - b = n.value, - value, x, y; - if (b === 0) return Integer[1]; - if (a === 0) return Integer[0]; - if (a === 1) return Integer[1]; - if (a === -1) return n.isEven() ? Integer[1] : Integer[-1]; - if (n.sign) { - return Integer[0]; - } - if (!n.isSmall) throw new Error("The exponent " + n.toString() + " is too large."); - if (this.isSmall) { - if (isPrecise(value = Math.pow(a, b))) - return new SmallInteger(truncate(value)); - } - x = this; - y = Integer[1]; - while (true) { - if (b & 1 === 1) { - y = y.times(x); - --b; - } - if (b === 0) break; - b /= 2; - x = x.square(); - } - return y; - }; - SmallInteger.prototype.pow = BigInteger.prototype.pow; - - NativeBigInt.prototype.pow = function (v) { - var n = parseValue(v); - var a = this.value, b = n.value; - var _0 = BigInt(0), _1 = BigInt(1), _2 = BigInt(2); - if (b === _0) return Integer[1]; - if (a === _0) return Integer[0]; - if (a === _1) return Integer[1]; - if (a === BigInt(-1)) return n.isEven() ? Integer[1] : Integer[-1]; - if (n.isNegative()) return new NativeBigInt(_0); - var x = this; - var y = Integer[1]; - while (true) { - if ((b & _1) === _1) { - y = y.times(x); - --b; - } - if (b === _0) break; - b /= _2; - x = x.square(); - } - return y; - } - - BigInteger.prototype.modPow = function (exp, mod) { - exp = parseValue(exp); - mod = parseValue(mod); - if (mod.isZero()) throw new Error("Cannot take modPow with modulus 0"); - var r = Integer[1], - base = this.mod(mod); - if (exp.isNegative()) { - exp = exp.multiply(Integer[-1]); - base = base.modInv(mod); - } - while (exp.isPositive()) { - if (base.isZero()) return Integer[0]; - if (exp.isOdd()) r = r.multiply(base).mod(mod); - exp = exp.divide(2); - base = base.square().mod(mod); - } - return r; - }; - NativeBigInt.prototype.modPow = SmallInteger.prototype.modPow = BigInteger.prototype.modPow; - - function compareAbs(a, b) { - if (a.length !== b.length) { - return a.length > b.length ? 1 : -1; - } - for (var i = a.length - 1; i >= 0; i--) { - if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1; - } - return 0; - } - - BigInteger.prototype.compareAbs = function (v) { - var n = parseValue(v), - a = this.value, - b = n.value; - if (n.isSmall) return 1; - return compareAbs(a, b); - }; - SmallInteger.prototype.compareAbs = function (v) { - var n = parseValue(v), - a = Math.abs(this.value), - b = n.value; - if (n.isSmall) { - b = Math.abs(b); - return a === b ? 0 : a > b ? 1 : -1; - } - return -1; - }; - NativeBigInt.prototype.compareAbs = function (v) { - var a = this.value; - var b = parseValue(v).value; - a = a >= 0 ? a : -a; - b = b >= 0 ? b : -b; - return a === b ? 0 : a > b ? 1 : -1; - } - - BigInteger.prototype.compare = function (v) { - // See discussion about comparison with Infinity: - // https://github.com/peterolson/BigInteger.js/issues/61 - if (v === Infinity) { - return -1; - } - if (v === -Infinity) { - return 1; - } - - var n = parseValue(v), - a = this.value, - b = n.value; - if (this.sign !== n.sign) { - return n.sign ? 1 : -1; - } - if (n.isSmall) { - return this.sign ? -1 : 1; - } - return compareAbs(a, b) * (this.sign ? -1 : 1); - }; - BigInteger.prototype.compareTo = BigInteger.prototype.compare; - - SmallInteger.prototype.compare = function (v) { - if (v === Infinity) { - return -1; - } - if (v === -Infinity) { - return 1; - } - - var n = parseValue(v), - a = this.value, - b = n.value; - if (n.isSmall) { - return a == b ? 0 : a > b ? 1 : -1; - } - if (a < 0 !== n.sign) { - return a < 0 ? -1 : 1; - } - return a < 0 ? 1 : -1; - }; - SmallInteger.prototype.compareTo = SmallInteger.prototype.compare; - - NativeBigInt.prototype.compare = function (v) { - if (v === Infinity) { - return -1; - } - if (v === -Infinity) { - return 1; - } - var a = this.value; - var b = parseValue(v).value; - return a === b ? 0 : a > b ? 1 : -1; - } - NativeBigInt.prototype.compareTo = NativeBigInt.prototype.compare; - - BigInteger.prototype.equals = function (v) { - return this.compare(v) === 0; - }; - NativeBigInt.prototype.eq = NativeBigInt.prototype.equals = SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals; - - BigInteger.prototype.notEquals = function (v) { - return this.compare(v) !== 0; - }; - NativeBigInt.prototype.neq = NativeBigInt.prototype.notEquals = SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals; - - BigInteger.prototype.greater = function (v) { - return this.compare(v) > 0; - }; - NativeBigInt.prototype.gt = NativeBigInt.prototype.greater = SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater; - - BigInteger.prototype.lesser = function (v) { - return this.compare(v) < 0; - }; - NativeBigInt.prototype.lt = NativeBigInt.prototype.lesser = SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser; - - BigInteger.prototype.greaterOrEquals = function (v) { - return this.compare(v) >= 0; - }; - NativeBigInt.prototype.geq = NativeBigInt.prototype.greaterOrEquals = SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals; - - BigInteger.prototype.lesserOrEquals = function (v) { - return this.compare(v) <= 0; - }; - NativeBigInt.prototype.leq = NativeBigInt.prototype.lesserOrEquals = SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals; - - BigInteger.prototype.isEven = function () { - return (this.value[0] & 1) === 0; - }; - SmallInteger.prototype.isEven = function () { - return (this.value & 1) === 0; - }; - NativeBigInt.prototype.isEven = function () { - return (this.value & BigInt(1)) === BigInt(0); - } - - BigInteger.prototype.isOdd = function () { - return (this.value[0] & 1) === 1; - }; - SmallInteger.prototype.isOdd = function () { - return (this.value & 1) === 1; - }; - NativeBigInt.prototype.isOdd = function () { - return (this.value & BigInt(1)) === BigInt(1); - } - - BigInteger.prototype.isPositive = function () { - return !this.sign; - }; - SmallInteger.prototype.isPositive = function () { - return this.value > 0; - }; - NativeBigInt.prototype.isPositive = SmallInteger.prototype.isPositive; - - BigInteger.prototype.isNegative = function () { - return this.sign; - }; - SmallInteger.prototype.isNegative = function () { - return this.value < 0; - }; - NativeBigInt.prototype.isNegative = SmallInteger.prototype.isNegative; - - BigInteger.prototype.isUnit = function () { - return false; - }; - SmallInteger.prototype.isUnit = function () { - return Math.abs(this.value) === 1; - }; - NativeBigInt.prototype.isUnit = function () { - return this.abs().value === BigInt(1); - } - - BigInteger.prototype.isZero = function () { - return false; - }; - SmallInteger.prototype.isZero = function () { - return this.value === 0; - }; - NativeBigInt.prototype.isZero = function () { - return this.value === BigInt(0); - } - - BigInteger.prototype.isDivisibleBy = function (v) { - var n = parseValue(v); - if (n.isZero()) return false; - if (n.isUnit()) return true; - if (n.compareAbs(2) === 0) return this.isEven(); - return this.mod(n).isZero(); - }; - NativeBigInt.prototype.isDivisibleBy = SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy; - - function isBasicPrime(v) { - var n = v.abs(); - if (n.isUnit()) return false; - if (n.equals(2) || n.equals(3) || n.equals(5)) return true; - if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false; - if (n.lesser(49)) return true; - // we don't know if it's prime: let the other functions figure it out - } - - function millerRabinTest(n, a) { - var nPrev = n.prev(), - b = nPrev, - r = 0, - d, t, i, x; - while (b.isEven()) b = b.divide(2), r++; - next: for (i = 0; i < a.length; i++) { - if (n.lesser(a[i])) continue; - x = bigInt(a[i]).modPow(b, n); - if (x.isUnit() || x.equals(nPrev)) continue; - for (d = r - 1; d != 0; d--) { - x = x.square().mod(n); - if (x.isUnit()) return false; - if (x.equals(nPrev)) continue next; - } - return false; - } - return true; - } - - // Set "strict" to true to force GRH-supported lower bound of 2*log(N)^2 - BigInteger.prototype.isPrime = function (strict) { - var isPrime = isBasicPrime(this); - if (isPrime !== undefined) return isPrime; - var n = this.abs(); - var bits = n.bitLength(); - if (bits <= 64) - return millerRabinTest(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]); - var logN = Math.log(2) * bits.toJSNumber(); - var t = Math.ceil((strict === true) ? (2 * Math.pow(logN, 2)) : logN); - for (var a = [], i = 0; i < t; i++) { - a.push(bigInt(i + 2)); - } - return millerRabinTest(n, a); - }; - NativeBigInt.prototype.isPrime = SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime; - - BigInteger.prototype.isProbablePrime = function (iterations, rng) { - var isPrime = isBasicPrime(this); - if (isPrime !== undefined) return isPrime; - var n = this.abs(); - var t = iterations === undefined ? 5 : iterations; - for (var a = [], i = 0; i < t; i++) { - a.push(bigInt.randBetween(2, n.minus(2), rng)); - } - return millerRabinTest(n, a); - }; - NativeBigInt.prototype.isProbablePrime = SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime; - - BigInteger.prototype.modInv = function (n) { - var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR; - while (!newR.isZero()) { - q = r.divide(newR); - lastT = t; - lastR = r; - t = newT; - r = newR; - newT = lastT.subtract(q.multiply(newT)); - newR = lastR.subtract(q.multiply(newR)); - } - if (!r.isUnit()) throw new Error(this.toString() + " and " + n.toString() + " are not co-prime"); - if (t.compare(0) === -1) { - t = t.add(n); - } - if (this.isNegative()) { - return t.negate(); - } - return t; - }; - - NativeBigInt.prototype.modInv = SmallInteger.prototype.modInv = BigInteger.prototype.modInv; - - BigInteger.prototype.next = function () { - var value = this.value; - if (this.sign) { - return subtractSmall(value, 1, this.sign); - } - return new BigInteger(addSmall(value, 1), this.sign); - }; - SmallInteger.prototype.next = function () { - var value = this.value; - if (value + 1 < MAX_INT) return new SmallInteger(value + 1); - return new BigInteger(MAX_INT_ARR, false); - }; - NativeBigInt.prototype.next = function () { - return new NativeBigInt(this.value + BigInt(1)); - } - - BigInteger.prototype.prev = function () { - var value = this.value; - if (this.sign) { - return new BigInteger(addSmall(value, 1), true); - } - return subtractSmall(value, 1, this.sign); - }; - SmallInteger.prototype.prev = function () { - var value = this.value; - if (value - 1 > -MAX_INT) return new SmallInteger(value - 1); - return new BigInteger(MAX_INT_ARR, true); - }; - NativeBigInt.prototype.prev = function () { - return new NativeBigInt(this.value - BigInt(1)); - } - - var powersOfTwo = [1]; - while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]); - var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1]; - - function shift_isSmall(n) { - return Math.abs(n) <= BASE; - } - - BigInteger.prototype.shiftLeft = function (v) { - var n = parseValue(v).toJSNumber(); - if (!shift_isSmall(n)) { - throw new Error(String(n) + " is too large for shifting."); - } - if (n < 0) return this.shiftRight(-n); - var result = this; - if (result.isZero()) return result; - while (n >= powers2Length) { - result = result.multiply(highestPower2); - n -= powers2Length - 1; - } - return result.multiply(powersOfTwo[n]); - }; - NativeBigInt.prototype.shiftLeft = SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft; - - BigInteger.prototype.shiftRight = function (v) { - var remQuo; - var n = parseValue(v).toJSNumber(); - if (!shift_isSmall(n)) { - throw new Error(String(n) + " is too large for shifting."); - } - if (n < 0) return this.shiftLeft(-n); - var result = this; - while (n >= powers2Length) { - if (result.isZero() || (result.isNegative() && result.isUnit())) return result; - remQuo = divModAny(result, highestPower2); - result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; - n -= powers2Length - 1; - } - remQuo = divModAny(result, powersOfTwo[n]); - return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; - }; - NativeBigInt.prototype.shiftRight = SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight; - - function bitwise(x, y, fn) { - y = parseValue(y); - var xSign = x.isNegative(), ySign = y.isNegative(); - var xRem = xSign ? x.not() : x, - yRem = ySign ? y.not() : y; - var xDigit = 0, yDigit = 0; - var xDivMod = null, yDivMod = null; - var result = []; - while (!xRem.isZero() || !yRem.isZero()) { - xDivMod = divModAny(xRem, highestPower2); - xDigit = xDivMod[1].toJSNumber(); - if (xSign) { - xDigit = highestPower2 - 1 - xDigit; // two's complement for negative numbers - } - - yDivMod = divModAny(yRem, highestPower2); - yDigit = yDivMod[1].toJSNumber(); - if (ySign) { - yDigit = highestPower2 - 1 - yDigit; // two's complement for negative numbers - } - - xRem = xDivMod[0]; - yRem = yDivMod[0]; - result.push(fn(xDigit, yDigit)); - } - var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0); - for (var i = result.length - 1; i >= 0; i -= 1) { - sum = sum.multiply(highestPower2).add(bigInt(result[i])); - } - return sum; - } - - BigInteger.prototype.not = function () { - return this.negate().prev(); - }; - NativeBigInt.prototype.not = SmallInteger.prototype.not = BigInteger.prototype.not; - - BigInteger.prototype.and = function (n) { - return bitwise(this, n, function (a, b) { return a & b; }); - }; - NativeBigInt.prototype.and = SmallInteger.prototype.and = BigInteger.prototype.and; - - BigInteger.prototype.or = function (n) { - return bitwise(this, n, function (a, b) { return a | b; }); - }; - NativeBigInt.prototype.or = SmallInteger.prototype.or = BigInteger.prototype.or; - - BigInteger.prototype.xor = function (n) { - return bitwise(this, n, function (a, b) { return a ^ b; }); - }; - NativeBigInt.prototype.xor = SmallInteger.prototype.xor = BigInteger.prototype.xor; - - var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I; - function roughLOB(n) { // get lowestOneBit (rough) - // SmallInteger: return Min(lowestOneBit(n), 1 << 30) - // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7] - var v = n.value, - x = typeof v === "number" ? v | LOBMASK_I : - typeof v === "bigint" ? v | BigInt(LOBMASK_I) : - v[0] + v[1] * BASE | LOBMASK_BI; - return x & -x; - } - - function integerLogarithm(value, base) { - if (base.compareTo(value) <= 0) { - var tmp = integerLogarithm(value, base.square(base)); - var p = tmp.p; - var e = tmp.e; - var t = p.multiply(base); - return t.compareTo(value) <= 0 ? { p: t, e: e * 2 + 1 } : { p: p, e: e * 2 }; - } - return { p: bigInt(1), e: 0 }; - } - - BigInteger.prototype.bitLength = function () { - var n = this; - if (n.compareTo(bigInt(0)) < 0) { - n = n.negate().subtract(bigInt(1)); - } - if (n.compareTo(bigInt(0)) === 0) { - return bigInt(0); - } - return bigInt(integerLogarithm(n, bigInt(2)).e).add(bigInt(1)); - } - NativeBigInt.prototype.bitLength = SmallInteger.prototype.bitLength = BigInteger.prototype.bitLength; - - function max(a, b) { - a = parseValue(a); - b = parseValue(b); - return a.greater(b) ? a : b; - } - function min(a, b) { - a = parseValue(a); - b = parseValue(b); - return a.lesser(b) ? a : b; - } - function gcd(a, b) { - a = parseValue(a).abs(); - b = parseValue(b).abs(); - if (a.equals(b)) return a; - if (a.isZero()) return b; - if (b.isZero()) return a; - var c = Integer[1], d, t; - while (a.isEven() && b.isEven()) { - d = min(roughLOB(a), roughLOB(b)); - a = a.divide(d); - b = b.divide(d); - c = c.multiply(d); - } - while (a.isEven()) { - a = a.divide(roughLOB(a)); - } - do { - while (b.isEven()) { - b = b.divide(roughLOB(b)); - } - if (a.greater(b)) { - t = b; b = a; a = t; - } - b = b.subtract(a); - } while (!b.isZero()); - return c.isUnit() ? a : a.multiply(c); - } - function lcm(a, b) { - a = parseValue(a).abs(); - b = parseValue(b).abs(); - return a.divide(gcd(a, b)).multiply(b); - } - function randBetween(a, b, rng) { - a = parseValue(a); - b = parseValue(b); - var usedRNG = rng || Math.random; - var low = min(a, b), high = max(a, b); - var range = high.subtract(low).add(1); - if (range.isSmall) return low.add(Math.floor(usedRNG() * range)); - var digits = toBase(range, BASE).value; - var result = [], restricted = true; - for (var i = 0; i < digits.length; i++) { - var top = restricted ? digits[i] + (i + 1 < digits.length ? digits[i + 1] / BASE : 0) : BASE; - var digit = truncate(usedRNG() * top); - result.push(digit); - if (digit < digits[i]) restricted = false; - } - return low.add(Integer.fromArray(result, BASE, false)); - } - - var parseBase = function (text, base, alphabet, caseSensitive) { - alphabet = alphabet || DEFAULT_ALPHABET; - text = String(text); - if (!caseSensitive) { - text = text.toLowerCase(); - alphabet = alphabet.toLowerCase(); - } - var length = text.length; - var i; - var absBase = Math.abs(base); - var alphabetValues = {}; - for (i = 0; i < alphabet.length; i++) { - alphabetValues[alphabet[i]] = i; - } - for (i = 0; i < length; i++) { - var c = text[i]; - if (c === "-") continue; - if (c in alphabetValues) { - if (alphabetValues[c] >= absBase) { - if (c === "1" && absBase === 1) continue; - throw new Error(c + " is not a valid digit in base " + base + "."); - } - } - } - base = parseValue(base); - var digits = []; - var isNegative = text[0] === "-"; - for (i = isNegative ? 1 : 0; i < text.length; i++) { - var c = text[i]; - if (c in alphabetValues) digits.push(parseValue(alphabetValues[c])); - else if (c === "<") { - var start = i; - do { i++; } while (text[i] !== ">" && i < text.length); - digits.push(parseValue(text.slice(start + 1, i))); - } - else throw new Error(c + " is not a valid character"); - } - return parseBaseFromArray(digits, base, isNegative); - }; - - function parseBaseFromArray(digits, base, isNegative) { - var val = Integer[0], pow = Integer[1], i; - for (i = digits.length - 1; i >= 0; i--) { - val = val.add(digits[i].times(pow)); - pow = pow.times(base); - } - return isNegative ? val.negate() : val; - } - - function stringify(digit, alphabet) { - alphabet = alphabet || DEFAULT_ALPHABET; - if (digit < alphabet.length) { - return alphabet[digit]; - } - return "<" + digit + ">"; - } - - function toBase(n, base) { - base = bigInt(base); - if (base.isZero()) { - if (n.isZero()) return { value: [0], isNegative: false }; - throw new Error("Cannot convert nonzero numbers to base 0."); - } - if (base.equals(-1)) { - if (n.isZero()) return { value: [0], isNegative: false }; - if (n.isNegative()) - return { - value: [].concat.apply([], Array.apply(null, Array(-n.toJSNumber())) - .map(Array.prototype.valueOf, [1, 0]) - ), - isNegative: false - }; - - var arr = Array.apply(null, Array(n.toJSNumber() - 1)) - .map(Array.prototype.valueOf, [0, 1]); - arr.unshift([1]); - return { - value: [].concat.apply([], arr), - isNegative: false - }; - } - - var neg = false; - if (n.isNegative() && base.isPositive()) { - neg = true; - n = n.abs(); - } - if (base.isUnit()) { - if (n.isZero()) return { value: [0], isNegative: false }; - - return { - value: Array.apply(null, Array(n.toJSNumber())) - .map(Number.prototype.valueOf, 1), - isNegative: neg - }; - } - var out = []; - var left = n, divmod; - while (left.isNegative() || left.compareAbs(base) >= 0) { - divmod = left.divmod(base); - left = divmod.quotient; - var digit = divmod.remainder; - if (digit.isNegative()) { - digit = base.minus(digit).abs(); - left = left.next(); - } - out.push(digit.toJSNumber()); - } - out.push(left.toJSNumber()); - return { value: out.reverse(), isNegative: neg }; - } - - function toBaseString(n, base, alphabet) { - var arr = toBase(n, base); - return (arr.isNegative ? "-" : "") + arr.value.map(function (x) { - return stringify(x, alphabet); - }).join(''); - } - - BigInteger.prototype.toArray = function (radix) { - return toBase(this, radix); - }; - - SmallInteger.prototype.toArray = function (radix) { - return toBase(this, radix); - }; - - NativeBigInt.prototype.toArray = function (radix) { - return toBase(this, radix); - }; - - BigInteger.prototype.toString = function (radix, alphabet) { - if (radix === undefined) radix = 10; - if (radix !== 10) return toBaseString(this, radix, alphabet); - var v = this.value, l = v.length, str = String(v[--l]), zeros = "0000000", digit; - while (--l >= 0) { - digit = String(v[l]); - str += zeros.slice(digit.length) + digit; - } - var sign = this.sign ? "-" : ""; - return sign + str; - }; - - SmallInteger.prototype.toString = function (radix, alphabet) { - if (radix === undefined) radix = 10; - if (radix != 10) return toBaseString(this, radix, alphabet); - return String(this.value); - }; - - NativeBigInt.prototype.toString = SmallInteger.prototype.toString; - - NativeBigInt.prototype.toJSON = BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function () { return this.toString(); } - - BigInteger.prototype.valueOf = function () { - return parseInt(this.toString(), 10); - }; - BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf; - - SmallInteger.prototype.valueOf = function () { - return this.value; - }; - SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf; - NativeBigInt.prototype.valueOf = NativeBigInt.prototype.toJSNumber = function () { - return parseInt(this.toString(), 10); - } - - function parseStringValue(v) { - if (isPrecise(+v)) { - var x = +v; - if (x === truncate(x)) - return supportsNativeBigInt ? new NativeBigInt(BigInt(x)) : new SmallInteger(x); - throw new Error("Invalid integer: " + v); - } - var sign = v[0] === "-"; - if (sign) v = v.slice(1); - var split = v.split(/e/i); - if (split.length > 2) throw new Error("Invalid integer: " + split.join("e")); - if (split.length === 2) { - var exp = split[1]; - if (exp[0] === "+") exp = exp.slice(1); - exp = +exp; - if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error("Invalid integer: " + exp + " is not a valid exponent."); - var text = split[0]; - var decimalPlace = text.indexOf("."); - if (decimalPlace >= 0) { - exp -= text.length - decimalPlace - 1; - text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1); - } - if (exp < 0) throw new Error("Cannot include negative exponent part for integers"); - text += (new Array(exp + 1)).join("0"); - v = text; - } - var isValid = /^([0-9][0-9]*)$/.test(v); - if (!isValid) throw new Error("Invalid integer: " + v); - if (supportsNativeBigInt) { - return new NativeBigInt(BigInt(sign ? "-" + v : v)); - } - var r = [], max = v.length, l = LOG_BASE, min = max - l; - while (max > 0) { - r.push(+v.slice(min, max)); - min -= l; - if (min < 0) min = 0; - max -= l; - } - trim(r); - return new BigInteger(r, sign); - } - - function parseNumberValue(v) { - if (supportsNativeBigInt) { - return new NativeBigInt(BigInt(v)); - } - if (isPrecise(v)) { - if (v !== truncate(v)) throw new Error(v + " is not an integer."); - return new SmallInteger(v); - } - return parseStringValue(v.toString()); - } - - function parseValue(v) { - if (typeof v === "number") { - return parseNumberValue(v); - } - if (typeof v === "string") { - return parseStringValue(v); - } - if (typeof v === "bigint") { - return new NativeBigInt(v); - } - return v; - } - // Pre-define numbers in range [-999,999] - for (var i = 0; i < 1000; i++) { - Integer[i] = parseValue(i); - if (i > 0) Integer[-i] = parseValue(-i); - } - // Backwards compatibility - Integer.one = Integer[1]; - Integer.zero = Integer[0]; - Integer.minusOne = Integer[-1]; - Integer.max = max; - Integer.min = min; - Integer.gcd = gcd; - Integer.lcm = lcm; - Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger || x instanceof NativeBigInt; }; - Integer.randBetween = randBetween; - - Integer.fromArray = function (digits, base, isNegative) { - return parseBaseFromArray(digits.map(parseValue), parseValue(base || 10), isNegative); - }; - - return Integer; -})(); - -// Node.js check -if ( true && module.hasOwnProperty("exports")) { - module.exports = bigInt; -} - -//amd check -if (typeof define === "function" && define.amd) { - define( function () { - return bigInt; - }); -} - - -/***/ }), - -/***/ 6474: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 4994: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -var Chainsaw = __nccwpck_require__(6533); -var EventEmitter = (__nccwpck_require__(2361).EventEmitter); -var Buffers = __nccwpck_require__(1590); -var Vars = __nccwpck_require__(3755); -var Stream = (__nccwpck_require__(2781).Stream); -exports = module.exports = function (bufOrEm, eventName) { - if (Buffer.isBuffer(bufOrEm)) { - return exports.parse(bufOrEm); - } - - var s = exports.stream(); - if (bufOrEm && bufOrEm.pipe) { - bufOrEm.pipe(s); - } - else if (bufOrEm) { - bufOrEm.on(eventName || 'data', function (buf) { - s.write(buf); - }); - - bufOrEm.on('end', function () { - s.end(); - }); - } - return s; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; }; - -exports.stream = function (input) { - if (input) return exports.apply(null, arguments); - - var pending = null; - function getBytes (bytes, cb, skip) { - pending = { - bytes : bytes, - skip : skip, - cb : function (buf) { - pending = null; - cb(buf); - }, - }; - dispatch(); - } - - var offset = null; - function dispatch () { - if (!pending) { - if (caughtEnd) done = true; +var __awaiter = (this && this.__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(exports, "__esModule", ({ value: true })); +exports.findInPath = exports.which = exports.mkdirP = exports.rmRF = exports.mv = exports.cp = void 0; +const assert_1 = __nccwpck_require__(2613); +const path = __importStar(__nccwpck_require__(6928)); +const ioUtil = __importStar(__nccwpck_require__(5207)); +/** + * Copies a file or folder. + * Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js + * + * @param source source path + * @param dest destination path + * @param options optional. See CopyOptions. + */ +function cp(source, dest, options = {}) { + return __awaiter(this, void 0, void 0, function* () { + const { force, recursive, copySourceDirectory } = readCopyOptions(options); + const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null; + // Dest is an existing file, but not forcing + if (destStat && destStat.isFile() && !force) { return; } - if (typeof pending === 'function') { - pending(); + // If dest is an existing directory, should copy inside. + 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 { - var bytes = offset + pending.bytes; - - if (buffers.length >= bytes) { - var buf; - if (offset == null) { - buf = buffers.splice(0, bytes); - if (!pending.skip) { - buf = buf.slice(); - } + if (path.relative(source, newDest) === '') { + // a file cannot be copied to itself + throw new Error(`'${newDest}' and '${source}' are the same file`); + } + yield copyFile(source, newDest, force); + } + }); +} +exports.cp = cp; +/** + * Moves a path. + * + * @param source source path + * @param dest destination path + * @param options optional. See MoveOptions. + */ +function mv(source, dest, options = {}) { + return __awaiter(this, void 0, void 0, function* () { + if (yield ioUtil.exists(dest)) { + let destExists = true; + if (yield ioUtil.isDirectory(dest)) { + // If dest is directory copy src into 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 { - if (!pending.skip) { - buf = buffers.slice(offset, bytes); - } - offset = bytes; + throw new Error('Destination already exists'); } - - if (pending.skip) { - pending.cb(); + } + } + yield mkdirP(path.dirname(dest)); + yield ioUtil.rename(source, dest); + }); +} +exports.mv = mv; +/** + * Remove a path recursively with force + * + * @param inputPath path to remove + */ +function rmRF(inputPath) { + return __awaiter(this, void 0, void 0, function* () { + if (ioUtil.IS_WINDOWS) { + // Check for invalid characters + // https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file + if (/[*"<>|]/.test(inputPath)) { + throw new Error('File path must not contain `*`, `"`, `<`, `>` or `|` on Windows'); + } + } + try { + // note if path does not exist, error is silent + yield ioUtil.rm(inputPath, { + force: true, + maxRetries: 3, + recursive: true, + retryDelay: 300 + }); + } + catch (err) { + throw new Error(`File was unable to be removed ${err}`); + } + }); +} +exports.rmRF = rmRF; +/** + * Make a directory. Creates the full path with folders in between + * Will throw if it fails + * + * @param fsPath path to create + * @returns Promise + */ +function mkdirP(fsPath) { + return __awaiter(this, void 0, void 0, function* () { + assert_1.ok(fsPath, 'a path argument must be provided'); + yield ioUtil.mkdir(fsPath, { recursive: true }); + }); +} +exports.mkdirP = mkdirP; +/** + * Returns path of a tool had the tool actually been invoked. Resolves via paths. + * If you check and the tool does not exist, it will throw. + * + * @param tool name of the tool + * @param check whether to check if tool exists + * @returns Promise path to tool + */ +function which(tool, check) { + return __awaiter(this, void 0, void 0, function* () { + if (!tool) { + throw new Error("parameter 'tool' is required"); + } + // recursive when check=true + 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 { - pending.cb(buf); + 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; } - } - - function builder (saw) { - function next () { if (!done) saw.next() } - - var self = words(function (bytes, cb) { - return function (name) { - getBytes(bytes, function (buf) { - vars.set(name, cb(buf)); - next(); - }); - }; - }); - - self.tap = function (cb) { - saw.nest(cb, vars.store); - }; - - self.into = function (key, cb) { - if (!vars.get(key)) vars.set(key, {}); - var parent = vars; - vars = Vars(parent.get(key)); - - saw.nest(function () { - cb.apply(this, arguments); - this.tap(function () { - vars = parent; - }); - }, vars.store); - }; - - self.flush = function () { - vars.store = {}; - next(); - }; - - self.loop = function (cb) { - var end = false; - - saw.nest(false, function loop () { - this.vars = vars.store; - cb.call(this, function () { - end = true; - next(); - }, vars.store); - this.tap(function () { - if (end) saw.next() - else loop.call(this) - }.bind(this)); - }, vars.store); - }; - - self.buffer = function (name, bytes) { - if (typeof bytes === 'string') { - bytes = vars.get(bytes); + const matches = yield findInPath(tool); + if (matches && matches.length > 0) { + return matches[0]; + } + return ''; + }); +} +exports.which = which; +/** + * Returns a list of all occurrences of the given tool on the system path. + * + * @returns Promise the paths of the tool + */ +function findInPath(tool) { + return __awaiter(this, void 0, void 0, function* () { + if (!tool) { + throw new Error("parameter 'tool' is required"); + } + // build the list of extensions to try + const extensions = []; + if (ioUtil.IS_WINDOWS && process.env['PATHEXT']) { + for (const extension of process.env['PATHEXT'].split(path.delimiter)) { + if (extension) { + extensions.push(extension); + } } - - getBytes(bytes, function (buf) { - vars.set(name, buf); - next(); - }); - }; - - self.skip = function (bytes) { - if (typeof bytes === 'string') { - bytes = vars.get(bytes); + } + // if it's rooted, return it if exists. otherwise return empty. + if (ioUtil.isRooted(tool)) { + const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions); + if (filePath) { + return [filePath]; } - - getBytes(bytes, function () { - next(); - }); - }; - - self.scan = function find (name, search) { - if (typeof search === 'string') { - search = new Buffer(search); + return []; + } + // if any path separators, return empty + if (tool.includes(path.sep)) { + return []; + } + // build the list of directories + // + // Note, technically "where" checks the current directory on Windows. From a toolkit perspective, + // it feels like we should not do this. Checking the current directory seems like more of a use + // case of a shell, and the which() function exposed by the toolkit should strive for consistency + // across platforms. + const directories = []; + if (process.env.PATH) { + for (const p of process.env.PATH.split(path.delimiter)) { + if (p) { + directories.push(p); + } } - else if (!Buffer.isBuffer(search)) { - throw new Error('search must be a Buffer or a string'); + } + // find all matches + const matches = []; + for (const directory of directories) { + const filePath = yield ioUtil.tryGetExecutablePath(path.join(directory, tool), extensions); + if (filePath) { + matches.push(filePath); } - - var taken = 0; - pending = function () { - var pos = buffers.indexOf(search, offset + taken); - var i = pos-offset-taken; - if (pos !== -1) { - pending = null; - if (offset != null) { - vars.set( - name, - buffers.slice(offset, offset + taken + i) - ); - offset += taken + i + search.length; - } - else { - vars.set( - name, - buffers.slice(0, taken + i) - ); - buffers.splice(0, taken + i + search.length); - } - next(); - dispatch(); - } else { - i = Math.max(buffers.length - search.length - offset - taken, 0); - } - taken += i; - }; - dispatch(); - }; - - self.peek = function (cb) { - offset = 0; - saw.nest(function () { - cb.call(this, vars.store); - this.tap(function () { - offset = null; - }); - }); - }; - - return self; - }; - - var stream = Chainsaw.light(builder); - stream.writable = true; - - var buffers = Buffers(); - - stream.write = function (buf) { - buffers.push(buf); - dispatch(); - }; - - var vars = Vars(); - - var done = false, caughtEnd = false; - stream.end = function () { - caughtEnd = true; - }; - - stream.pipe = Stream.prototype.pipe; - Object.getOwnPropertyNames(EventEmitter.prototype).forEach(function (name) { - stream[name] = EventEmitter.prototype[name]; + } + return matches; }); - - return stream; -}; - -exports.parse = function parse (buffer) { - var self = words(function (bytes, cb) { - return function (name) { - if (offset + bytes <= buffer.length) { - var buf = buffer.slice(offset, offset + bytes); - offset += bytes; - vars.set(name, cb(buf)); +} +exports.findInPath = findInPath; +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* () { + // Ensure there is not a run away recursive copy + 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()) { + // Recurse + yield cpDirRecursive(srcFile, destFile, currentDepth, force); } else { - vars.set(name, null); + yield copyFile(srcFile, destFile, force); } - return self; - }; - }); - - var offset = 0; - var vars = Vars(); - self.vars = vars.store; - - self.tap = function (cb) { - cb.call(self, vars.store); - return self; - }; - - self.into = function (key, cb) { - if (!vars.get(key)) { - vars.set(key, {}); - } - var parent = vars; - vars = Vars(parent.get(key)); - cb.call(self, vars.store); - vars = parent; - return self; - }; - - self.loop = function (cb) { - var end = false; - var ender = function () { end = true }; - while (end === false) { - cb.call(self, ender, vars.store); - } - return self; - }; - - self.buffer = function (name, size) { - if (typeof size === 'string') { - size = vars.get(size); - } - var buf = buffer.slice(offset, Math.min(buffer.length, offset + size)); - offset += size; - vars.set(name, buf); - - return self; - }; - - self.skip = function (bytes) { - if (typeof bytes === 'string') { - bytes = vars.get(bytes); - } - offset += bytes; - - return self; - }; - - self.scan = function (name, search) { - if (typeof search === 'string') { - search = new Buffer(search); - } - else if (!Buffer.isBuffer(search)) { - throw new Error('search must be a Buffer or a string'); - } - vars.set(name, null); - - // simple but slow string search - for (var i = 0; i + offset <= buffer.length - search.length + 1; i++) { - for ( - var j = 0; - j < search.length && buffer[offset+i+j] === search[j]; - j++ - ); - if (j === search.length) break; } - - vars.set(name, buffer.slice(offset, offset + i)); - offset += i + search.length; - return self; - }; - - self.peek = function (cb) { - var was = offset; - cb.call(self, vars.store); - offset = was; - return self; - }; - - self.flush = function () { - vars.store = {}; - return self; - }; - - self.eof = function () { - return offset >= buffer.length; - }; - - return self; -}; - -// convert byte strings to unsigned little endian numbers -function decodeLEu (bytes) { - var acc = 0; - for (var i = 0; i < bytes.length; i++) { - acc += Math.pow(256,i) * bytes[i]; - } - return acc; -} - -// convert byte strings to unsigned big endian numbers -function decodeBEu (bytes) { - var acc = 0; - for (var i = 0; i < bytes.length; i++) { - acc += Math.pow(256, bytes.length - i - 1) * bytes[i]; - } - return acc; -} - -// convert byte strings to signed big endian numbers -function decodeBEs (bytes) { - var val = decodeBEu(bytes); - if ((bytes[0] & 0x80) == 0x80) { - val -= Math.pow(256, bytes.length); - } - return val; -} - -// convert byte strings to signed little endian numbers -function decodeLEs (bytes) { - var val = decodeLEu(bytes); - if ((bytes[bytes.length - 1] & 0x80) == 0x80) { - val -= Math.pow(256, bytes.length); - } - return val; -} - -function words (decode) { - var self = {}; - - [ 1, 2, 4, 8 ].forEach(function (bytes) { - var bits = bytes * 8; - - self['word' + bits + 'le'] - = self['word' + bits + 'lu'] - = decode(bytes, decodeLEu); - - self['word' + bits + 'ls'] - = decode(bytes, decodeLEs); - - self['word' + bits + 'be'] - = self['word' + bits + 'bu'] - = decode(bytes, decodeBEu); - - self['word' + bits + 'bs'] - = decode(bytes, decodeBEs); + // Change the mode for the newly created directory + yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode); }); - - // word8be(n) == word8le(n) for all n - self.word8 = self.word8u = self.word8be; - self.word8s = self.word8bs; - - return self; } - - -/***/ }), - -/***/ 3755: -/***/ ((module) => { - -module.exports = function (store) { - function getset (name, value) { - var node = vars.store; - var keys = name.split('.'); - keys.slice(0,-1).forEach(function (k) { - if (node[k] === undefined) node[k] = {}; - node = node[k] - }); - var key = keys[keys.length - 1]; - if (arguments.length == 1) { - return node[key]; +// Buffered file copy +function copyFile(srcFile, destFile, force) { + return __awaiter(this, void 0, void 0, function* () { + if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) { + // unlink/re-link it + try { + yield ioUtil.lstat(destFile); + yield ioUtil.unlink(destFile); + } + catch (e) { + // Try to override file permission + if (e.code === 'EPERM') { + yield ioUtil.chmod(destFile, '0666'); + yield ioUtil.unlink(destFile); + } + // other errors = it doesn't exist, no work to do + } + // Copy over symlink + const symlinkFull = yield ioUtil.readlink(srcFile); + yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? 'junction' : null); } - else { - return node[key] = value; + else if (!(yield ioUtil.exists(destFile)) || force) { + yield ioUtil.copyFile(srcFile, destFile); } - } - - var vars = { - get : function (name) { - return getset(name); - }, - set : function (name, value) { - return getset(name, value); - }, - store : store || {}, - }; - return vars; -}; - + }); +} +//# sourceMappingURL=io.js.map /***/ }), -/***/ 5490: +/***/ 7707: /***/ ((module) => { @@ -3764,15 +3208,14 @@ Promise.prototype.any = function () { /***/ }), -/***/ 8061: +/***/ 1281: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var firstLineError; try {throw new Error(); } catch (e) {firstLineError = e;} -var schedule = __nccwpck_require__(6203); -var Queue = __nccwpck_require__(878); -var util = __nccwpck_require__(7448); +var schedule = __nccwpck_require__(8108); +var Queue = __nccwpck_require__(2670); function Async() { this._customScheduler = false; @@ -3780,7 +3223,6 @@ function Async() { this._lateQueue = new Queue(16); this._normalQueue = new Queue(16); this._haveDrainedQueues = false; - this._trampolineEnabled = true; var self = this; this.drainQueues = function () { self._drainQueues(); @@ -3799,16 +3241,6 @@ Async.prototype.hasCustomScheduler = function() { return this._customScheduler; }; -Async.prototype.enableTrampoline = function() { - this._trampolineEnabled = true; -}; - -Async.prototype.disableTrampolineIfNecessary = function() { - if (util.hasDevTools) { - this._trampolineEnabled = false; - } -}; - Async.prototype.haveItemsQueued = function () { return this._isTickUsed || this._haveDrainedQueues; }; @@ -3857,62 +3289,33 @@ function AsyncSettlePromises(promise) { this._queueTick(); } -if (!util.hasDevTools) { - Async.prototype.invokeLater = AsyncInvokeLater; - Async.prototype.invoke = AsyncInvoke; - Async.prototype.settlePromises = AsyncSettlePromises; -} else { - Async.prototype.invokeLater = function (fn, receiver, arg) { - if (this._trampolineEnabled) { - AsyncInvokeLater.call(this, fn, receiver, arg); - } else { - this._schedule(function() { - setTimeout(function() { - fn.call(receiver, arg); - }, 100); - }); - } - }; +Async.prototype.invokeLater = AsyncInvokeLater; +Async.prototype.invoke = AsyncInvoke; +Async.prototype.settlePromises = AsyncSettlePromises; - Async.prototype.invoke = function (fn, receiver, arg) { - if (this._trampolineEnabled) { - AsyncInvoke.call(this, fn, receiver, arg); - } else { - this._schedule(function() { - fn.call(receiver, arg); - }); - } - }; - Async.prototype.settlePromises = function(promise) { - if (this._trampolineEnabled) { - AsyncSettlePromises.call(this, promise); - } else { - this._schedule(function() { - promise._settlePromises(); - }); - } - }; +function _drainQueue(queue) { + while (queue.length() > 0) { + _drainQueueStep(queue); + } } -Async.prototype._drainQueue = function(queue) { - while (queue.length() > 0) { - var fn = queue.shift(); - if (typeof fn !== "function") { - fn._settlePromises(); - continue; - } +function _drainQueueStep(queue) { + var fn = queue.shift(); + if (typeof fn !== "function") { + fn._settlePromises(); + } else { var receiver = queue.shift(); var arg = queue.shift(); fn.call(receiver, arg); } -}; +} Async.prototype._drainQueues = function () { - this._drainQueue(this._normalQueue); + _drainQueue(this._normalQueue); this._reset(); this._haveDrainedQueues = true; - this._drainQueue(this._lateQueue); + _drainQueue(this._lateQueue); }; Async.prototype._queueTick = function () { @@ -3932,7 +3335,7 @@ module.exports.firstLineError = firstLineError; /***/ }), -/***/ 3767: +/***/ 4330: /***/ ((module) => { @@ -4006,7 +3409,7 @@ Promise.bind = function (thisArg, value) { /***/ }), -/***/ 8710: +/***/ 4366: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { @@ -4017,14 +3420,14 @@ function noConflict() { catch (e) {} return bluebird; } -var bluebird = __nccwpck_require__(3694)(); +var bluebird = __nccwpck_require__(3096)(); bluebird.noConflict = noConflict; module.exports = bluebird; /***/ }), -/***/ 924: +/***/ 4454: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { @@ -4036,7 +3439,7 @@ if (cr) { } module.exports = function(Promise) { -var util = __nccwpck_require__(7448); +var util = __nccwpck_require__(409); var canEvaluate = util.canEvaluate; var isIdentifier = util.isIdentifier; @@ -4154,12 +3557,12 @@ Promise.prototype.get = function (propertyName) { /***/ }), -/***/ 6616: +/***/ 2855: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = function(Promise, PromiseArray, apiRejection, debug) { -var util = __nccwpck_require__(7448); +var util = __nccwpck_require__(409); var tryCatch = util.tryCatch; var errorObj = util.errorObj; var async = Promise._async; @@ -4290,13 +3693,13 @@ Promise.prototype._resultCancelled = function() { /***/ }), -/***/ 8985: +/***/ 4519: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = function(NEXT_FILTER) { -var util = __nccwpck_require__(7448); -var getKeys = (__nccwpck_require__(3062).keys); +var util = __nccwpck_require__(409); +var getKeys = (__nccwpck_require__(8974).keys); var tryCatch = util.tryCatch; var errorObj = util.errorObj; @@ -4339,7 +3742,7 @@ return catchFilter; /***/ }), -/***/ 5422: +/***/ 7790: /***/ ((module) => { @@ -4415,15 +3818,16 @@ return Context; /***/ }), -/***/ 6004: +/***/ 7979: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -module.exports = function(Promise, Context) { -var getDomain = Promise._getDomain; +module.exports = function(Promise, Context, + enableAsyncHooks, disableAsyncHooks) { var async = Promise._async; -var Warning = (__nccwpck_require__(5816).Warning); -var util = __nccwpck_require__(7448); +var Warning = (__nccwpck_require__(9318).Warning); +var util = __nccwpck_require__(409); +var es5 = __nccwpck_require__(8974); var canAttachTrace = util.canAttachTrace; var unhandledRejectionHandled; var possiblyUnhandledRejection; @@ -4449,6 +3853,34 @@ var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); +var deferUnhandledRejectionCheck; +(function() { + var promises = []; + + function unhandledRejectionCheck() { + for (var i = 0; i < promises.length; ++i) { + promises[i]._notifyUnhandledRejection(); + } + unhandledRejectionClear(); + } + + function unhandledRejectionClear() { + promises.length = 0; + } + + deferUnhandledRejectionCheck = function(promise) { + promises.push(promise); + setTimeout(unhandledRejectionCheck, 1); + }; + + es5.defineProperty(Promise, "_unhandledRejectionCheck", { + value: unhandledRejectionCheck + }); + es5.defineProperty(Promise, "_unhandledRejectionClear", { + value: unhandledRejectionClear + }); +})(); + Promise.prototype.suppressUnhandledRejections = function() { var target = this._target(); target._bitField = ((target._bitField & (~1048576)) | @@ -4458,7 +3890,7 @@ Promise.prototype.suppressUnhandledRejections = function() { Promise.prototype._ensurePossibleRejectionHandled = function () { if ((this._bitField & 524288) !== 0) return; this._setRejectionIsUnhandled(); - async.invokeLater(this._notifyUnhandledRejection, this, undefined); + deferUnhandledRejectionCheck(this); }; Promise.prototype._notifyUnhandledRejectionIsHandled = function () { @@ -4516,19 +3948,13 @@ Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) { }; Promise.onPossiblyUnhandledRejection = function (fn) { - var domain = getDomain(); - possiblyUnhandledRejection = - typeof fn === "function" ? (domain === null ? - fn : util.domainBind(domain, fn)) - : undefined; + var context = Promise._getContext(); + possiblyUnhandledRejection = util.contextBind(context, fn); }; Promise.onUnhandledRejectionHandled = function (fn) { - var domain = getDomain(); - unhandledRejectionHandled = - typeof fn === "function" ? (domain === null ? - fn : util.domainBind(domain, fn)) - : undefined; + var context = Promise._getContext(); + unhandledRejectionHandled = util.contextBind(context, fn); }; var disableLongStackTraces = function() {}; @@ -4539,6 +3965,7 @@ Promise.longStackTraces = function () { if (!config.longStackTraces && longStackTracesIsSupported()) { var Promise_captureStackTrace = Promise.prototype._captureStackTrace; var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; + var Promise_dereferenceTrace = Promise.prototype._dereferenceTrace; config.longStackTraces = true; disableLongStackTraces = function() { if (async.haveItemsQueued() && !config.longStackTraces) { @@ -4546,14 +3973,14 @@ Promise.longStackTraces = function () { } Promise.prototype._captureStackTrace = Promise_captureStackTrace; Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; + Promise.prototype._dereferenceTrace = Promise_dereferenceTrace; Context.deactivateLongStackTraces(); - async.enableTrampoline(); config.longStackTraces = false; }; Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; + Promise.prototype._dereferenceTrace = longStackTracesDereferenceTrace; Context.activateLongStackTraces(); - async.disableTrampolineIfNecessary(); } }; @@ -4561,37 +3988,85 @@ Promise.hasLongStackTraces = function () { return config.longStackTraces && longStackTracesIsSupported(); }; + +var legacyHandlers = { + unhandledrejection: { + before: function() { + var ret = util.global.onunhandledrejection; + util.global.onunhandledrejection = null; + return ret; + }, + after: function(fn) { + util.global.onunhandledrejection = fn; + } + }, + rejectionhandled: { + before: function() { + var ret = util.global.onrejectionhandled; + util.global.onrejectionhandled = null; + return ret; + }, + after: function(fn) { + util.global.onrejectionhandled = fn; + } + } +}; + var fireDomEvent = (function() { + var dispatch = function(legacy, e) { + if (legacy) { + var fn; + try { + fn = legacy.before(); + return !util.global.dispatchEvent(e); + } finally { + legacy.after(fn); + } + } else { + return !util.global.dispatchEvent(e); + } + }; try { if (typeof CustomEvent === "function") { var event = new CustomEvent("CustomEvent"); util.global.dispatchEvent(event); return function(name, event) { - var domEvent = new CustomEvent(name.toLowerCase(), { + name = name.toLowerCase(); + var eventData = { detail: event, cancelable: true - }); - return !util.global.dispatchEvent(domEvent); + }; + var domEvent = new CustomEvent(name, eventData); + es5.defineProperty( + domEvent, "promise", {value: event.promise}); + es5.defineProperty( + domEvent, "reason", {value: event.reason}); + + return dispatch(legacyHandlers[name], domEvent); }; } else if (typeof Event === "function") { var event = new Event("CustomEvent"); util.global.dispatchEvent(event); return function(name, event) { - var domEvent = new Event(name.toLowerCase(), { + name = name.toLowerCase(); + var domEvent = new Event(name, { cancelable: true }); domEvent.detail = event; - return !util.global.dispatchEvent(domEvent); + es5.defineProperty(domEvent, "promise", {value: event.promise}); + es5.defineProperty(domEvent, "reason", {value: event.reason}); + return dispatch(legacyHandlers[name], domEvent); }; } else { var event = document.createEvent("CustomEvent"); event.initCustomEvent("testingtheevent", false, true, {}); util.global.dispatchEvent(event); return function(name, event) { + name = name.toLowerCase(); var domEvent = document.createEvent("CustomEvent"); - domEvent.initCustomEvent(name.toLowerCase(), false, true, + domEvent.initCustomEvent(name, false, true, event); - return !util.global.dispatchEvent(domEvent); + return dispatch(legacyHandlers[name], domEvent); }; } } catch (e) {} @@ -4709,6 +4184,18 @@ Promise.config = function(opts) { Promise.prototype._fireEvent = defaultFireEvent; } } + if ("asyncHooks" in opts && util.nodeSupportsAsyncResource) { + var prev = config.asyncHooks; + var cur = !!opts.asyncHooks; + if (prev !== cur) { + config.asyncHooks = cur; + if (cur) { + enableAsyncHooks(); + } else { + disableAsyncHooks(); + } + } + } return Promise; }; @@ -4729,6 +4216,7 @@ Promise.prototype._attachCancellationCallback = function(onCancel) { }; Promise.prototype._captureStackTrace = function () {}; Promise.prototype._attachExtraTrace = function () {}; +Promise.prototype._dereferenceTrace = function () {}; Promise.prototype._clearCancellationData = function() {}; Promise.prototype._propagateFrom = function (parent, flags) { ; @@ -4834,6 +4322,10 @@ function longStackTracesAttachExtraTrace(error, ignoreSelf) { } } +function longStackTracesDereferenceTrace() { + this._trace = undefined; +} + function checkForgottenReturns(returnValue, promiseCreated, name, promise, parent) { if (returnValue === undefined && promiseCreated !== null && @@ -5091,8 +4583,8 @@ function parseLineInfo(line) { function setBounds(firstLineError, lastLineError) { if (!longStackTracesIsSupported()) return; - var firstStackLines = firstLineError.stack.split("\n"); - var lastStackLines = lastLineError.stack.split("\n"); + var firstStackLines = (firstLineError.stack || "").split("\n"); + var lastStackLines = (lastLineError.stack || "").split("\n"); var firstIndex = -1; var lastIndex = -1; var firstFileName; @@ -5301,12 +4793,16 @@ var config = { warnings: warnings, longStackTraces: false, cancellation: false, - monitoring: false + monitoring: false, + asyncHooks: false }; if (longStackTraces) Promise.longStackTraces(); return { + asyncHooks: function() { + return config.asyncHooks; + }, longStackTraces: function() { return config.longStackTraces; }, @@ -5338,7 +4834,7 @@ return { /***/ }), -/***/ 8277: +/***/ 6535: /***/ ((module) => { @@ -5391,7 +4887,7 @@ Promise.prototype.catchReturn = function (value) { /***/ }), -/***/ 838: +/***/ 3207: /***/ ((module) => { @@ -5428,13 +4924,13 @@ Promise.mapSeries = PromiseMapSeries; /***/ }), -/***/ 5816: +/***/ 9318: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var es5 = __nccwpck_require__(3062); +var es5 = __nccwpck_require__(8974); var Objectfreeze = es5.freeze; -var util = __nccwpck_require__(7448); +var util = __nccwpck_require__(409); var inherits = util.inherits; var notEnumerableProp = util.notEnumerableProp; @@ -5551,7 +5047,7 @@ module.exports = { /***/ }), -/***/ 3062: +/***/ 8974: /***/ ((module) => { var isES5 = (function(){ @@ -5638,7 +5134,7 @@ if (isES5) { /***/ }), -/***/ 2223: +/***/ 8595: /***/ ((module) => { @@ -5657,14 +5153,15 @@ Promise.filter = function (promises, fn, options) { /***/ }), -/***/ 7304: +/***/ 2198: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -module.exports = function(Promise, tryConvertToPromise) { -var util = __nccwpck_require__(7448); +module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) { +var util = __nccwpck_require__(409); var CancellationError = Promise.CancellationError; var errorObj = util.errorObj; +var catchFilter = __nccwpck_require__(4519)(NEXT_FILTER); function PassThroughHandlerContext(promise, type, handler) { this.promise = promise; @@ -5716,7 +5213,9 @@ function finallyHandler(reasonOrValue) { var ret = this.isFinallyHandler() ? handler.call(promise._boundValue()) : handler.call(promise._boundValue(), reasonOrValue); - if (ret !== undefined) { + if (ret === NEXT_FILTER) { + return ret; + } else if (ret !== undefined) { promise._setReturnedNonUndefined(); var maybePromise = tryConvertToPromise(ret, promise); if (maybePromise instanceof Promise) { @@ -5765,17 +5264,49 @@ Promise.prototype["finally"] = function (handler) { finallyHandler); }; + Promise.prototype.tap = function (handler) { return this._passThrough(handler, 1, finallyHandler); }; +Promise.prototype.tapCatch = function (handlerOrPredicate) { + var len = arguments.length; + if(len === 1) { + return this._passThrough(handlerOrPredicate, + 1, + undefined, + finallyHandler); + } else { + var catchInstances = new Array(len - 1), + j = 0, i; + for (i = 0; i < len - 1; ++i) { + var item = arguments[i]; + if (util.isObject(item)) { + catchInstances[j++] = item; + } else { + return Promise.reject(new TypeError( + "tapCatch statement predicate: " + + "expecting an object but got " + util.classString(item) + )); + } + } + catchInstances.length = j; + var handler = arguments[i]; + return this._passThrough(catchFilter(catchInstances, handler, this), + 1, + undefined, + finallyHandler); + } + +}; + return PassThroughHandlerContext; }; /***/ }), -/***/ 8619: +/***/ 1595: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { @@ -5785,9 +5316,9 @@ module.exports = function(Promise, tryConvertToPromise, Proxyable, debug) { -var errors = __nccwpck_require__(5816); +var errors = __nccwpck_require__(9318); var TypeError = errors.TypeError; -var util = __nccwpck_require__(7448); +var util = __nccwpck_require__(409); var errorObj = util.errorObj; var tryCatch = util.tryCatch; var yieldHandlers = []; @@ -5937,7 +5468,7 @@ PromiseSpawn.prototype._continue = function (result) { if (maybePromise === null) { this._promiseRejected( new TypeError( - "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", value) + + "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", String(value)) + "From coroutine:\u000a" + this._stack.split("\n").slice(1, -7).join("\n") ) @@ -6005,14 +5536,13 @@ Promise.spawn = function (generatorFunction) { /***/ }), -/***/ 5248: +/***/ 3321: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = -function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, - getDomain) { -var util = __nccwpck_require__(7448); +function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async) { +var util = __nccwpck_require__(409); var canEvaluate = util.canEvaluate; var tryCatch = util.tryCatch; var errorObj = util.errorObj; @@ -6157,10 +5687,8 @@ Promise.join = function () { if (!ret._isFateSealed()) { if (holder.asyncNeeded) { - var domain = getDomain(); - if (domain !== null) { - holder.fn = util.domainBind(domain, holder.fn); - } + var context = Promise._getContext(); + holder.fn = util.contextBind(context, holder.fn); } ret._setAsyncGuaranteed(); ret._setOnCancel(holder); @@ -6169,7 +5697,7 @@ Promise.join = function () { } } } - var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];}; + var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len ; ++$_i) {args[$_i] = arguments[$_i ];}; if (fn) args.pop(); var ret = new PromiseArray(args).promise(); return fn !== undefined ? ret.spread(fn) : ret; @@ -6180,7 +5708,7 @@ Promise.join = function () { /***/ }), -/***/ 8150: +/***/ 9651: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { @@ -6190,8 +5718,7 @@ module.exports = function(Promise, tryConvertToPromise, INTERNAL, debug) { -var getDomain = Promise._getDomain; -var util = __nccwpck_require__(7448); +var util = __nccwpck_require__(409); var tryCatch = util.tryCatch; var errorObj = util.errorObj; var async = Promise._async; @@ -6199,8 +5726,8 @@ var async = Promise._async; function MappingPromiseArray(promises, fn, limit, _filter) { this.constructor$(promises); this._promise._captureStackTrace(); - var domain = getDomain(); - this._callback = domain === null ? fn : util.domainBind(domain, fn); + var context = Promise._getContext(); + this._callback = util.contextBind(context, fn); this._preservedValues = _filter === INTERNAL ? new Array(this.length()) : null; @@ -6208,6 +5735,14 @@ function MappingPromiseArray(promises, fn, limit, _filter) { this._inFlight = 0; this._queue = []; async.invoke(this._asyncInit, this, undefined); + if (util.isArray(promises)) { + for (var i = 0; i < promises.length; ++i) { + var maybePromise = promises[i]; + if (maybePromise instanceof Promise) { + maybePromise.suppressUnhandledRejections(); + } + } + } } util.inherits(MappingPromiseArray, PromiseArray); @@ -6355,13 +5890,13 @@ Promise.map = function (promises, fn, options, _filter) { /***/ }), -/***/ 7415: +/***/ 5588: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { -var util = __nccwpck_require__(7448); +var util = __nccwpck_require__(409); var tryCatch = util.tryCatch; Promise.method = function (fn) { @@ -6417,15 +5952,15 @@ Promise.prototype._resolveFromSyncValue = function (value) { /***/ }), -/***/ 4315: +/***/ 1774: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var util = __nccwpck_require__(7448); +var util = __nccwpck_require__(409); var maybeWrapAsError = util.maybeWrapAsError; -var errors = __nccwpck_require__(5816); +var errors = __nccwpck_require__(9318); var OperationalError = errors.OperationalError; -var es5 = __nccwpck_require__(3062); +var es5 = __nccwpck_require__(8974); function isUntypedError(obj) { return obj instanceof Error && @@ -6475,12 +6010,12 @@ module.exports = nodebackForPromise; /***/ }), -/***/ 5447: +/***/ 3327: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = function(Promise) { -var util = __nccwpck_require__(7448); +var util = __nccwpck_require__(409); var async = Promise._async; var tryCatch = util.tryCatch; var errorObj = util.errorObj; @@ -6540,7 +6075,7 @@ Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback, /***/ }), -/***/ 3694: +/***/ 3096: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { @@ -6556,27 +6091,49 @@ var apiRejection = function(msg) { }; function Proxyable() {} var UNDEFINED_BINDING = {}; -var util = __nccwpck_require__(7448); +var util = __nccwpck_require__(409); +util.setReflectHandler(reflectHandler); -var getDomain; -if (util.isNode) { - getDomain = function() { - var ret = process.domain; - if (ret === undefined) ret = null; - return ret; - }; -} else { - getDomain = function() { +var getDomain = function() { + var domain = process.domain; + if (domain === undefined) { return null; + } + return domain; +}; +var getContextDefault = function() { + return null; +}; +var getContextDomain = function() { + return { + domain: getDomain(), + async: null }; -} -util.notEnumerableProp(Promise, "_getDomain", getDomain); +}; +var AsyncResource = util.isNode && util.nodeSupportsAsyncResource ? + (__nccwpck_require__(290).AsyncResource) : null; +var getContextAsyncHooks = function() { + return { + domain: getDomain(), + async: new AsyncResource("Bluebird::Promise") + }; +}; +var getContext = util.isNode ? getContextDomain : getContextDefault; +util.notEnumerableProp(Promise, "_getContext", getContext); +var enableAsyncHooks = function() { + getContext = getContextAsyncHooks; + util.notEnumerableProp(Promise, "_getContext", getContextAsyncHooks); +}; +var disableAsyncHooks = function() { + getContext = getContextDomain; + util.notEnumerableProp(Promise, "_getContext", getContextDomain); +}; -var es5 = __nccwpck_require__(3062); -var Async = __nccwpck_require__(8061); +var es5 = __nccwpck_require__(8974); +var Async = __nccwpck_require__(1281); var async = new Async(); es5.defineProperty(Promise, "_async", {value: async}); -var errors = __nccwpck_require__(5816); +var errors = __nccwpck_require__(9318); var TypeError = Promise.TypeError = errors.TypeError; Promise.RangeError = errors.RangeError; var CancellationError = Promise.CancellationError = errors.CancellationError; @@ -6587,40 +6144,43 @@ Promise.AggregateError = errors.AggregateError; var INTERNAL = function(){}; var APPLY = {}; var NEXT_FILTER = {}; -var tryConvertToPromise = __nccwpck_require__(9787)(Promise, INTERNAL); +var tryConvertToPromise = __nccwpck_require__(1565)(Promise, INTERNAL); var PromiseArray = - __nccwpck_require__(5307)(Promise, INTERNAL, + __nccwpck_require__(554)(Promise, INTERNAL, tryConvertToPromise, apiRejection, Proxyable); -var Context = __nccwpck_require__(5422)(Promise); +var Context = __nccwpck_require__(7790)(Promise); /*jshint unused:false*/ var createContext = Context.create; -var debug = __nccwpck_require__(6004)(Promise, Context); + +var debug = __nccwpck_require__(7979)(Promise, Context, + enableAsyncHooks, disableAsyncHooks); var CapturedTrace = debug.CapturedTrace; var PassThroughHandlerContext = - __nccwpck_require__(7304)(Promise, tryConvertToPromise); -var catchFilter = __nccwpck_require__(8985)(NEXT_FILTER); -var nodebackForPromise = __nccwpck_require__(4315); + __nccwpck_require__(2198)(Promise, tryConvertToPromise, NEXT_FILTER); +var catchFilter = __nccwpck_require__(4519)(NEXT_FILTER); +var nodebackForPromise = __nccwpck_require__(1774); var errorObj = util.errorObj; var tryCatch = util.tryCatch; function check(self, executor) { + if (self == null || self.constructor !== Promise) { + throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } if (typeof executor !== "function") { throw new TypeError("expecting a function but got " + util.classString(executor)); } - if (self.constructor !== Promise) { - throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } + } function Promise(executor) { + if (executor !== INTERNAL) { + check(this, executor); + } this._bitField = 0; this._fulfillmentHandler0 = undefined; this._rejectionHandler0 = undefined; this._promise0 = undefined; this._receiver0 = undefined; - if (executor !== INTERNAL) { - check(this, executor); - this._resolveFromExecutor(executor); - } + this._resolveFromExecutor(executor); this._promiseCreated(); this._fireEvent("promiseCreated", this); } @@ -6639,12 +6199,17 @@ Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { if (util.isObject(item)) { catchInstances[j++] = item; } else { - return apiRejection("expecting an object but got " + - "A catch statement predicate " + util.classString(item)); + return apiRejection("Catch statement predicate: " + + "expecting an object but got " + util.classString(item)); } } catchInstances.length = j; fn = arguments[i]; + + if (typeof fn !== "function") { + throw new TypeError("The last argument to .catch() " + + "must be a function, got " + util.toString(fn)); + } return this.then(undefined, catchFilter(catchInstances, fn, this)); } return this.then(undefined, fn); @@ -6785,7 +6350,7 @@ Promise.prototype._then = function ( this._fireEvent("promiseChained", this, promise); } - var domain = getDomain(); + var context = getContext(); if (!((bitField & 50397184) === 0)) { var handler, value, settler = target._settlePromiseCtx; if (((bitField & 33554432) !== 0)) { @@ -6803,15 +6368,14 @@ Promise.prototype._then = function ( } async.invoke(settler, target, { - handler: domain === null ? handler - : (typeof handler === "function" && - util.domainBind(domain, handler)), + handler: util.contextBind(context, handler), promise: promise, receiver: receiver, value: value }); } else { - target._addCallbacks(didFulfill, didReject, promise, receiver, domain); + target._addCallbacks(didFulfill, didReject, promise, + receiver, context); } return promise; @@ -6872,7 +6436,15 @@ Promise.prototype._setWillBeCancelled = function() { Promise.prototype._setAsyncGuaranteed = function() { if (async.hasCustomScheduler()) return; - this._bitField = this._bitField | 134217728; + var bitField = this._bitField; + this._bitField = bitField | + (((bitField & 536870912) >> 2) ^ + 134217728); +}; + +Promise.prototype._setNoAsyncGuarantee = function() { + this._bitField = (this._bitField | 536870912) & + (~134217728); }; Promise.prototype._receiverAt = function (index) { @@ -6927,7 +6499,7 @@ Promise.prototype._addCallbacks = function ( reject, promise, receiver, - domain + context ) { var index = this._length(); @@ -6940,12 +6512,10 @@ Promise.prototype._addCallbacks = function ( this._promise0 = promise; this._receiver0 = receiver; if (typeof fulfill === "function") { - this._fulfillmentHandler0 = - domain === null ? fulfill : util.domainBind(domain, fulfill); + this._fulfillmentHandler0 = util.contextBind(context, fulfill); } if (typeof reject === "function") { - this._rejectionHandler0 = - domain === null ? reject : util.domainBind(domain, reject); + this._rejectionHandler0 = util.contextBind(context, reject); } } else { var base = index * 4 - 4; @@ -6953,11 +6523,11 @@ Promise.prototype._addCallbacks = function ( this[base + 3] = receiver; if (typeof fulfill === "function") { this[base + 0] = - domain === null ? fulfill : util.domainBind(domain, fulfill); + util.contextBind(context, fulfill); } if (typeof reject === "function") { this[base + 1] = - domain === null ? reject : util.domainBind(domain, reject); + util.contextBind(context, reject); } } this._setLength(index + 1); @@ -6977,6 +6547,7 @@ Promise.prototype._resolveCallback = function(value, shouldBind) { if (shouldBind) this._propagateFrom(maybePromise, 2); + var promise = maybePromise._target(); if (promise === this) { @@ -6993,7 +6564,7 @@ Promise.prototype._resolveCallback = function(value, shouldBind) { } this._setFollowing(); this._setLength(0); - this._setFollowee(promise); + this._setFollowee(maybePromise); } else if (((bitField & 33554432) !== 0)) { this._fulfill(promise._value()); } else if (((bitField & 16777216) !== 0)) { @@ -7019,6 +6590,7 @@ function(reason, synchronous, ignoreNonErrorWarnings) { }; Promise.prototype._resolveFromExecutor = function (executor) { + if (executor === INTERNAL) return; var promise = this; this._captureStackTrace(); this._pushContext(); @@ -7182,6 +6754,7 @@ Promise.prototype._fulfill = function (value) { } else { async.settlePromises(this); } + this._dereferenceTrace(); } }; @@ -7250,6 +6823,14 @@ Promise.prototype._settledValue = function() { } }; +if (typeof Symbol !== "undefined" && Symbol.toStringTag) { + es5.defineProperty(Promise.prototype, Symbol.toStringTag, { + get: function () { + return "Object"; + } + }); +} + function deferResolve(v) {this.promise._resolveCallback(v);} function deferReject(v) {this.promise._rejectCallback(v, false);} @@ -7267,31 +6848,31 @@ util.notEnumerableProp(Promise, "_makeSelfResolutionError", makeSelfResolutionError); -__nccwpck_require__(7415)(Promise, INTERNAL, tryConvertToPromise, apiRejection, +__nccwpck_require__(5588)(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug); -__nccwpck_require__(3767)(Promise, INTERNAL, tryConvertToPromise, debug); -__nccwpck_require__(6616)(Promise, PromiseArray, apiRejection, debug); -__nccwpck_require__(8277)(Promise); -__nccwpck_require__(6653)(Promise); -__nccwpck_require__(5248)( - Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain); +__nccwpck_require__(4330)(Promise, INTERNAL, tryConvertToPromise, debug); +__nccwpck_require__(2855)(Promise, PromiseArray, apiRejection, debug); +__nccwpck_require__(6535)(Promise); +__nccwpck_require__(5761)(Promise); +__nccwpck_require__(3321)( + Promise, PromiseArray, tryConvertToPromise, INTERNAL, async); Promise.Promise = Promise; -Promise.version = "3.4.7"; -__nccwpck_require__(8150)(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); -__nccwpck_require__(924)(Promise); -__nccwpck_require__(880)(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); -__nccwpck_require__(2114)(Promise, INTERNAL, debug); -__nccwpck_require__(8619)(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug); -__nccwpck_require__(5447)(Promise); -__nccwpck_require__(3047)(Promise, INTERNAL); -__nccwpck_require__(5261)(Promise, PromiseArray, tryConvertToPromise, apiRejection); -__nccwpck_require__(256)(Promise, INTERNAL, tryConvertToPromise, apiRejection); -__nccwpck_require__(8959)(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); -__nccwpck_require__(6087)(Promise, PromiseArray, debug); -__nccwpck_require__(1156)(Promise, PromiseArray, apiRejection); -__nccwpck_require__(2223)(Promise, INTERNAL); -__nccwpck_require__(838)(Promise, INTERNAL); -__nccwpck_require__(5490)(Promise); +Promise.version = "3.7.2"; +__nccwpck_require__(4454)(Promise); +__nccwpck_require__(1595)(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug); +__nccwpck_require__(9651)(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); +__nccwpck_require__(3327)(Promise); +__nccwpck_require__(5865)(Promise, INTERNAL); +__nccwpck_require__(2951)(Promise, PromiseArray, tryConvertToPromise, apiRejection); +__nccwpck_require__(5380)(Promise, INTERNAL, tryConvertToPromise, apiRejection); +__nccwpck_require__(631)(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); +__nccwpck_require__(5270)(Promise, PromiseArray, debug); +__nccwpck_require__(1253)(Promise, PromiseArray, apiRejection); +__nccwpck_require__(8407)(Promise, INTERNAL, debug); +__nccwpck_require__(1113)(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); +__nccwpck_require__(7707)(Promise); +__nccwpck_require__(3207)(Promise, INTERNAL); +__nccwpck_require__(8595)(Promise, INTERNAL); util.toFastProperties(Promise); util.toFastProperties(Promise.prototype); @@ -7320,19 +6901,20 @@ __nccwpck_require__(5490)(Promise); /***/ }), -/***/ 5307: +/***/ 554: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = function(Promise, INTERNAL, tryConvertToPromise, apiRejection, Proxyable) { -var util = __nccwpck_require__(7448); +var util = __nccwpck_require__(409); var isArray = util.isArray; function toResolutionValue(val) { switch(val) { case -2: return []; case -3: return {}; + case -6: return new Map(); } } @@ -7340,6 +6922,7 @@ function PromiseArray(values) { var promise = this._promise = new Promise(INTERNAL); if (values instanceof Promise) { promise._propagateFrom(values, 3); + values.suppressUnhandledRejections(); } promise._setOnCancel(this); this._values = values; @@ -7511,18 +7094,18 @@ return PromiseArray; /***/ }), -/***/ 3047: +/***/ 5865: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = function(Promise, INTERNAL) { var THIS = {}; -var util = __nccwpck_require__(7448); -var nodebackForPromise = __nccwpck_require__(4315); +var util = __nccwpck_require__(409); +var nodebackForPromise = __nccwpck_require__(1774); var withAppended = util.withAppended; var maybeWrapAsError = util.maybeWrapAsError; var canEvaluate = util.canEvaluate; -var TypeError = (__nccwpck_require__(5816).TypeError); +var TypeError = (__nccwpck_require__(9318).TypeError); var defaultSuffix = "Async"; var defaultPromisified = {__isPromisified__: true}; var noCopyProps = [ @@ -7832,15 +7415,15 @@ Promise.promisifyAll = function (target, options) { /***/ }), -/***/ 5261: +/***/ 2951: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = function( Promise, PromiseArray, tryConvertToPromise, apiRejection) { -var util = __nccwpck_require__(7448); +var util = __nccwpck_require__(409); var isObject = util.isObject; -var es5 = __nccwpck_require__(3062); +var es5 = __nccwpck_require__(8974); var Es6Map; if (typeof Map === "function") Es6Map = Map; @@ -7892,7 +7475,7 @@ function PropertiesPromiseArray(obj) { } this.constructor$(entries); this._isMap = isMap; - this._init$(undefined, -3); + this._init$(undefined, isMap ? -6 : -3); } util.inherits(PropertiesPromiseArray, PromiseArray); @@ -7957,7 +7540,7 @@ Promise.props = function (promises) { /***/ }), -/***/ 878: +/***/ 2670: /***/ ((module) => { @@ -8037,13 +7620,13 @@ module.exports = Queue; /***/ }), -/***/ 256: +/***/ 5380: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = function( Promise, INTERNAL, tryConvertToPromise, apiRejection) { -var util = __nccwpck_require__(7448); +var util = __nccwpck_require__(409); var raceLater = function (promise) { return promise.then(function(array) { @@ -8093,7 +7676,7 @@ Promise.prototype.race = function () { /***/ }), -/***/ 8959: +/***/ 631: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { @@ -8103,14 +7686,13 @@ module.exports = function(Promise, tryConvertToPromise, INTERNAL, debug) { -var getDomain = Promise._getDomain; -var util = __nccwpck_require__(7448); +var util = __nccwpck_require__(409); var tryCatch = util.tryCatch; function ReductionPromiseArray(promises, fn, initialValue, _each) { this.constructor$(promises); - var domain = getDomain(); - this._fn = domain === null ? fn : util.domainBind(domain, fn); + var context = Promise._getContext(); + this._fn = util.contextBind(context, fn); if (initialValue !== undefined) { initialValue = Promise.resolve(initialValue); initialValue._attachCancellationCallback(this); @@ -8130,8 +7712,8 @@ function ReductionPromiseArray(promises, fn, initialValue, _each) { util.inherits(ReductionPromiseArray, PromiseArray); ReductionPromiseArray.prototype._gotAccum = function(accum) { - if (this._eachValues !== undefined && - this._eachValues !== null && + if (this._eachValues !== undefined && + this._eachValues !== null && accum !== INTERNAL) { this._eachValues.push(accum); } @@ -8187,6 +7769,13 @@ ReductionPromiseArray.prototype._iterate = function (values) { this._currentCancellable = value; + for (var j = i; j < length; ++j) { + var maybePromise = values[j]; + if (maybePromise instanceof Promise) { + maybePromise.suppressUnhandledRejections(); + } + } + if (!value.isRejected()) { for (; i < length; ++i) { var ctx = { @@ -8196,7 +7785,12 @@ ReductionPromiseArray.prototype._iterate = function (values) { length: length, array: this }; + value = value._then(gotAccum, undefined, undefined, ctx, undefined); + + if ((i & 127) === 0) { + value._setNoAsyncGuarantee(); + } } } @@ -8272,11 +7866,11 @@ function gotValue(value) { /***/ }), -/***/ 6203: +/***/ 8108: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var util = __nccwpck_require__(7448); +var util = __nccwpck_require__(409); var schedule; var noAsyncScheduler = function() { throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); @@ -8297,7 +7891,8 @@ if (util.isNode && typeof MutationObserver === "undefined") { } else if ((typeof MutationObserver !== "undefined") && !(typeof window !== "undefined" && window.navigator && - (window.navigator.standalone || window.cordova))) { + (window.navigator.standalone || window.cordova)) && + ("classList" in document.documentElement)) { schedule = (function() { var div = document.createElement("div"); var opts = {attributes: true}; @@ -8311,11 +7906,11 @@ if (util.isNode && typeof MutationObserver === "undefined") { var scheduleToggle = function() { if (toggleScheduled) return; - toggleScheduled = true; - div2.classList.toggle("foo"); - }; + toggleScheduled = true; + div2.classList.toggle("foo"); + }; - return function schedule(fn) { + return function schedule(fn) { var o = new MutationObserver(function() { o.disconnect(); fn(); @@ -8340,14 +7935,14 @@ module.exports = schedule; /***/ }), -/***/ 6087: +/***/ 5270: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = function(Promise, PromiseArray, debug) { var PromiseInspection = Promise.PromiseInspection; -var util = __nccwpck_require__(7448); +var util = __nccwpck_require__(409); function SettledPromiseArray(values) { this.constructor$(values); @@ -8382,6 +7977,10 @@ Promise.settle = function (promises) { return new SettledPromiseArray(promises).promise(); }; +Promise.allSettled = function (promises) { + return new SettledPromiseArray(promises).promise(); +}; + Promise.prototype.settle = function () { return Promise.settle(this); }; @@ -8390,15 +7989,15 @@ Promise.prototype.settle = function () { /***/ }), -/***/ 1156: +/***/ 1253: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = function(Promise, PromiseArray, apiRejection) { -var util = __nccwpck_require__(7448); -var RangeError = (__nccwpck_require__(5816).RangeError); -var AggregateError = (__nccwpck_require__(5816).AggregateError); +var util = __nccwpck_require__(409); +var RangeError = (__nccwpck_require__(9318).RangeError); +var AggregateError = (__nccwpck_require__(9318).AggregateError); var isArray = util.isArray; var CANCELLATION = {}; @@ -8545,7 +8144,7 @@ Promise._SomePromiseArray = SomePromiseArray; /***/ }), -/***/ 6653: +/***/ 5761: /***/ ((module) => { @@ -8655,12 +8254,12 @@ Promise.PromiseInspection = PromiseInspection; /***/ }), -/***/ 9787: +/***/ 1565: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = function(Promise, INTERNAL) { -var util = __nccwpck_require__(7448); +var util = __nccwpck_require__(409); var errorObj = util.errorObj; var isObject = util.isObject; @@ -8748,12 +8347,12 @@ return tryConvertToPromise; /***/ }), -/***/ 2114: +/***/ 8407: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = function(Promise, INTERNAL, debug) { -var util = __nccwpck_require__(7448); +var util = __nccwpck_require__(409); var TimeoutError = Promise.TimeoutError; function HandleWrapper(handle) { @@ -8848,15 +8447,15 @@ Promise.prototype.timeout = function (ms, message) { /***/ }), -/***/ 880: +/***/ 1113: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = function (Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug) { - var util = __nccwpck_require__(7448); - var TypeError = (__nccwpck_require__(5816).TypeError); - var inherits = (__nccwpck_require__(7448).inherits); + var util = __nccwpck_require__(409); + var TypeError = (__nccwpck_require__(9318).TypeError); + var inherits = (__nccwpck_require__(409).inherits); var errorObj = util.errorObj; var tryCatch = util.tryCatch; var NULL = {}; @@ -9081,11 +8680,11 @@ module.exports = function (Promise, apiRejection, tryConvertToPromise, /***/ }), -/***/ 7448: +/***/ 409: /***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { -var es5 = __nccwpck_require__(3062); +var es5 = __nccwpck_require__(8974); var canEvaluate = typeof navigator == "undefined"; var errorObj = {e: {}}; @@ -9281,8 +8880,12 @@ function toFastProperties(obj) { /*jshint -W027,-W055,-W031*/ function FakeConstructor() {} FakeConstructor.prototype = obj; - var l = 8; - while (l--) new FakeConstructor(); + var receiver = new FakeConstructor(); + function ic() { + return typeof receiver.foo; + } + ic(); + ic(); return obj; eval(obj); } @@ -9309,10 +8912,11 @@ function safeToString(obj) { } function isError(obj) { - return obj !== null && + return obj instanceof Error || + (obj !== null && typeof obj === "object" && typeof obj.message === "string" && - typeof obj.name === "string"; + typeof obj.name === "string"); } function markAsOriginatingFromRejection(e) { @@ -9407,18 +9011,42 @@ function getNativePromise() { if (typeof Promise === "function") { try { var promise = new Promise(function(){}); - if ({}.toString.call(promise) === "[object Promise]") { + if (classString(promise) === "[object Promise]") { return Promise; } } catch (e) {} } } -function domainBind(self, cb) { - return self.bind(cb); +var reflectHandler; +function contextBind(ctx, cb) { + if (ctx === null || + typeof cb !== "function" || + cb === reflectHandler) { + return cb; + } + + if (ctx.domain !== null) { + cb = ctx.domain.bind(cb); + } + + var async = ctx.async; + if (async !== null) { + var old = cb; + cb = function() { + var $_len = arguments.length + 2;var args = new Array($_len); for(var $_i = 2; $_i < $_len ; ++$_i) {args[$_i] = arguments[$_i - 2];}; + args[0] = old; + args[1] = this; + return async.runInAsyncScope.apply(async, args); + }; + } + return cb; } var ret = { + setReflectHandler: function(fn) { + reflectHandler = fn; + }, isClass: isClass, isIdentifier: isIdentifier, inheritedDataKeys: inheritedDataKeys, @@ -9445,19 +9073,32 @@ var ret = { markAsOriginatingFromRejection: markAsOriginatingFromRejection, classString: classString, copyDescriptors: copyDescriptors, - hasDevTools: typeof chrome !== "undefined" && chrome && - typeof chrome.loadTimes === "function", isNode: isNode, hasEnvVariables: hasEnvVariables, env: env, global: globalObject, getNativePromise: getNativePromise, - domainBind: domainBind + contextBind: contextBind }; ret.isRecentNode = ret.isNode && (function() { - var version = process.versions.node.split(".").map(Number); + var version; + if (process.versions && process.versions.node) { + version = process.versions.node.split(".").map(Number); + } else if (process.version) { + version = process.version.split(".").map(Number); + } return (version[0] === 0 && version[1] > 10) || (version[0] > 0); })(); +ret.nodeSupportsAsyncResource = ret.isNode && (function() { + var supportsAsync = false; + try { + var res = (__nccwpck_require__(290).AsyncResource); + supportsAsync = typeof res.prototype.runInAsyncScope === "function"; + } catch (e) { + supportsAsync = false; + } + return supportsAsync; +})(); if (ret.isNode) ret.toFastProperties(process); @@ -9467,17115 +9108,35389 @@ module.exports = ret; /***/ }), -/***/ 3717: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var concatMap = __nccwpck_require__(6891); -var balanced = __nccwpck_require__(9417); +/***/ 5481: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -module.exports = expandTop; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. -var escSlash = '\0SLASH'+Math.random()+'\0'; -var escOpen = '\0OPEN'+Math.random()+'\0'; -var escClose = '\0CLOSE'+Math.random()+'\0'; -var escComma = '\0COMMA'+Math.random()+'\0'; -var escPeriod = '\0PERIOD'+Math.random()+'\0'; +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. -function numeric(str) { - return parseInt(str, 10) == str - ? parseInt(str, 10) - : str.charCodeAt(0); +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; } +exports.isArray = isArray; -function escapeBraces(str) { - return str.split('\\\\').join(escSlash) - .split('\\{').join(escOpen) - .split('\\}').join(escClose) - .split('\\,').join(escComma) - .split('\\.').join(escPeriod); +function isBoolean(arg) { + return typeof arg === 'boolean'; } +exports.isBoolean = isBoolean; -function unescapeBraces(str) { - return str.split(escSlash).join('\\') - .split(escOpen).join('{') - .split(escClose).join('}') - .split(escComma).join(',') - .split(escPeriod).join('.'); +function isNull(arg) { + return arg === null; } +exports.isNull = isNull; - -// Basically just str.split(","), but handling cases -// where we have nested braced sections, which should be -// treated as individual members, like {a,{b,c},d} -function parseCommaParts(str) { - if (!str) - return ['']; - - var parts = []; - var m = balanced('{', '}', str); - - if (!m) - return str.split(','); - - var pre = m.pre; - var body = m.body; - var post = m.post; - var p = pre.split(','); - - p[p.length-1] += '{' + body + '}'; - var postParts = parseCommaParts(post); - if (post.length) { - p[p.length-1] += postParts.shift(); - p.push.apply(p, postParts); - } - - parts.push.apply(parts, p); - - return parts; +function isNullOrUndefined(arg) { + return arg == null; } +exports.isNullOrUndefined = isNullOrUndefined; -function expandTop(str) { - if (!str) - return []; - - // I don't know why Bash 4.3 does this, but it does. - // Anything starting with {} will have the first two bytes preserved - // but *only* at the top level, so {},a}b will not expand to anything, - // but a{},b}c will be expanded to [a}c,abc]. - // One could argue that this is a bug in Bash, but since the goal of - // this module is to match Bash's rules, we escape a leading {} - if (str.substr(0, 2) === '{}') { - str = '\\{\\}' + str.substr(2); - } - - return expand(escapeBraces(str), true).map(unescapeBraces); +function isNumber(arg) { + return typeof arg === 'number'; } +exports.isNumber = isNumber; -function identity(e) { - return e; -} +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; -function embrace(str) { - return '{' + str + '}'; +function isSymbol(arg) { + return typeof arg === 'symbol'; } -function isPadded(el) { - return /^-?0\d/.test(el); +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; } +exports.isUndefined = isUndefined; -function lte(i, y) { - return i <= y; +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; } -function gte(i, y) { - return i >= y; +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; } +exports.isObject = isObject; -function expand(str, isTop) { - var expansions = []; +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; - var m = balanced('{', '}', str); - if (!m || /\$$/.test(m.pre)) return [str]; +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; - var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); - var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); - var isSequence = isNumericSequence || isAlphaSequence; - var isOptions = m.body.indexOf(',') >= 0; - if (!isSequence && !isOptions) { - // {a},b} - if (m.post.match(/,.*\}/)) { - str = m.pre + '{' + m.body + escClose + m.post; - return expand(str); - } - return [str]; - } +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; - var n; - if (isSequence) { - n = m.body.split(/\.\./); - } else { - n = parseCommaParts(m.body); - if (n.length === 1) { - // x{{a,b}}y ==> x{a}y x{b}y - n = expand(n[0], false).map(embrace); - if (n.length === 1) { - var post = m.post.length - ? expand(m.post, false) - : ['']; - return post.map(function(p) { - return m.pre + n[0] + p; - }); - } - } - } +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; - // at this point, n is the parts, and we know it's not a comma set - // with a single entry. +exports.isBuffer = __nccwpck_require__(181).Buffer.isBuffer; - // no need to expand pre, since it is guaranteed to be free of brace-sets - var pre = m.pre; - var post = m.post.length - ? expand(m.post, false) - : ['']; +function objectToString(o) { + return Object.prototype.toString.call(o); +} - var N; - if (isSequence) { - var x = numeric(n[0]); - var y = numeric(n[1]); - var width = Math.max(n[0].length, n[1].length) - var incr = n.length == 3 - ? Math.abs(numeric(n[2])) - : 1; - var test = lte; - var reverse = y < x; - if (reverse) { - incr *= -1; - test = gte; - } - var pad = n.some(isPadded); +/***/ }), - N = []; +/***/ 1373: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - for (var i = x; test(i, y); i += incr) { - var c; - if (isAlphaSequence) { - c = String.fromCharCode(i); - if (c === '\\') - c = ''; - } else { - c = String(i); - if (pad) { - var need = width - c.length; - if (need > 0) { - var z = new Array(need + 1).join('0'); - if (i < 0) - c = '-' + z + c.slice(1); - else - c = z + c; - } - } - } - N.push(c); - } - } else { - N = concatMap(n, function(el) { return expand(el, false) }); - } - for (var j = 0; j < N.length; j++) { - for (var k = 0; k < post.length; k++) { - var expansion = pre + N[j] + post[k]; - if (!isTop || isSequence || expansion) - expansions.push(expansion); - } - } +const {Transform, PassThrough} = __nccwpck_require__(2203); +const zlib = __nccwpck_require__(3106); +const mimicResponse = __nccwpck_require__(9382); - return expansions; -} +module.exports = response => { + const contentEncoding = (response.headers['content-encoding'] || '').toLowerCase(); + if (!['gzip', 'deflate', 'br'].includes(contentEncoding)) { + return response; + } + // TODO: Remove this when targeting Node.js 12. + const isBrotli = contentEncoding === 'br'; + if (isBrotli && typeof zlib.createBrotliDecompress !== 'function') { + response.destroy(new Error('Brotli is not supported on Node.js < 12')); + return response; + } -/***/ }), + let isEmpty = true; -/***/ 7329: -/***/ ((__unused_webpack_module, __unused_webpack_exports, __nccwpck_require__) => { + const checker = new Transform({ + transform(data, _encoding, callback) { + isEmpty = false; + callback(null, data); + }, -var initBuffer = __nccwpck_require__(3478); + flush(callback) { + callback(); + } + }); -if (!Buffer.prototype.indexOf) { - Buffer.prototype.indexOf = function (value, offset) { - offset = offset || 0; + const finalStream = new PassThrough({ + autoDestroy: false, + destroy(error, callback) { + response.destroy(); - // Always wrap the input as a Buffer so that this method will support any - // data type such as array octet, string or buffer. - if (typeof value === "string" || value instanceof String) { - value = initBuffer(value); - } else if (typeof value === "number" || value instanceof Number) { - value = initBuffer([ value ]); - } + callback(error); + } + }); - var len = value.length; + const decompressStream = isBrotli ? zlib.createBrotliDecompress() : zlib.createUnzip(); - for (var i = offset; i <= this.length - len; i++) { - var mismatch = false; - for (var j = 0; j < len; j++) { - if (this[i + j] != value[j]) { - mismatch = true; - break; - } - } + decompressStream.once('error', error => { + if (isEmpty && !response.readable) { + finalStream.end(); + return; + } - if (!mismatch) { - return i; - } - } + finalStream.destroy(error); + }); - return -1; - }; -} + mimicResponse(response, finalStream); + response.pipe(checker).pipe(decompressStream).pipe(finalStream); -function bufferLastIndexOf (value, offset) { + return finalStream; +}; - // Always wrap the input as a Buffer so that this method will support any - // data type such as array octet, string or buffer. - if (typeof value === "string" || value instanceof String) { - value = initBuffer(value); - } else if (typeof value === "number" || value instanceof Number) { - value = initBuffer([ value ]); - } - var len = value.length; - offset = offset || this.length - len; +/***/ }), - for (var i = offset; i >= 0; i--) { - var mismatch = false; - for (var j = 0; j < len; j++) { - if (this[i + j] != value[j]) { - mismatch = true; - break; - } - } +/***/ 9382: +/***/ ((module) => { - if (!mismatch) { - return i; - } - } - return -1; -} +// We define these manually to ensure they're always copied +// even if they would move up the prototype chain +// https://nodejs.org/api/http.html#http_class_http_incomingmessage +const knownProperties = [ + 'aborted', + 'complete', + 'headers', + 'httpVersion', + 'httpVersionMinor', + 'httpVersionMajor', + 'method', + 'rawHeaders', + 'rawTrailers', + 'setTimeout', + 'socket', + 'statusCode', + 'statusMessage', + 'trailers', + 'url' +]; -if (Buffer.prototype.lastIndexOf) { - // check Buffer#lastIndexOf is usable: https://github.com/nodejs/node/issues/4604 - if (initBuffer("ABC").lastIndexOf ("ABC") === -1) - Buffer.prototype.lastIndexOf = bufferLastIndexOf; -} else { - Buffer.prototype.lastIndexOf = bufferLastIndexOf; -} +module.exports = (fromStream, toStream) => { + if (toStream._readableState.autoDestroy) { + throw new Error('The second stream must have the `autoDestroy` option set to `false`'); + } + const fromProperties = new Set(Object.keys(fromStream).concat(knownProperties)); -/***/ }), + const properties = {}; -/***/ 3478: -/***/ ((module) => { + for (const property of fromProperties) { + // Don't overwrite existing properties. + if (property in toStream) { + continue; + } -module.exports = function initBuffer(val) { - // assume old version - var nodeVersion = process && process.version ? process.version : "v5.0.0"; - var major = nodeVersion.split(".")[0].replace("v", ""); - return major < 6 - ? new Buffer(val) - : Buffer.from(val); -}; + properties[property] = { + get() { + const value = fromStream[property]; + const isFunction = typeof value === 'function'; -/***/ }), + return isFunction ? value.bind(fromStream) : value; + }, + set(value) { + fromStream[property] = value; + }, + enumerable: true, + configurable: false + }; + } -/***/ 1590: -/***/ ((module) => { + Object.defineProperties(toStream, properties); -module.exports = Buffers; - -function Buffers (bufs) { - if (!(this instanceof Buffers)) return new Buffers(bufs); - this.buffers = bufs || []; - this.length = this.buffers.reduce(function (size, buf) { - return size + buf.length - }, 0); -} - -Buffers.prototype.push = function () { - for (var i = 0; i < arguments.length; i++) { - if (!Buffer.isBuffer(arguments[i])) { - throw new TypeError('Tried to push a non-buffer'); - } - } - - for (var i = 0; i < arguments.length; i++) { - var buf = arguments[i]; - this.buffers.push(buf); - this.length += buf.length; - } - return this.length; -}; - -Buffers.prototype.unshift = function () { - for (var i = 0; i < arguments.length; i++) { - if (!Buffer.isBuffer(arguments[i])) { - throw new TypeError('Tried to unshift a non-buffer'); - } - } - - for (var i = 0; i < arguments.length; i++) { - var buf = arguments[i]; - this.buffers.unshift(buf); - this.length += buf.length; - } - return this.length; -}; - -Buffers.prototype.copy = function (dst, dStart, start, end) { - return this.slice(start, end).copy(dst, dStart, 0, end - start); -}; - -Buffers.prototype.splice = function (i, howMany) { - var buffers = this.buffers; - var index = i >= 0 ? i : this.length - i; - var reps = [].slice.call(arguments, 2); - - if (howMany === undefined) { - howMany = this.length - index; - } - else if (howMany > this.length - index) { - howMany = this.length - index; - } - - for (var i = 0; i < reps.length; i++) { - this.length += reps[i].length; - } - - var removed = new Buffers(); - var bytes = 0; - - var startBytes = 0; - for ( - var ii = 0; - ii < buffers.length && startBytes + buffers[ii].length < index; - ii ++ - ) { startBytes += buffers[ii].length } - - if (index - startBytes > 0) { - var start = index - startBytes; - - if (start + howMany < buffers[ii].length) { - removed.push(buffers[ii].slice(start, start + howMany)); - - var orig = buffers[ii]; - //var buf = new Buffer(orig.length - howMany); - var buf0 = new Buffer(start); - for (var i = 0; i < start; i++) { - buf0[i] = orig[i]; - } - - var buf1 = new Buffer(orig.length - start - howMany); - for (var i = start + howMany; i < orig.length; i++) { - buf1[ i - howMany - start ] = orig[i] - } - - if (reps.length > 0) { - var reps_ = reps.slice(); - reps_.unshift(buf0); - reps_.push(buf1); - buffers.splice.apply(buffers, [ ii, 1 ].concat(reps_)); - ii += reps_.length; - reps = []; - } - else { - buffers.splice(ii, 1, buf0, buf1); - //buffers[ii] = buf; - ii += 2; - } - } - else { - removed.push(buffers[ii].slice(start)); - buffers[ii] = buffers[ii].slice(0, start); - ii ++; - } - } - - if (reps.length > 0) { - buffers.splice.apply(buffers, [ ii, 0 ].concat(reps)); - ii += reps.length; - } - - while (removed.length < howMany) { - var buf = buffers[ii]; - var len = buf.length; - var take = Math.min(len, howMany - removed.length); - - if (take === len) { - removed.push(buf); - buffers.splice(ii, 1); - } - else { - removed.push(buf.slice(0, take)); - buffers[ii] = buffers[ii].slice(take); - } - } - - this.length -= removed.length; - - return removed; -}; - -Buffers.prototype.slice = function (i, j) { - var buffers = this.buffers; - if (j === undefined) j = this.length; - if (i === undefined) i = 0; - - if (j > this.length) j = this.length; - - var startBytes = 0; - for ( - var si = 0; - si < buffers.length && startBytes + buffers[si].length <= i; - si ++ - ) { startBytes += buffers[si].length } - - var target = new Buffer(j - i); - - var ti = 0; - for (var ii = si; ti < j - i && ii < buffers.length; ii++) { - var len = buffers[ii].length; - - var start = ti === 0 ? i - startBytes : 0; - var end = ti + len >= j - i - ? Math.min(start + (j - i) - ti, len) - : len - ; - - buffers[ii].copy(target, ti, start, end); - ti += end - start; - } - - return target; -}; + fromStream.once('aborted', () => { + toStream.destroy(); -Buffers.prototype.pos = function (i) { - if (i < 0 || i >= this.length) throw new Error('oob'); - var l = i, bi = 0, bu = null; - for (;;) { - bu = this.buffers[bi]; - if (l < bu.length) { - return {buf: bi, offset: l}; - } else { - l -= bu.length; - } - bi++; - } -}; + toStream.emit('aborted'); + }); -Buffers.prototype.get = function get (i) { - var pos = this.pos(i); + fromStream.once('close', () => { + if (fromStream.complete) { + if (toStream.readable) { + toStream.once('end', () => { + toStream.emit('close'); + }); + } else { + toStream.emit('close'); + } + } else { + toStream.emit('close'); + } + }); - return this.buffers[pos.buf].get(pos.offset); + return toStream; }; -Buffers.prototype.set = function set (i, b) { - var pos = this.pos(i); - return this.buffers[pos.buf].set(pos.offset, b); -}; +/***/ }), -Buffers.prototype.indexOf = function (needle, offset) { - if ("string" === typeof needle) { - needle = new Buffer(needle); - } else if (needle instanceof Buffer) { - // already a buffer - } else { - throw new Error('Invalid type for a search string'); - } +/***/ 2114: +/***/ ((module, exports) => { - if (!needle.length) { - return 0; - } - if (!this.length) { - return -1; +Object.defineProperty(exports, "__esModule", ({ value: true })); +function isTLSSocket(socket) { + return socket.encrypted; +} +const deferToConnect = (socket, fn) => { + let listeners; + if (typeof fn === 'function') { + const connect = fn; + listeners = { connect }; } - - var i = 0, j = 0, match = 0, mstart, pos = 0; - - // start search from a particular point in the virtual buffer - if (offset) { - var p = this.pos(offset); - i = p.buf; - j = p.offset; - pos = offset; + else { + listeners = fn; } - - // for each character in virtual buffer - for (;;) { - while (j >= this.buffers[i].length) { - j = 0; - i++; - - if (i >= this.buffers.length) { - // search string not found - return -1; - } + const hasConnectListener = typeof listeners.connect === 'function'; + const hasSecureConnectListener = typeof listeners.secureConnect === 'function'; + const hasCloseListener = typeof listeners.close === 'function'; + const onConnect = () => { + if (hasConnectListener) { + listeners.connect(); } - - var char = this.buffers[i][j]; - - if (char == needle[match]) { - // keep track where match started - if (match == 0) { - mstart = { - i: i, - j: j, - pos: pos - }; + if (isTLSSocket(socket) && hasSecureConnectListener) { + if (socket.authorized) { + listeners.secureConnect(); } - match++; - if (match == needle.length) { - // full match - return mstart.pos; + else if (!socket.authorizationError) { + socket.once('secureConnect', listeners.secureConnect); } - } else if (match != 0) { - // a partial match ended, go back to match starting position - // this will continue the search at the next character - i = mstart.i; - j = mstart.j; - pos = mstart.pos; - match = 0; } - - j++; - pos++; + if (hasCloseListener) { + socket.once('close', listeners.close); + } + }; + if (socket.writable && !socket.connecting) { + onConnect(); } -}; - -Buffers.prototype.toBuffer = function() { - return this.slice(); -} - -Buffers.prototype.toString = function(encoding, start, end) { - return this.slice(start, end).toString(encoding); -} + else if (socket.connecting) { + socket.once('connect', onConnect); + } + else if (socket.destroyed && hasCloseListener) { + listeners.close(socket._hadError); + } +}; +exports["default"] = deferToConnect; +// For CommonJS default export support +module.exports = deferToConnect; +module.exports["default"] = deferToConnect; /***/ }), -/***/ 6533: +/***/ 7865: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var Traverse = __nccwpck_require__(8588); -var EventEmitter = (__nccwpck_require__(2361).EventEmitter); - -module.exports = Chainsaw; -function Chainsaw (builder) { - var saw = Chainsaw.saw(builder, {}); - var r = builder.call(saw.handlers, saw); - if (r !== undefined) saw.handlers = r; - saw.record(); - return saw.chain(); -}; - -Chainsaw.light = function ChainsawLight (builder) { - var saw = Chainsaw.saw(builder, {}); - var r = builder.call(saw.handlers, saw); - if (r !== undefined) saw.handlers = r; - return saw.chain(); -}; - -Chainsaw.saw = function (builder, handlers) { - var saw = new EventEmitter; - saw.handlers = handlers; - saw.actions = []; - - saw.chain = function () { - var ch = Traverse(saw.handlers).map(function (node) { - if (this.isRoot) return node; - var ps = this.path; - - if (typeof node === 'function') { - this.update(function () { - saw.actions.push({ - path : ps, - args : [].slice.call(arguments) - }); - return ch; - }); - } - }); - process.nextTick(function () { - saw.emit('begin'); - saw.next(); - }); - return ch; - }; +var stream = __nccwpck_require__(6131); - saw.pop = function () { - return saw.actions.shift(); - }; +function DuplexWrapper(options, writable, readable) { + if (typeof readable === "undefined") { + readable = writable; + writable = options; + options = null; + } - saw.next = function () { - var action = saw.pop(); + stream.Duplex.call(this, options); - if (!action) { - saw.emit('end'); - } - else if (!action.trap) { - var node = saw.handlers; - action.path.forEach(function (key) { node = node[key] }); - node.apply(saw.handlers, action.args); - } - }; + if (typeof readable.read !== "function") { + readable = (new stream.Readable(options)).wrap(readable); + } - saw.nest = function (cb) { - var args = [].slice.call(arguments, 1); - var autonext = true; + this._writable = writable; + this._readable = readable; + this._waiting = false; - if (typeof cb === 'boolean') { - var autonext = cb; - cb = args.shift(); - } + var self = this; - var s = Chainsaw.saw(builder, {}); - var r = builder.call(s.handlers, s); + writable.once("finish", function() { + self.end(); + }); - if (r !== undefined) s.handlers = r; + this.once("finish", function() { + writable.end(); + }); - // If we are recording... - if ("undefined" !== typeof saw.step) { - // ... our children should, too - s.record(); - } + readable.on("readable", function() { + if (self._waiting) { + self._waiting = false; + self._read(); + } + }); - cb.apply(s.chain(), args); - if (autonext !== false) s.on('end', saw.next); - }; + readable.once("end", function() { + self.push(null); + }); - saw.record = function () { - upgradeChainsaw(saw); - }; + if (!options || typeof options.bubbleErrors === "undefined" || options.bubbleErrors) { + writable.on("error", function(err) { + self.emit("error", err); + }); - ['trap', 'down', 'jump'].forEach(function (method) { - saw[method] = function () { - throw new Error("To use the trap, down and jump features, please "+ - "call record() first to start recording actions."); - }; + readable.on("error", function(err) { + self.emit("error", err); }); + } +} - return saw; -}; +DuplexWrapper.prototype = Object.create(stream.Duplex.prototype, {constructor: {value: DuplexWrapper}}); -function upgradeChainsaw(saw) { - saw.step = 0; +DuplexWrapper.prototype._write = function _write(input, encoding, done) { + this._writable.write(input, encoding, done); +}; - // override pop - saw.pop = function () { - return saw.actions[saw.step++]; - }; +DuplexWrapper.prototype._read = function _read() { + var buf; + var reads = 0; + while ((buf = this._readable.read()) !== null) { + this.push(buf); + reads++; + } + if (reads === 0) { + this._waiting = true; + } +}; - saw.trap = function (name, cb) { - var ps = Array.isArray(name) ? name : [name]; - saw.actions.push({ - path : ps, - step : saw.step, - cb : cb, - trap : true - }); - }; +module.exports = function duplex2(options, writable, readable) { + return new DuplexWrapper(options, writable, readable); +}; - saw.down = function (name) { - var ps = (Array.isArray(name) ? name : [name]).join('/'); - var i = saw.actions.slice(saw.step).map(function (x) { - if (x.trap && x.step <= saw.step) return false; - return x.path.join('/') == ps; - }).indexOf(true); +module.exports.DuplexWrapper = DuplexWrapper; - if (i >= 0) saw.step += i; - else saw.step = saw.actions.length; - var act = saw.actions[saw.step - 1]; - if (act && act.trap) { - // It's a trap! - saw.step = act.step; - act.cb(); - } - else saw.next(); - }; +/***/ }), - saw.jump = function (step) { - saw.step = step; - saw.next(); - }; -}; +/***/ 4839: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/***/ }), -/***/ 6891: -/***/ ((module) => { +const fs = __nccwpck_require__(5744) +const path = __nccwpck_require__(6928) +const mkdirsSync = (__nccwpck_require__(1089).mkdirsSync) +const utimesMillisSync = (__nccwpck_require__(6934).utimesMillisSync) +const stat = __nccwpck_require__(887) -module.exports = function (xs, fn) { - var res = []; - for (var i = 0; i < xs.length; i++) { - var x = fn(xs[i], i); - if (isArray(x)) res.push.apply(res, x); - else res.push(x); - } - return res; -}; +function copySync (src, dest, opts) { + if (typeof opts === 'function') { + opts = { filter: opts } + } -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; + opts = opts || {} + opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now + opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber + // Warn about using preserveTimestamps on 32-bit node + if (opts.preserveTimestamps && process.arch === 'ia32') { + process.emitWarning( + 'Using the preserveTimestamps option in 32-bit node is not recommended;\n\n' + + '\tsee https://github.com/jprichardson/node-fs-extra/issues/269', + 'Warning', 'fs-extra-WARN0002' + ) + } -/***/ }), + const { srcStat, destStat } = stat.checkPathsSync(src, dest, 'copy', opts) + stat.checkParentPathsSync(src, srcStat, dest, 'copy') + if (opts.filter && !opts.filter(src, dest)) return + const destParent = path.dirname(dest) + if (!fs.existsSync(destParent)) mkdirsSync(destParent) + return getStats(destStat, src, dest, opts) +} -/***/ 5898: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function getStats (destStat, src, dest, opts) { + const statSync = opts.dereference ? fs.statSync : fs.lstatSync + const srcStat = statSync(src) -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts) + else if (srcStat.isFile() || + srcStat.isCharacterDevice() || + srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts) + else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts) + else if (srcStat.isSocket()) throw new Error(`Cannot copy a socket file: ${src}`) + else if (srcStat.isFIFO()) throw new Error(`Cannot copy a FIFO pipe: ${src}`) + throw new Error(`Unknown file: ${src}`) +} -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. +function onFile (srcStat, destStat, src, dest, opts) { + if (!destStat) return copyFile(srcStat, src, dest, opts) + return mayCopyFile(srcStat, src, dest, opts) +} -function isArray(arg) { - if (Array.isArray) { - return Array.isArray(arg); +function mayCopyFile (srcStat, src, dest, opts) { + if (opts.overwrite) { + fs.unlinkSync(dest) + return copyFile(srcStat, src, dest, opts) + } else if (opts.errorOnExist) { + throw new Error(`'${dest}' already exists`) } - return objectToString(arg) === '[object Array]'; } -exports.isArray = isArray; -function isBoolean(arg) { - return typeof arg === 'boolean'; +function copyFile (srcStat, src, dest, opts) { + fs.copyFileSync(src, dest) + if (opts.preserveTimestamps) handleTimestamps(srcStat.mode, src, dest) + return setDestMode(dest, srcStat.mode) } -exports.isBoolean = isBoolean; -function isNull(arg) { - return arg === null; +function handleTimestamps (srcMode, src, dest) { + // Make sure the file is writable before setting the timestamp + // otherwise open fails with EPERM when invoked with 'r+' + // (through utimes call) + if (fileIsNotWritable(srcMode)) makeFileWritable(dest, srcMode) + return setDestTimestamps(src, dest) } -exports.isNull = isNull; -function isNullOrUndefined(arg) { - return arg == null; +function fileIsNotWritable (srcMode) { + return (srcMode & 0o200) === 0 } -exports.isNullOrUndefined = isNullOrUndefined; -function isNumber(arg) { - return typeof arg === 'number'; +function makeFileWritable (dest, srcMode) { + return setDestMode(dest, srcMode | 0o200) } -exports.isNumber = isNumber; -function isString(arg) { - return typeof arg === 'string'; +function setDestMode (dest, srcMode) { + return fs.chmodSync(dest, srcMode) } -exports.isString = isString; -function isSymbol(arg) { - return typeof arg === 'symbol'; +function setDestTimestamps (src, dest) { + // The initial srcStat.atime cannot be trusted + // because it is modified by the read(2) system call + // (See https://nodejs.org/api/fs.html#fs_stat_time_values) + const updatedSrcStat = fs.statSync(src) + return utimesMillisSync(dest, updatedSrcStat.atime, updatedSrcStat.mtime) } -exports.isSymbol = isSymbol; -function isUndefined(arg) { - return arg === void 0; +function onDir (srcStat, destStat, src, dest, opts) { + if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts) + return copyDir(src, dest, opts) } -exports.isUndefined = isUndefined; -function isRegExp(re) { - return objectToString(re) === '[object RegExp]'; +function mkDirAndCopy (srcMode, src, dest, opts) { + fs.mkdirSync(dest) + copyDir(src, dest, opts) + return setDestMode(dest, srcMode) } -exports.isRegExp = isRegExp; -function isObject(arg) { - return typeof arg === 'object' && arg !== null; +function copyDir (src, dest, opts) { + fs.readdirSync(src).forEach(item => copyDirItem(item, src, dest, opts)) } -exports.isObject = isObject; -function isDate(d) { - return objectToString(d) === '[object Date]'; +function copyDirItem (item, src, dest, opts) { + const srcItem = path.join(src, item) + const destItem = path.join(dest, item) + if (opts.filter && !opts.filter(srcItem, destItem)) return + const { destStat } = stat.checkPathsSync(srcItem, destItem, 'copy', opts) + return getStats(destStat, srcItem, destItem, opts) } -exports.isDate = isDate; -function isError(e) { - return (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; +function onLink (destStat, src, dest, opts) { + let resolvedSrc = fs.readlinkSync(src) + if (opts.dereference) { + resolvedSrc = path.resolve(process.cwd(), resolvedSrc) + } -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; + if (!destStat) { + return fs.symlinkSync(resolvedSrc, dest) + } else { + let resolvedDest + try { + resolvedDest = fs.readlinkSync(dest) + } catch (err) { + // dest exists and is a regular file or directory, + // Windows may throw UNKNOWN error. If dest already exists, + // fs throws error anyway, so no need to guard against it here. + if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlinkSync(resolvedSrc, dest) + throw err + } + if (opts.dereference) { + resolvedDest = path.resolve(process.cwd(), resolvedDest) + } + if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { + throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`) + } -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; + // prevent copy if src is a subdir of dest since unlinking + // dest in this case would result in removing src contents + // and therefore a broken symlink would be created. + if (stat.isSrcSubdir(resolvedDest, resolvedSrc)) { + throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`) + } + return copyLink(resolvedSrc, dest) + } } -exports.isPrimitive = isPrimitive; -exports.isBuffer = __nccwpck_require__(4300).Buffer.isBuffer; - -function objectToString(o) { - return Object.prototype.toString.call(o); +function copyLink (resolvedSrc, dest) { + fs.unlinkSync(dest) + return fs.symlinkSync(resolvedSrc, dest) } +module.exports = copySync + /***/ }), -/***/ 2391: +/***/ 1759: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const {Transform, PassThrough} = __nccwpck_require__(2781); -const zlib = __nccwpck_require__(9796); -const mimicResponse = __nccwpck_require__(3877); -module.exports = response => { - const contentEncoding = (response.headers['content-encoding'] || '').toLowerCase(); +const fs = __nccwpck_require__(3506) +const path = __nccwpck_require__(6928) +const { mkdirs } = __nccwpck_require__(1089) +const { pathExists } = __nccwpck_require__(2881) +const { utimesMillis } = __nccwpck_require__(6934) +const stat = __nccwpck_require__(887) - if (!['gzip', 'deflate', 'br'].includes(contentEncoding)) { - return response; - } +async function copy (src, dest, opts = {}) { + if (typeof opts === 'function') { + opts = { filter: opts } + } - // TODO: Remove this when targeting Node.js 12. - const isBrotli = contentEncoding === 'br'; - if (isBrotli && typeof zlib.createBrotliDecompress !== 'function') { - response.destroy(new Error('Brotli is not supported on Node.js < 12')); - return response; - } + opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now + opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber - let isEmpty = true; + // Warn about using preserveTimestamps on 32-bit node + if (opts.preserveTimestamps && process.arch === 'ia32') { + process.emitWarning( + 'Using the preserveTimestamps option in 32-bit node is not recommended;\n\n' + + '\tsee https://github.com/jprichardson/node-fs-extra/issues/269', + 'Warning', 'fs-extra-WARN0001' + ) + } - const checker = new Transform({ - transform(data, _encoding, callback) { - isEmpty = false; + const { srcStat, destStat } = await stat.checkPaths(src, dest, 'copy', opts) - callback(null, data); - }, + await stat.checkParentPaths(src, srcStat, dest, 'copy') - flush(callback) { - callback(); - } - }); + const include = await runFilter(src, dest, opts) - const finalStream = new PassThrough({ - autoDestroy: false, - destroy(error, callback) { - response.destroy(); + if (!include) return - callback(error); - } - }); + // check if the parent of dest exists, and create it if it doesn't exist + const destParent = path.dirname(dest) + const dirExists = await pathExists(destParent) + if (!dirExists) { + await mkdirs(destParent) + } - const decompressStream = isBrotli ? zlib.createBrotliDecompress() : zlib.createUnzip(); + await getStatsAndPerformCopy(destStat, src, dest, opts) +} - decompressStream.once('error', error => { - if (isEmpty && !response.readable) { - finalStream.end(); - return; - } +async function runFilter (src, dest, opts) { + if (!opts.filter) return true + return opts.filter(src, dest) +} - finalStream.destroy(error); - }); +async function getStatsAndPerformCopy (destStat, src, dest, opts) { + const statFn = opts.dereference ? fs.stat : fs.lstat + const srcStat = await statFn(src) - mimicResponse(response, finalStream); - response.pipe(checker).pipe(decompressStream).pipe(finalStream); + if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts) - return finalStream; -}; + if ( + srcStat.isFile() || + srcStat.isCharacterDevice() || + srcStat.isBlockDevice() + ) return onFile(srcStat, destStat, src, dest, opts) + if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts) + if (srcStat.isSocket()) throw new Error(`Cannot copy a socket file: ${src}`) + if (srcStat.isFIFO()) throw new Error(`Cannot copy a FIFO pipe: ${src}`) + throw new Error(`Unknown file: ${src}`) +} -/***/ }), +async function onFile (srcStat, destStat, src, dest, opts) { + if (!destStat) return copyFile(srcStat, src, dest, opts) -/***/ 3877: -/***/ ((module) => { + if (opts.overwrite) { + await fs.unlink(dest) + return copyFile(srcStat, src, dest, opts) + } + if (opts.errorOnExist) { + throw new Error(`'${dest}' already exists`) + } +} +async function copyFile (srcStat, src, dest, opts) { + await fs.copyFile(src, dest) + if (opts.preserveTimestamps) { + // Make sure the file is writable before setting the timestamp + // otherwise open fails with EPERM when invoked with 'r+' + // (through utimes call) + if (fileIsNotWritable(srcStat.mode)) { + await makeFileWritable(dest, srcStat.mode) + } + // Set timestamps and mode correspondingly -// We define these manually to ensure they're always copied -// even if they would move up the prototype chain -// https://nodejs.org/api/http.html#http_class_http_incomingmessage -const knownProperties = [ - 'aborted', - 'complete', - 'headers', - 'httpVersion', - 'httpVersionMinor', - 'httpVersionMajor', - 'method', - 'rawHeaders', - 'rawTrailers', - 'setTimeout', - 'socket', - 'statusCode', - 'statusMessage', - 'trailers', - 'url' -]; - -module.exports = (fromStream, toStream) => { - if (toStream._readableState.autoDestroy) { - throw new Error('The second stream must have the `autoDestroy` option set to `false`'); - } - - const fromProperties = new Set(Object.keys(fromStream).concat(knownProperties)); + // Note that The initial srcStat.atime cannot be trusted + // because it is modified by the read(2) system call + // (See https://nodejs.org/api/fs.html#fs_stat_time_values) + const updatedSrcStat = await fs.stat(src) + await utimesMillis(dest, updatedSrcStat.atime, updatedSrcStat.mtime) + } - const properties = {}; + return fs.chmod(dest, srcStat.mode) +} - for (const property of fromProperties) { - // Don't overwrite existing properties. - if (property in toStream) { - continue; - } +function fileIsNotWritable (srcMode) { + return (srcMode & 0o200) === 0 +} - properties[property] = { - get() { - const value = fromStream[property]; - const isFunction = typeof value === 'function'; +function makeFileWritable (dest, srcMode) { + return fs.chmod(dest, srcMode | 0o200) +} - return isFunction ? value.bind(fromStream) : value; - }, - set(value) { - fromStream[property] = value; - }, - enumerable: true, - configurable: false - }; - } +async function onDir (srcStat, destStat, src, dest, opts) { + // the dest directory might not exist, create it + if (!destStat) { + await fs.mkdir(dest) + } - Object.defineProperties(toStream, properties); + const items = await fs.readdir(src) - fromStream.once('aborted', () => { - toStream.destroy(); + // loop through the files in the current directory to copy everything + await Promise.all(items.map(async item => { + const srcItem = path.join(src, item) + const destItem = path.join(dest, item) - toStream.emit('aborted'); - }); + // skip the item if it is matches by the filter function + const include = await runFilter(srcItem, destItem, opts) + if (!include) return - fromStream.once('close', () => { - if (fromStream.complete) { - if (toStream.readable) { - toStream.once('end', () => { - toStream.emit('close'); - }); - } else { - toStream.emit('close'); - } - } else { - toStream.emit('close'); - } - }); + const { destStat } = await stat.checkPaths(srcItem, destItem, 'copy', opts) - return toStream; -}; + // If the item is a copyable file, `getStatsAndPerformCopy` will copy it + // If the item is a directory, `getStatsAndPerformCopy` will call `onDir` recursively + return getStatsAndPerformCopy(destStat, srcItem, destItem, opts) + })) + if (!destStat) { + await fs.chmod(dest, srcStat.mode) + } +} -/***/ }), +async function onLink (destStat, src, dest, opts) { + let resolvedSrc = await fs.readlink(src) + if (opts.dereference) { + resolvedSrc = path.resolve(process.cwd(), resolvedSrc) + } + if (!destStat) { + return fs.symlink(resolvedSrc, dest) + } -/***/ 6214: -/***/ ((module, exports) => { + let resolvedDest = null + try { + resolvedDest = await fs.readlink(dest) + } catch (e) { + // dest exists and is a regular file or directory, + // Windows may throw UNKNOWN error. If dest already exists, + // fs throws error anyway, so no need to guard against it here. + if (e.code === 'EINVAL' || e.code === 'UNKNOWN') return fs.symlink(resolvedSrc, dest) + throw e + } + if (opts.dereference) { + resolvedDest = path.resolve(process.cwd(), resolvedDest) + } + if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { + throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`) + } + // do not copy if src is a subdir of dest since unlinking + // dest in this case would result in removing src contents + // and therefore a broken symlink would be created. + if (stat.isSrcSubdir(resolvedDest, resolvedSrc)) { + throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`) + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -function isTLSSocket(socket) { - return socket.encrypted; + // copy the link + await fs.unlink(dest) + return fs.symlink(resolvedSrc, dest) } -const deferToConnect = (socket, fn) => { - let listeners; - if (typeof fn === 'function') { - const connect = fn; - listeners = { connect }; - } - else { - listeners = fn; - } - const hasConnectListener = typeof listeners.connect === 'function'; - const hasSecureConnectListener = typeof listeners.secureConnect === 'function'; - const hasCloseListener = typeof listeners.close === 'function'; - const onConnect = () => { - if (hasConnectListener) { - listeners.connect(); - } - if (isTLSSocket(socket) && hasSecureConnectListener) { - if (socket.authorized) { - listeners.secureConnect(); - } - else if (!socket.authorizationError) { - socket.once('secureConnect', listeners.secureConnect); - } - } - if (hasCloseListener) { - socket.once('close', listeners.close); - } - }; - if (socket.writable && !socket.connecting) { - onConnect(); - } - else if (socket.connecting) { - socket.once('connect', onConnect); - } - else if (socket.destroyed && hasCloseListener) { - listeners.close(socket._hadError); - } -}; -exports["default"] = deferToConnect; -// For CommonJS default export support -module.exports = deferToConnect; -module.exports["default"] = deferToConnect; + +module.exports = copy /***/ }), -/***/ 1932: +/***/ 5796: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var stream = __nccwpck_require__(1642); - -function DuplexWrapper(options, writable, readable) { - if (typeof readable === "undefined") { - readable = writable; - writable = options; - options = null; - } - - stream.Duplex.call(this, options); +const u = (__nccwpck_require__(5077).fromPromise) +module.exports = { + copy: u(__nccwpck_require__(1759)), + copySync: __nccwpck_require__(4839) +} - if (typeof readable.read !== "function") { - readable = (new stream.Readable(options)).wrap(readable); - } - this._writable = writable; - this._readable = readable; - this._waiting = false; +/***/ }), - var self = this; +/***/ 7882: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - writable.once("finish", function() { - self.end(); - }); - this.once("finish", function() { - writable.end(); - }); - readable.on("readable", function() { - if (self._waiting) { - self._waiting = false; - self._read(); - } - }); +const u = (__nccwpck_require__(5077).fromPromise) +const fs = __nccwpck_require__(3506) +const path = __nccwpck_require__(6928) +const mkdir = __nccwpck_require__(1089) +const remove = __nccwpck_require__(6205) - readable.once("end", function() { - self.push(null); - }); +const emptyDir = u(async function emptyDir (dir) { + let items + try { + items = await fs.readdir(dir) + } catch { + return mkdir.mkdirs(dir) + } - if (!options || typeof options.bubbleErrors === "undefined" || options.bubbleErrors) { - writable.on("error", function(err) { - self.emit("error", err); - }); + return Promise.all(items.map(item => remove.remove(path.join(dir, item)))) +}) - readable.on("error", function(err) { - self.emit("error", err); - }); +function emptyDirSync (dir) { + let items + try { + items = fs.readdirSync(dir) + } catch { + return mkdir.mkdirsSync(dir) } + + items.forEach(item => { + item = path.join(dir, item) + remove.removeSync(item) + }) } -DuplexWrapper.prototype = Object.create(stream.Duplex.prototype, {constructor: {value: DuplexWrapper}}); +module.exports = { + emptyDirSync, + emptydirSync: emptyDirSync, + emptyDir, + emptydir: emptyDir +} -DuplexWrapper.prototype._write = function _write(input, encoding, done) { - this._writable.write(input, encoding, done); -}; -DuplexWrapper.prototype._read = function _read() { - var buf; - var reads = 0; - while ((buf = this._readable.read()) !== null) { - this.push(buf); - reads++; - } - if (reads === 0) { - this._waiting = true; - } -}; +/***/ }), -module.exports = function duplex2(options, writable, readable) { - return new DuplexWrapper(options, writable, readable); -}; +/***/ 3529: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -module.exports.DuplexWrapper = DuplexWrapper; -/***/ }), +const u = (__nccwpck_require__(5077).fromPromise) +const path = __nccwpck_require__(6928) +const fs = __nccwpck_require__(3506) +const mkdir = __nccwpck_require__(1089) -/***/ 6863: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +async function createFile (file) { + let stats + try { + stats = await fs.stat(file) + } catch { } + if (stats && stats.isFile()) return -module.exports = realpath -realpath.realpath = realpath -realpath.sync = realpathSync -realpath.realpathSync = realpathSync -realpath.monkeypatch = monkeypatch -realpath.unmonkeypatch = unmonkeypatch - -var fs = __nccwpck_require__(7147) -var origRealpath = fs.realpath -var origRealpathSync = fs.realpathSync - -var version = process.version -var ok = /^v[0-5]\./.test(version) -var old = __nccwpck_require__(1734) - -function newError (er) { - return er && er.syscall === 'realpath' && ( - er.code === 'ELOOP' || - er.code === 'ENOMEM' || - er.code === 'ENAMETOOLONG' - ) -} + const dir = path.dirname(file) -function realpath (p, cache, cb) { - if (ok) { - return origRealpath(p, cache, cb) + let dirStats = null + try { + dirStats = await fs.stat(dir) + } catch (err) { + // if the directory doesn't exist, make it + if (err.code === 'ENOENT') { + await mkdir.mkdirs(dir) + await fs.writeFile(file, '') + return + } else { + throw err + } } - if (typeof cache === 'function') { - cb = cache - cache = null + if (dirStats.isDirectory()) { + await fs.writeFile(file, '') + } else { + // parent is not a directory + // This is just to cause an internal ENOTDIR error to be thrown + await fs.readdir(dir) } - origRealpath(p, cache, function (er, result) { - if (newError(er)) { - old.realpath(p, cache, cb) - } else { - cb(er, result) - } - }) } -function realpathSync (p, cache) { - if (ok) { - return origRealpathSync(p, cache) - } +function createFileSync (file) { + let stats + try { + stats = fs.statSync(file) + } catch { } + if (stats && stats.isFile()) return + const dir = path.dirname(file) try { - return origRealpathSync(p, cache) - } catch (er) { - if (newError(er)) { - return old.realpathSync(p, cache) - } else { - throw er + if (!fs.statSync(dir).isDirectory()) { + // parent is not a directory + // This is just to cause an internal ENOTDIR error to be thrown + fs.readdirSync(dir) } + } catch (err) { + // If the stat call above failed because the directory doesn't exist, create it + if (err && err.code === 'ENOENT') mkdir.mkdirsSync(dir) + else throw err } -} -function monkeypatch () { - fs.realpath = realpath - fs.realpathSync = realpathSync + fs.writeFileSync(file, '') } -function unmonkeypatch () { - fs.realpath = origRealpath - fs.realpathSync = origRealpathSync +module.exports = { + createFile: u(createFile), + createFileSync } /***/ }), -/***/ 1734: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 5779: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -var pathModule = __nccwpck_require__(1017); -var isWindows = process.platform === 'win32'; -var fs = __nccwpck_require__(7147); -// JavaScript implementation of realpath, ported from node pre-v6 +const { createFile, createFileSync } = __nccwpck_require__(3529) +const { createLink, createLinkSync } = __nccwpck_require__(8751) +const { createSymlink, createSymlinkSync } = __nccwpck_require__(4896) -var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); +module.exports = { + // file + createFile, + createFileSync, + ensureFile: createFile, + ensureFileSync: createFileSync, + // link + createLink, + createLinkSync, + ensureLink: createLink, + ensureLinkSync: createLinkSync, + // symlink + createSymlink, + createSymlinkSync, + ensureSymlink: createSymlink, + ensureSymlinkSync: createSymlinkSync +} -function rethrow() { - // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and - // is fairly slow to generate. - var callback; - if (DEBUG) { - var backtrace = new Error; - callback = debugCallback; - } else - callback = missingCallback; - return callback; +/***/ }), - function debugCallback(err) { - if (err) { - backtrace.message = err.message; - err = backtrace; - missingCallback(err); - } +/***/ 8751: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const u = (__nccwpck_require__(5077).fromPromise) +const path = __nccwpck_require__(6928) +const fs = __nccwpck_require__(3506) +const mkdir = __nccwpck_require__(1089) +const { pathExists } = __nccwpck_require__(2881) +const { areIdentical } = __nccwpck_require__(887) + +async function createLink (srcpath, dstpath) { + let dstStat + try { + dstStat = await fs.lstat(dstpath) + } catch { + // ignore error } - function missingCallback(err) { - if (err) { - if (process.throwDeprecation) - throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs - else if (!process.noDeprecation) { - var msg = 'fs: missing callback ' + (err.stack || err.message); - if (process.traceDeprecation) - console.trace(msg); - else - console.error(msg); - } - } + let srcStat + try { + srcStat = await fs.lstat(srcpath) + } catch (err) { + err.message = err.message.replace('lstat', 'ensureLink') + throw err } -} -function maybeCallback(cb) { - return typeof cb === 'function' ? cb : rethrow(); -} + if (dstStat && areIdentical(srcStat, dstStat)) return -var normalize = pathModule.normalize; + const dir = path.dirname(dstpath) -// Regexp that finds the next partion of a (partial) path -// result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] -if (isWindows) { - var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; -} else { - var nextPartRe = /(.*?)(?:[\/]+|$)/g; + const dirExists = await pathExists(dir) + + if (!dirExists) { + await mkdir.mkdirs(dir) + } + + await fs.link(srcpath, dstpath) } -// Regex to find the device root, including trailing slash. E.g. 'c:\\'. -if (isWindows) { - var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; -} else { - var splitRootRe = /^[\/]*/; -} - -exports.realpathSync = function realpathSync(p, cache) { - // make p is absolute - p = pathModule.resolve(p); +function createLinkSync (srcpath, dstpath) { + let dstStat + try { + dstStat = fs.lstatSync(dstpath) + } catch {} - if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { - return cache[p]; + try { + const srcStat = fs.lstatSync(srcpath) + if (dstStat && areIdentical(srcStat, dstStat)) return + } catch (err) { + err.message = err.message.replace('lstat', 'ensureLink') + throw err } - var original = p, - seenLinks = {}, - knownHard = {}; - - // current character position in p - var pos; - // the partial path so far, including a trailing slash if any - var current; - // the partial path without a trailing slash (except when pointing at a root) - var base; - // the partial path scanned in the previous round, with slash - var previous; - - start(); - - function start() { - // Skip over roots - var m = splitRootRe.exec(p); - pos = m[0].length; - current = m[0]; - base = m[0]; - previous = ''; + const dir = path.dirname(dstpath) + const dirExists = fs.existsSync(dir) + if (dirExists) return fs.linkSync(srcpath, dstpath) + mkdir.mkdirsSync(dir) - // On windows, check that the root exists. On unix there is no need. - if (isWindows && !knownHard[base]) { - fs.lstatSync(base); - knownHard[base] = true; - } - } + return fs.linkSync(srcpath, dstpath) +} - // walk down the path, swapping out linked pathparts for their real - // values - // NB: p.length changes. - while (pos < p.length) { - // find the next part - nextPartRe.lastIndex = pos; - var result = nextPartRe.exec(p); - previous = current; - current += result[0]; - base = previous + result[1]; - pos = nextPartRe.lastIndex; +module.exports = { + createLink: u(createLink), + createLinkSync +} - // continue if not a symlink - if (knownHard[base] || (cache && cache[base] === base)) { - continue; - } - var resolvedLink; - if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { - // some known symbolic link. no need to stat again. - resolvedLink = cache[base]; - } else { - var stat = fs.lstatSync(base); - if (!stat.isSymbolicLink()) { - knownHard[base] = true; - if (cache) cache[base] = base; - continue; - } +/***/ }), - // read the link if it wasn't read before - // dev/ino always return 0 on windows, so skip the check. - var linkTarget = null; - if (!isWindows) { - var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); - if (seenLinks.hasOwnProperty(id)) { - linkTarget = seenLinks[id]; - } - } - if (linkTarget === null) { - fs.statSync(base); - linkTarget = fs.readlinkSync(base); - } - resolvedLink = pathModule.resolve(previous, linkTarget); - // track this, if given a cache. - if (cache) cache[base] = resolvedLink; - if (!isWindows) seenLinks[id] = linkTarget; - } +/***/ 3121: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // resolve the link, then start over - p = pathModule.resolve(resolvedLink, p.slice(pos)); - start(); - } - if (cache) cache[original] = p; - return p; -}; +const path = __nccwpck_require__(6928) +const fs = __nccwpck_require__(3506) +const { pathExists } = __nccwpck_require__(2881) +const u = (__nccwpck_require__(5077).fromPromise) -exports.realpath = function realpath(p, cache, cb) { - if (typeof cb !== 'function') { - cb = maybeCallback(cache); - cache = null; - } +/** + * Function that returns two types of paths, one relative to symlink, and one + * relative to the current working directory. Checks if path is absolute or + * relative. If the path is relative, this function checks if the path is + * relative to symlink or relative to current working directory. This is an + * initiative to find a smarter `srcpath` to supply when building symlinks. + * This allows you to determine which path to use out of one of three possible + * types of source paths. The first is an absolute path. This is detected by + * `path.isAbsolute()`. When an absolute path is provided, it is checked to + * see if it exists. If it does it's used, if not an error is returned + * (callback)/ thrown (sync). The other two options for `srcpath` are a + * relative url. By default Node's `fs.symlink` works by creating a symlink + * using `dstpath` and expects the `srcpath` to be relative to the newly + * created symlink. If you provide a `srcpath` that does not exist on the file + * system it results in a broken symlink. To minimize this, the function + * checks to see if the 'relative to symlink' source file exists, and if it + * does it will use it. If it does not, it checks if there's a file that + * exists that is relative to the current working directory, if does its used. + * This preserves the expectations of the original fs.symlink spec and adds + * the ability to pass in `relative to current working direcotry` paths. + */ - // make p is absolute - p = pathModule.resolve(p); +async function symlinkPaths (srcpath, dstpath) { + if (path.isAbsolute(srcpath)) { + try { + await fs.lstat(srcpath) + } catch (err) { + err.message = err.message.replace('lstat', 'ensureSymlink') + throw err + } - if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { - return process.nextTick(cb.bind(null, null, cache[p])); + return { + toCwd: srcpath, + toDst: srcpath + } } - var original = p, - seenLinks = {}, - knownHard = {}; + const dstdir = path.dirname(dstpath) + const relativeToDst = path.join(dstdir, srcpath) - // current character position in p - var pos; - // the partial path so far, including a trailing slash if any - var current; - // the partial path without a trailing slash (except when pointing at a root) - var base; - // the partial path scanned in the previous round, with slash - var previous; - - start(); - - function start() { - // Skip over roots - var m = splitRootRe.exec(p); - pos = m[0].length; - current = m[0]; - base = m[0]; - previous = ''; - - // On windows, check that the root exists. On unix there is no need. - if (isWindows && !knownHard[base]) { - fs.lstat(base, function(err) { - if (err) return cb(err); - knownHard[base] = true; - LOOP(); - }); - } else { - process.nextTick(LOOP); + const exists = await pathExists(relativeToDst) + if (exists) { + return { + toCwd: relativeToDst, + toDst: srcpath } } - // walk down the path, swapping out linked pathparts for their real - // values - function LOOP() { - // stop if scanned past end of path - if (pos >= p.length) { - if (cache) cache[original] = p; - return cb(null, p); - } + try { + await fs.lstat(srcpath) + } catch (err) { + err.message = err.message.replace('lstat', 'ensureSymlink') + throw err + } - // find the next part - nextPartRe.lastIndex = pos; - var result = nextPartRe.exec(p); - previous = current; - current += result[0]; - base = previous + result[1]; - pos = nextPartRe.lastIndex; + return { + toCwd: srcpath, + toDst: path.relative(dstdir, srcpath) + } +} - // continue if not a symlink - if (knownHard[base] || (cache && cache[base] === base)) { - return process.nextTick(LOOP); +function symlinkPathsSync (srcpath, dstpath) { + if (path.isAbsolute(srcpath)) { + const exists = fs.existsSync(srcpath) + if (!exists) throw new Error('absolute srcpath does not exist') + return { + toCwd: srcpath, + toDst: srcpath } + } - if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { - // known symbolic link. no need to stat again. - return gotResolvedLink(cache[base]); + const dstdir = path.dirname(dstpath) + const relativeToDst = path.join(dstdir, srcpath) + const exists = fs.existsSync(relativeToDst) + if (exists) { + return { + toCwd: relativeToDst, + toDst: srcpath } - - return fs.lstat(base, gotStat); } - function gotStat(err, stat) { - if (err) return cb(err); - - // if not a symlink, skip to the next path part - if (!stat.isSymbolicLink()) { - knownHard[base] = true; - if (cache) cache[base] = base; - return process.nextTick(LOOP); - } + const srcExists = fs.existsSync(srcpath) + if (!srcExists) throw new Error('relative srcpath does not exist') + return { + toCwd: srcpath, + toDst: path.relative(dstdir, srcpath) + } +} - // stat & read the link if not read before - // call gotTarget as soon as the link target is known - // dev/ino always return 0 on windows, so skip the check. - if (!isWindows) { - var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); - if (seenLinks.hasOwnProperty(id)) { - return gotTarget(null, seenLinks[id], base); - } - } - fs.stat(base, function(err) { - if (err) return cb(err); +module.exports = { + symlinkPaths: u(symlinkPaths), + symlinkPathsSync +} - fs.readlink(base, function(err, target) { - if (!isWindows) seenLinks[id] = target; - gotTarget(err, target); - }); - }); - } - function gotTarget(err, target, base) { - if (err) return cb(err); +/***/ }), - var resolvedLink = pathModule.resolve(previous, target); - if (cache) cache[base] = resolvedLink; - gotResolvedLink(resolvedLink); - } +/***/ 7045: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function gotResolvedLink(resolvedLink) { - // resolve the link, then start over - p = pathModule.resolve(resolvedLink, p.slice(pos)); - start(); - } -}; -/***/ }), +const fs = __nccwpck_require__(3506) +const u = (__nccwpck_require__(5077).fromPromise) -/***/ 7158: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +async function symlinkType (srcpath, type) { + if (type) return type -var __webpack_unused_export__; -/* unused reexport */ __nccwpck_require__(9479) -/* unused reexport */ __nccwpck_require__(3284) -exports.Writer = __nccwpck_require__(8680) + let stats + try { + stats = await fs.lstat(srcpath) + } catch { + return 'file' + } -exports.$B = { - Reader: __nccwpck_require__(8413), - Writer: __nccwpck_require__(2539) + return (stats && stats.isDirectory()) ? 'dir' : 'file' } -exports.Lv = { - Reader: __nccwpck_require__(4486), - Writer: __nccwpck_require__(4745) -} +function symlinkTypeSync (srcpath, type) { + if (type) return type -exports.rU = { - Reader: __nccwpck_require__(8337), - Writer: __nccwpck_require__(404) + let stats + try { + stats = fs.lstatSync(srcpath) + } catch { + return 'file' + } + return (stats && stats.isDirectory()) ? 'dir' : 'file' } -exports._S = { - Reader: __nccwpck_require__(7328), - Writer: __nccwpck_require__(2071) +module.exports = { + symlinkType: u(symlinkType), + symlinkTypeSync } -__webpack_unused_export__ = __webpack_unused_export__ = exports.Lv.Reader -__webpack_unused_export__ = __webpack_unused_export__ = exports.$B.Reader -__webpack_unused_export__ = __webpack_unused_export__ = exports.rU.Reader -__webpack_unused_export__ = __webpack_unused_export__ = exports._S.Reader -exports.Writer.Dir = __webpack_unused_export__ = exports.Lv.Writer -exports.Writer.File = __webpack_unused_export__ = exports.$B.Writer -exports.Writer.Link = __webpack_unused_export__ = exports.rU.Writer -exports.Writer.Proxy = __webpack_unused_export__ = exports._S.Writer +/***/ }), -/* unused reexport */ __nccwpck_require__(3317) +/***/ 4896: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/***/ }), -/***/ 9479: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const u = (__nccwpck_require__(5077).fromPromise) +const path = __nccwpck_require__(6928) +const fs = __nccwpck_require__(3506) -// the parent class for all fstreams. +const { mkdirs, mkdirsSync } = __nccwpck_require__(1089) -module.exports = Abstract +const { symlinkPaths, symlinkPathsSync } = __nccwpck_require__(3121) +const { symlinkType, symlinkTypeSync } = __nccwpck_require__(7045) -var Stream = (__nccwpck_require__(2781).Stream) -var inherits = __nccwpck_require__(4124) +const { pathExists } = __nccwpck_require__(2881) -function Abstract () { - Stream.call(this) -} +const { areIdentical } = __nccwpck_require__(887) -inherits(Abstract, Stream) +async function createSymlink (srcpath, dstpath, type) { + let stats + try { + stats = await fs.lstat(dstpath) + } catch { } -Abstract.prototype.on = function (ev, fn) { - if (ev === 'ready' && this.ready) { - process.nextTick(fn.bind(this)) - } else { - Stream.prototype.on.call(this, ev, fn) - } - return this -} - -Abstract.prototype.abort = function () { - this._aborted = true - this.emit('abort') -} - -Abstract.prototype.destroy = function () {} - -Abstract.prototype.warn = function (msg, code) { - var self = this - var er = decorate(msg, code, self) - if (!self.listeners('warn')) { - console.error('%s %s\n' + - 'path = %s\n' + - 'syscall = %s\n' + - 'fstream_type = %s\n' + - 'fstream_path = %s\n' + - 'fstream_unc_path = %s\n' + - 'fstream_class = %s\n' + - 'fstream_stack =\n%s\n', - code || 'UNKNOWN', - er.stack, - er.path, - er.syscall, - er.fstream_type, - er.fstream_path, - er.fstream_unc_path, - er.fstream_class, - er.fstream_stack.join('\n')) - } else { - self.emit('warn', er) + if (stats && stats.isSymbolicLink()) { + const [srcStat, dstStat] = await Promise.all([ + fs.stat(srcpath), + fs.stat(dstpath) + ]) + + if (areIdentical(srcStat, dstStat)) return } -} -Abstract.prototype.info = function (msg, code) { - this.emit('info', msg, code) -} + const relative = await symlinkPaths(srcpath, dstpath) + srcpath = relative.toDst + const toType = await symlinkType(relative.toCwd, type) + const dir = path.dirname(dstpath) -Abstract.prototype.error = function (msg, code, th) { - var er = decorate(msg, code, this) - if (th) throw er - else this.emit('error', er) + if (!(await pathExists(dir))) { + await mkdirs(dir) + } + + return fs.symlink(srcpath, dstpath, toType) } -function decorate (er, code, self) { - if (!(er instanceof Error)) er = new Error(er) - er.code = er.code || code - er.path = er.path || self.path - er.fstream_type = er.fstream_type || self.type - er.fstream_path = er.fstream_path || self.path - if (self._path !== self.path) { - er.fstream_unc_path = er.fstream_unc_path || self._path - } - if (self.linkpath) { - er.fstream_linkpath = er.fstream_linkpath || self.linkpath +function createSymlinkSync (srcpath, dstpath, type) { + let stats + try { + stats = fs.lstatSync(dstpath) + } catch { } + if (stats && stats.isSymbolicLink()) { + const srcStat = fs.statSync(srcpath) + const dstStat = fs.statSync(dstpath) + if (areIdentical(srcStat, dstStat)) return } - er.fstream_class = er.fstream_class || self.constructor.name - er.fstream_stack = er.fstream_stack || - new Error().stack.split(/\n/).slice(3).map(function (s) { - return s.replace(/^ {4}at /, '') - }) - return er + const relative = symlinkPathsSync(srcpath, dstpath) + srcpath = relative.toDst + type = symlinkTypeSync(relative.toCwd, type) + const dir = path.dirname(dstpath) + const exists = fs.existsSync(dir) + if (exists) return fs.symlinkSync(srcpath, dstpath, type) + mkdirsSync(dir) + return fs.symlinkSync(srcpath, dstpath, type) +} + +module.exports = { + createSymlink: u(createSymlink), + createSymlinkSync } /***/ }), -/***/ 3317: -/***/ ((module) => { +/***/ 3506: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -module.exports = collect -function collect (stream) { - if (stream._collected) return +// This is adapted from https://github.com/normalize/mz +// Copyright (c) 2014-2016 Jonathan Ong me@jongleberry.com and Contributors +const u = (__nccwpck_require__(5077).fromCallback) +const fs = __nccwpck_require__(5744) + +const api = [ + 'access', + 'appendFile', + 'chmod', + 'chown', + 'close', + 'copyFile', + 'fchmod', + 'fchown', + 'fdatasync', + 'fstat', + 'fsync', + 'ftruncate', + 'futimes', + 'lchmod', + 'lchown', + 'link', + 'lstat', + 'mkdir', + 'mkdtemp', + 'open', + 'opendir', + 'readdir', + 'readFile', + 'readlink', + 'realpath', + 'rename', + 'rm', + 'rmdir', + 'stat', + 'symlink', + 'truncate', + 'unlink', + 'utimes', + 'writeFile' +].filter(key => { + // Some commands are not available on some systems. Ex: + // fs.cp was added in Node.js v16.7.0 + // fs.lchown is not available on at least some Linux + return typeof fs[key] === 'function' +}) - if (stream._paused) return stream.on('resume', collect.bind(null, stream)) +// Export cloned fs: +Object.assign(exports, fs) - stream._collected = true - stream.pause() +// Universalify async methods: +api.forEach(method => { + exports[method] = u(fs[method]) +}) - stream.on('data', save) - stream.on('end', save) - var buf = [] - function save (b) { - if (typeof b === 'string') b = new Buffer(b) - if (Buffer.isBuffer(b) && !b.length) return - buf.push(b) +// We differ from mz/fs in that we still ship the old, broken, fs.exists() +// since we are a drop-in replacement for the native module +exports.exists = function (filename, callback) { + if (typeof callback === 'function') { + return fs.exists(filename, callback) } + return new Promise(resolve => { + return fs.exists(filename, resolve) + }) +} - stream.on('entry', saveEntry) - var entryBuffer = [] - function saveEntry (e) { - collect(e) - entryBuffer.push(e) - } +// fs.read(), fs.write(), fs.readv(), & fs.writev() need special treatment due to multiple callback args - stream.on('proxy', proxyPause) - function proxyPause (p) { - p.pause() +exports.read = function (fd, buffer, offset, length, position, callback) { + if (typeof callback === 'function') { + return fs.read(fd, buffer, offset, length, position, callback) } + return new Promise((resolve, reject) => { + fs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer) => { + if (err) return reject(err) + resolve({ bytesRead, buffer }) + }) + }) +} - // replace the pipe method with a new version that will - // unlock the buffered stuff. if you just call .pipe() - // without a destination, then it'll re-play the events. - stream.pipe = (function (orig) { - return function (dest) { - // console.error(' === open the pipes', dest && dest.path) +// Function signature can be +// fs.write(fd, buffer[, offset[, length[, position]]], callback) +// OR +// fs.write(fd, string[, position[, encoding]], callback) +// We need to handle both cases, so we use ...args +exports.write = function (fd, buffer, ...args) { + if (typeof args[args.length - 1] === 'function') { + return fs.write(fd, buffer, ...args) + } - // let the entries flow through one at a time. - // Once they're all done, then we can resume completely. - var e = 0 - ;(function unblockEntry () { - var entry = entryBuffer[e++] - // console.error(" ==== unblock entry", entry && entry.path) - if (!entry) return resume() - entry.on('end', unblockEntry) - if (dest) dest.add(entry) - else stream.emit('entry', entry) - })() + return new Promise((resolve, reject) => { + fs.write(fd, buffer, ...args, (err, bytesWritten, buffer) => { + if (err) return reject(err) + resolve({ bytesWritten, buffer }) + }) + }) +} - function resume () { - stream.removeListener('entry', saveEntry) - stream.removeListener('data', save) - stream.removeListener('end', save) +// Function signature is +// s.readv(fd, buffers[, position], callback) +// We need to handle the optional arg, so we use ...args +exports.readv = function (fd, buffers, ...args) { + if (typeof args[args.length - 1] === 'function') { + return fs.readv(fd, buffers, ...args) + } - stream.pipe = orig - if (dest) stream.pipe(dest) + return new Promise((resolve, reject) => { + fs.readv(fd, buffers, ...args, (err, bytesRead, buffers) => { + if (err) return reject(err) + resolve({ bytesRead, buffers }) + }) + }) +} - buf.forEach(function (b) { - if (b) stream.emit('data', b) - else stream.emit('end') - }) +// Function signature is +// s.writev(fd, buffers[, position], callback) +// We need to handle the optional arg, so we use ...args +exports.writev = function (fd, buffers, ...args) { + if (typeof args[args.length - 1] === 'function') { + return fs.writev(fd, buffers, ...args) + } - stream.resume() - } + return new Promise((resolve, reject) => { + fs.writev(fd, buffers, ...args, (err, bytesWritten, buffers) => { + if (err) return reject(err) + resolve({ bytesWritten, buffers }) + }) + }) +} - return dest - } - })(stream.pipe) +// fs.realpath.native sometimes not available if fs is monkey-patched +if (typeof fs.realpath.native === 'function') { + exports.realpath.native = u(fs.realpath.native) +} else { + process.emitWarning( + 'fs.realpath.native is not a function. Is fs being monkey-patched?', + 'Warning', 'fs-extra-WARN0003' + ) } /***/ }), -/***/ 4486: +/***/ 2136: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// A thing that emits "entry" events with Reader objects -// Pausing it causes it to stop emitting entry events, and also -// pauses the current entry if there is one. -module.exports = DirReader -var fs = __nccwpck_require__(7758) -var inherits = __nccwpck_require__(4124) -var path = __nccwpck_require__(1017) -var Reader = __nccwpck_require__(3284) -var assert = (__nccwpck_require__(9491).ok) +module.exports = { + // Export promiseified graceful-fs: + ...__nccwpck_require__(3506), + // Export extra methods: + ...__nccwpck_require__(5796), + ...__nccwpck_require__(7882), + ...__nccwpck_require__(5779), + ...__nccwpck_require__(8471), + ...__nccwpck_require__(1089), + ...__nccwpck_require__(2076), + ...__nccwpck_require__(5229), + ...__nccwpck_require__(2881), + ...__nccwpck_require__(6205) +} -inherits(DirReader, Reader) -function DirReader (props) { - var self = this - if (!(self instanceof DirReader)) { - throw new Error('DirReader must be called as constructor.') - } +/***/ }), - // should already be established as a Directory type - if (props.type !== 'Directory' || !props.Directory) { - throw new Error('Non-directory type ' + props.type) - } +/***/ 8471: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - self.entries = null - self._index = -1 - self._paused = false - self._length = -1 - if (props.sort) { - this.sort = props.sort - } - Reader.call(this, props) -} +const u = (__nccwpck_require__(5077).fromPromise) +const jsonFile = __nccwpck_require__(6239) -DirReader.prototype._getEntries = function () { - var self = this +jsonFile.outputJson = u(__nccwpck_require__(3753)) +jsonFile.outputJsonSync = __nccwpck_require__(425) +// aliases +jsonFile.outputJSON = jsonFile.outputJson +jsonFile.outputJSONSync = jsonFile.outputJsonSync +jsonFile.writeJSON = jsonFile.writeJson +jsonFile.writeJSONSync = jsonFile.writeJsonSync +jsonFile.readJSON = jsonFile.readJson +jsonFile.readJSONSync = jsonFile.readJsonSync - // race condition. might pause() before calling _getEntries, - // and then resume, and try to get them a second time. - if (self._gotEntries) return - self._gotEntries = true +module.exports = jsonFile - fs.readdir(self._path, function (er, entries) { - if (er) return self.error(er) - self.entries = entries +/***/ }), - self.emit('entries', entries) - if (self._paused) self.once('resume', processEntries) - else processEntries() +/***/ 6239: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function processEntries () { - self._length = self.entries.length - if (typeof self.sort === 'function') { - self.entries = self.entries.sort(self.sort.bind(self)) - } - self._read() - } - }) -} -// start walking the dir, and emit an "entry" event for each one. -DirReader.prototype._read = function () { - var self = this - if (!self.entries) return self._getEntries() +const jsonFile = __nccwpck_require__(2064) - if (self._paused || self._currentEntry || self._aborted) { - // console.error('DR paused=%j, current=%j, aborted=%j', self._paused, !!self._currentEntry, self._aborted) - return - } +module.exports = { + // jsonfile exports + readJson: jsonFile.readFile, + readJsonSync: jsonFile.readFileSync, + writeJson: jsonFile.writeFile, + writeJsonSync: jsonFile.writeFileSync +} - self._index++ - if (self._index >= self.entries.length) { - if (!self._ended) { - self._ended = true - self.emit('end') - self.emit('close') - } - return - } - // ok, handle this one, then. +/***/ }), - // save creating a proxy, by stat'ing the thing now. - var p = path.resolve(self._path, self.entries[self._index]) - assert(p !== self._path) - assert(self.entries[self._index]) +/***/ 425: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // set this to prevent trying to _read() again in the stat time. - self._currentEntry = p - fs[ self.props.follow ? 'stat' : 'lstat' ](p, function (er, stat) { - if (er) return self.error(er) - var who = self._proxy || self - stat.path = p - stat.basename = path.basename(p) - stat.dirname = path.dirname(p) - var childProps = self.getChildProps.call(who, stat) - childProps.path = p - childProps.basename = path.basename(p) - childProps.dirname = path.dirname(p) +const { stringify } = __nccwpck_require__(9449) +const { outputFileSync } = __nccwpck_require__(5229) - var entry = Reader(childProps, stat) +function outputJsonSync (file, data, options) { + const str = stringify(data, options) - // console.error("DR Entry", p, stat.size) + outputFileSync(file, str, options) +} - self._currentEntry = entry +module.exports = outputJsonSync - // "entry" events are for direct entries in a specific dir. - // "child" events are for any and all children at all levels. - // This nomenclature is not completely final. - entry.on('pause', function (who) { - if (!self._paused && !entry._disowned) { - self.pause(who) - } - }) +/***/ }), - entry.on('resume', function (who) { - if (self._paused && !entry._disowned) { - self.resume(who) - } - }) +/***/ 3753: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - entry.on('stat', function (props) { - self.emit('_entryStat', entry, props) - if (entry._aborted) return - if (entry._paused) { - entry.once('resume', function () { - self.emit('entryStat', entry, props) - }) - } else self.emit('entryStat', entry, props) - }) - entry.on('ready', function EMITCHILD () { - // console.error("DR emit child", entry._path) - if (self._paused) { - // console.error(" DR emit child - try again later") - // pause the child, and emit the "entry" event once we drain. - // console.error("DR pausing child entry") - entry.pause(self) - return self.once('resume', EMITCHILD) - } - - // skip over sockets. they can't be piped around properly, - // so there's really no sense even acknowledging them. - // if someone really wants to see them, they can listen to - // the "socket" events. - if (entry.type === 'Socket') { - self.emit('socket', entry) - } else { - self.emitEntry(entry) - } - }) - var ended = false - entry.on('close', onend) - entry.on('disown', onend) - function onend () { - if (ended) return - ended = true - self.emit('childEnd', entry) - self.emit('entryEnd', entry) - self._currentEntry = null - if (!self._paused) { - self._read() - } - } - - // XXX Remove this. Works in node as of 0.6.2 or so. - // Long filenames should not break stuff. - entry.on('error', function (er) { - if (entry._swallowErrors) { - self.warn(er) - entry.emit('end') - entry.emit('close') - } else { - self.emit('error', er) - } - }) +const { stringify } = __nccwpck_require__(9449) +const { outputFile } = __nccwpck_require__(5229) - // proxy up some events. - ;[ - 'child', - 'childEnd', - 'warn' - ].forEach(function (ev) { - entry.on(ev, self.emit.bind(self, ev)) - }) - }) -} +async function outputJson (file, data, options = {}) { + const str = stringify(data, options) -DirReader.prototype.disown = function (entry) { - entry.emit('beforeDisown') - entry._disowned = true - entry.parent = entry.root = null - if (entry === this._currentEntry) { - this._currentEntry = null - } - entry.emit('disown') + await outputFile(file, str, options) } -DirReader.prototype.getChildProps = function () { - return { - depth: this.depth + 1, - root: this.root || this, - parent: this, - follow: this.follow, - filter: this.filter, - sort: this.props.sort, - hardlinks: this.props.hardlinks - } -} +module.exports = outputJson -DirReader.prototype.pause = function (who) { - var self = this - if (self._paused) return - who = who || self - self._paused = true - if (self._currentEntry && self._currentEntry.pause) { - self._currentEntry.pause(who) - } - self.emit('pause', who) -} -DirReader.prototype.resume = function (who) { - var self = this - if (!self._paused) return - who = who || self +/***/ }), + +/***/ 1089: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - self._paused = false - // console.error('DR Emit Resume', self._path) - self.emit('resume', who) - if (self._paused) { - // console.error('DR Re-paused', self._path) - return - } - if (self._currentEntry) { - if (self._currentEntry.resume) self._currentEntry.resume(who) - } else self._read() -} +const u = (__nccwpck_require__(5077).fromPromise) +const { makeDir: _makeDir, makeDirSync } = __nccwpck_require__(9625) +const makeDir = u(_makeDir) -DirReader.prototype.emitEntry = function (entry) { - this.emit('entry', entry) - this.emit('child', entry) +module.exports = { + mkdirs: makeDir, + mkdirsSync: makeDirSync, + // alias + mkdirp: makeDir, + mkdirpSync: makeDirSync, + ensureDir: makeDir, + ensureDirSync: makeDirSync } /***/ }), -/***/ 4745: +/***/ 9625: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// It is expected that, when .add() returns false, the consumer -// of the DirWriter will pause until a "drain" event occurs. Note -// that this is *almost always going to be the case*, unless the -// thing being written is some sort of unsupported type, and thus -// skipped over. - -module.exports = DirWriter -var Writer = __nccwpck_require__(8680) -var inherits = __nccwpck_require__(4124) -var mkdir = __nccwpck_require__(6186) -var path = __nccwpck_require__(1017) -var collect = __nccwpck_require__(3317) +const fs = __nccwpck_require__(3506) +const { checkPath } = __nccwpck_require__(3388) -inherits(DirWriter, Writer) - -function DirWriter (props) { - var self = this - if (!(self instanceof DirWriter)) { - self.error('DirWriter must be called as constructor.', null, true) - } - - // should already be established as a Directory type - if (props.type !== 'Directory' || !props.Directory) { - self.error('Non-directory type ' + props.type + ' ' + - JSON.stringify(props), null, true) - } - - Writer.call(this, props) +const getMode = options => { + const defaults = { mode: 0o777 } + if (typeof options === 'number') return options + return ({ ...defaults, ...options }).mode } -DirWriter.prototype._create = function () { - var self = this - mkdir(self._path, Writer.dirmode, function (er) { - if (er) return self.error(er) - // ready to start getting entries! - self.ready = true - self.emit('ready') - self._process() +module.exports.makeDir = async (dir, options) => { + checkPath(dir) + + return fs.mkdir(dir, { + mode: getMode(options), + recursive: true }) } -// a DirWriter has an add(entry) method, but its .write() doesn't -// do anything. Why a no-op rather than a throw? Because this -// leaves open the door for writing directory metadata for -// gnu/solaris style dumpdirs. -DirWriter.prototype.write = function () { - return true -} +module.exports.makeDirSync = (dir, options) => { + checkPath(dir) -DirWriter.prototype.end = function () { - this._ended = true - this._process() + return fs.mkdirSync(dir, { + mode: getMode(options), + recursive: true + }) } -DirWriter.prototype.add = function (entry) { - var self = this - - // console.error('\tadd', entry._path, '->', self._path) - collect(entry) - if (!self.ready || self._currentEntry) { - self._buffer.push(entry) - return false - } - - // create a new writer, and pipe the incoming entry into it. - if (self._ended) { - return self.error('add after end') - } - self._buffer.push(entry) - self._process() +/***/ }), - return this._buffer.length === 0 -} +/***/ 3388: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -DirWriter.prototype._process = function () { - var self = this +// Adapted from https://github.com/sindresorhus/make-dir +// Copyright (c) Sindre Sorhus (sindresorhus.com) +// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - // console.error('DW Process p=%j', self._processing, self.basename) +const path = __nccwpck_require__(6928) - if (self._processing) return +// https://github.com/nodejs/node/issues/8987 +// https://github.com/libuv/libuv/pull/1088 +module.exports.checkPath = function checkPath (pth) { + if (process.platform === 'win32') { + const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path.parse(pth).root, '')) - var entry = self._buffer.shift() - if (!entry) { - // console.error("DW Drain") - self.emit('drain') - if (self._ended) self._finish() - return + if (pathHasInvalidWinCharacters) { + const error = new Error(`Path contains invalid characters: ${pth}`) + error.code = 'EINVAL' + throw error + } } +} - self._processing = true - // console.error("DW Entry", entry._path) - self.emit('entry', entry) +/***/ }), - // ok, add this entry - // - // don't allow recursive copying - var p = entry - var pp - do { - pp = p._path || p.path - if (pp === self.root._path || pp === self._path || - (pp && pp.indexOf(self._path) === 0)) { - // console.error('DW Exit (recursive)', entry.basename, self._path) - self._processing = false - if (entry._collected) entry.pipe() - return self._process() - } - p = p.parent - } while (p) - - // console.error("DW not recursive") - - // chop off the entry's root dir, replace with ours - var props = { - parent: self, - root: self.root || self, - type: entry.type, - depth: self.depth + 1 - } - - pp = entry._path || entry.path || entry.props.path - if (entry.parent) { - pp = pp.substr(entry.parent._path.length + 1) - } - // get rid of any ../../ shenanigans - props.path = path.join(self.path, path.join('/', pp)) - - // if i have a filter, the child should inherit it. - props.filter = self.filter - - // all the rest of the stuff, copy over from the source. - Object.keys(entry.props).forEach(function (k) { - if (!props.hasOwnProperty(k)) { - props[k] = entry.props[k] - } - }) +/***/ 2076: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // not sure at this point what kind of writer this is. - var child = self._currentChild = new Writer(props) - child.on('ready', function () { - // console.error("DW Child Ready", child.type, child._path) - // console.error(" resuming", entry._path) - entry.pipe(child) - entry.resume() - }) - // XXX Make this work in node. - // Long filenames should not break stuff. - child.on('error', function (er) { - if (child._swallowErrors) { - self.warn(er) - child.emit('end') - child.emit('close') - } else { - self.emit('error', er) - } - }) - // we fire _end internally *after* end, so that we don't move on - // until any "end" listeners have had their chance to do stuff. - child.on('close', onend) - var ended = false - function onend () { - if (ended) return - ended = true - // console.error("* DW Child end", child.basename) - self._currentChild = null - self._processing = false - self._process() - } +const u = (__nccwpck_require__(5077).fromPromise) +module.exports = { + move: u(__nccwpck_require__(7751)), + moveSync: __nccwpck_require__(9951) } /***/ }), -/***/ 8413: +/***/ 9951: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Basically just a wrapper around an fs.ReadStream -module.exports = FileReader -var fs = __nccwpck_require__(7758) -var inherits = __nccwpck_require__(4124) -var Reader = __nccwpck_require__(3284) -var EOF = {EOF: true} -var CLOSE = {CLOSE: true} +const fs = __nccwpck_require__(5744) +const path = __nccwpck_require__(6928) +const copySync = (__nccwpck_require__(5796).copySync) +const removeSync = (__nccwpck_require__(6205).removeSync) +const mkdirpSync = (__nccwpck_require__(1089).mkdirpSync) +const stat = __nccwpck_require__(887) -inherits(FileReader, Reader) +function moveSync (src, dest, opts) { + opts = opts || {} + const overwrite = opts.overwrite || opts.clobber || false -function FileReader (props) { - // console.error(" FR create", props.path, props.size, new Error().stack) - var self = this - if (!(self instanceof FileReader)) { - throw new Error('FileReader must be called as constructor.') + const { srcStat, isChangingCase = false } = stat.checkPathsSync(src, dest, 'move', opts) + stat.checkParentPathsSync(src, srcStat, dest, 'move') + if (!isParentRoot(dest)) mkdirpSync(path.dirname(dest)) + return doRename(src, dest, overwrite, isChangingCase) +} + +function isParentRoot (dest) { + const parent = path.dirname(dest) + const parsedPath = path.parse(parent) + return parsedPath.root === parent +} + +function doRename (src, dest, overwrite, isChangingCase) { + if (isChangingCase) return rename(src, dest, overwrite) + if (overwrite) { + removeSync(dest) + return rename(src, dest, overwrite) } + if (fs.existsSync(dest)) throw new Error('dest already exists.') + return rename(src, dest, overwrite) +} - // should already be established as a File type - // XXX Todo: preserve hardlinks by tracking dev+inode+nlink, - // with a HardLinkReader class. - if (!((props.type === 'Link' && props.Link) || - (props.type === 'File' && props.File))) { - throw new Error('Non-file type ' + props.type) +function rename (src, dest, overwrite) { + try { + fs.renameSync(src, dest) + } catch (err) { + if (err.code !== 'EXDEV') throw err + return moveAcrossDevice(src, dest, overwrite) } +} - self._buffer = [] - self._bytesEmitted = 0 - Reader.call(self, props) +function moveAcrossDevice (src, dest, overwrite) { + const opts = { + overwrite, + errorOnExist: true, + preserveTimestamps: true + } + copySync(src, dest, opts) + return removeSync(src) } -FileReader.prototype._getStream = function () { - var self = this - var stream = self._stream = fs.createReadStream(self._path, self.props) +module.exports = moveSync - if (self.props.blksize) { - stream.bufferSize = self.props.blksize - } - stream.on('open', self.emit.bind(self, 'open')) +/***/ }), - stream.on('data', function (c) { - // console.error('\t\t%d %s', c.length, self.basename) - self._bytesEmitted += c.length - // no point saving empty chunks - if (!c.length) { - return - } else if (self._paused || self._buffer.length) { - self._buffer.push(c) - self._read() - } else self.emit('data', c) - }) +/***/ 7751: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - stream.on('end', function () { - if (self._paused || self._buffer.length) { - // console.error('FR Buffering End', self._path) - self._buffer.push(EOF) - self._read() - } else { - self.emit('end') - } - if (self._bytesEmitted !== self.props.size) { - self.error("Didn't get expected byte count\n" + - 'expect: ' + self.props.size + '\n' + - 'actual: ' + self._bytesEmitted) - } - }) - stream.on('close', function () { - if (self._paused || self._buffer.length) { - // console.error('FR Buffering Close', self._path) - self._buffer.push(CLOSE) - self._read() - } else { - // console.error('FR close 1', self._path) - self.emit('close') - } - }) +const fs = __nccwpck_require__(3506) +const path = __nccwpck_require__(6928) +const { copy } = __nccwpck_require__(5796) +const { remove } = __nccwpck_require__(6205) +const { mkdirp } = __nccwpck_require__(1089) +const { pathExists } = __nccwpck_require__(2881) +const stat = __nccwpck_require__(887) - stream.on('error', function (e) { - self.emit('error', e) - }) +async function move (src, dest, opts = {}) { + const overwrite = opts.overwrite || opts.clobber || false - self._read() -} + const { srcStat, isChangingCase = false } = await stat.checkPaths(src, dest, 'move', opts) -FileReader.prototype._read = function () { - var self = this - // console.error('FR _read', self._path) - if (self._paused) { - // console.error('FR _read paused', self._path) - return - } + await stat.checkParentPaths(src, srcStat, dest, 'move') - if (!self._stream) { - // console.error('FR _getStream calling', self._path) - return self._getStream() + // If the parent of dest is not root, make sure it exists before proceeding + const destParent = path.dirname(dest) + const parsedParentPath = path.parse(destParent) + if (parsedParentPath.root !== destParent) { + await mkdirp(destParent) } - // clear out the buffer, if there is one. - if (self._buffer.length) { - // console.error('FR _read has buffer', self._buffer.length, self._path) - var buf = self._buffer - for (var i = 0, l = buf.length; i < l; i++) { - var c = buf[i] - if (c === EOF) { - // console.error('FR Read emitting buffered end', self._path) - self.emit('end') - } else if (c === CLOSE) { - // console.error('FR Read emitting buffered close', self._path) - self.emit('close') - } else { - // console.error('FR Read emitting buffered data', self._path) - self.emit('data', c) - } + return doRename(src, dest, overwrite, isChangingCase) +} - if (self._paused) { - // console.error('FR Read Re-pausing at '+i, self._path) - self._buffer = buf.slice(i) - return - } +async function doRename (src, dest, overwrite, isChangingCase) { + if (!isChangingCase) { + if (overwrite) { + await remove(dest) + } else if (await pathExists(dest)) { + throw new Error('dest already exists.') } - self._buffer.length = 0 } -// console.error("FR _read done") -// that's about all there is to it. -} -FileReader.prototype.pause = function (who) { - var self = this - // console.error('FR Pause', self._path) - if (self._paused) return - who = who || self - self._paused = true - if (self._stream) self._stream.pause() - self.emit('pause', who) + try { + // Try w/ rename first, and try copy + remove if EXDEV + await fs.rename(src, dest) + } catch (err) { + if (err.code !== 'EXDEV') { + throw err + } + await moveAcrossDevice(src, dest, overwrite) + } } -FileReader.prototype.resume = function (who) { - var self = this - // console.error('FR Resume', self._path) - if (!self._paused) return - who = who || self - self.emit('resume', who) - self._paused = false - if (self._stream) self._stream.resume() - self._read() +async function moveAcrossDevice (src, dest, overwrite) { + const opts = { + overwrite, + errorOnExist: true, + preserveTimestamps: true + } + + await copy(src, dest, opts) + return remove(src) } +module.exports = move + /***/ }), -/***/ 2539: +/***/ 5229: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -module.exports = FileWriter -var fs = __nccwpck_require__(7758) -var Writer = __nccwpck_require__(8680) -var inherits = __nccwpck_require__(4124) -var EOF = {} -inherits(FileWriter, Writer) +const u = (__nccwpck_require__(5077).fromPromise) +const fs = __nccwpck_require__(3506) +const path = __nccwpck_require__(6928) +const mkdir = __nccwpck_require__(1089) +const pathExists = (__nccwpck_require__(2881).pathExists) -function FileWriter (props) { - var self = this - if (!(self instanceof FileWriter)) { - throw new Error('FileWriter must be called as constructor.') - } +async function outputFile (file, data, encoding = 'utf-8') { + const dir = path.dirname(file) - // should already be established as a File type - if (props.type !== 'File' || !props.File) { - throw new Error('Non-file type ' + props.type) + if (!(await pathExists(dir))) { + await mkdir.mkdirs(dir) } - self._buffer = [] - self._bytesWritten = 0 + return fs.writeFile(file, data, encoding) +} + +function outputFileSync (file, ...args) { + const dir = path.dirname(file) + if (!fs.existsSync(dir)) { + mkdir.mkdirsSync(dir) + } - Writer.call(this, props) + fs.writeFileSync(file, ...args) } -FileWriter.prototype._create = function () { - var self = this - if (self._stream) return +module.exports = { + outputFile: u(outputFile), + outputFileSync +} - var so = {} - if (self.props.flags) so.flags = self.props.flags - so.mode = Writer.filemode - if (self._old && self._old.blksize) so.bufferSize = self._old.blksize - self._stream = fs.createWriteStream(self._path, so) +/***/ }), - self._stream.on('open', function () { - // console.error("FW open", self._buffer, self._path) - self.ready = true - self._buffer.forEach(function (c) { - if (c === EOF) self._stream.end() - else self._stream.write(c) - }) - self.emit('ready') - // give this a kick just in case it needs it. - self.emit('drain') - }) +/***/ 2881: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - self._stream.on('error', function (er) { self.emit('error', er) }) - self._stream.on('drain', function () { self.emit('drain') }) +const u = (__nccwpck_require__(5077).fromPromise) +const fs = __nccwpck_require__(3506) - self._stream.on('close', function () { - // console.error('\n\nFW Stream Close', self._path, self.size) - self._finish() - }) +function pathExists (path) { + return fs.access(path).then(() => true).catch(() => false) } -FileWriter.prototype.write = function (c) { - var self = this - - self._bytesWritten += c.length +module.exports = { + pathExists: u(pathExists), + pathExistsSync: fs.existsSync +} - if (!self.ready) { - if (!Buffer.isBuffer(c) && typeof c !== 'string') { - throw new Error('invalid write data') - } - self._buffer.push(c) - return false - } - var ret = self._stream.write(c) - // console.error('\t-- fw wrote, _stream says', ret, self._stream._queue.length) +/***/ }), - // allow 2 buffered writes, because otherwise there's just too - // much stop and go bs. - if (ret === false && self._stream._queue) { - return self._stream._queue.length <= 2 - } else { - return ret - } -} +/***/ 6205: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -FileWriter.prototype.end = function (c) { - var self = this - if (c) self.write(c) - if (!self.ready) { - self._buffer.push(EOF) - return false - } +const fs = __nccwpck_require__(5744) +const u = (__nccwpck_require__(5077).fromCallback) - return self._stream.end() +function remove (path, callback) { + fs.rm(path, { recursive: true, force: true }, callback) } -FileWriter.prototype._finish = function () { - var self = this - if (typeof self.size === 'number' && self._bytesWritten !== self.size) { - self.error( - 'Did not get expected byte count.\n' + - 'expect: ' + self.size + '\n' + - 'actual: ' + self._bytesWritten) - } - Writer.prototype._finish.call(self) +function removeSync (path) { + fs.rmSync(path, { recursive: true, force: true }) } - -/***/ }), - -/***/ 1600: -/***/ ((module) => { - -module.exports = getType - -function getType (st) { - var types = [ - 'Directory', - 'File', - 'SymbolicLink', - 'Link', // special for hardlinks from tarballs - 'BlockDevice', - 'CharacterDevice', - 'FIFO', - 'Socket' - ] - var type - - if (st.type && types.indexOf(st.type) !== -1) { - st[st.type] = true - return st.type - } - - for (var i = 0, l = types.length; i < l; i++) { - type = types[i] - var is = st[type] || st['is' + type] - if (typeof is === 'function') is = is.call(st) - if (is) { - st[type] = true - st.type = type - return type - } - } - - return null +module.exports = { + remove: u(remove), + removeSync } /***/ }), -/***/ 8337: +/***/ 887: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Basically just a wrapper around an fs.readlink -// -// XXX: Enhance this to support the Link type, by keeping -// a lookup table of {:}, so that hardlinks -// can be preserved in tarballs. -module.exports = LinkReader -var fs = __nccwpck_require__(7758) -var inherits = __nccwpck_require__(4124) -var Reader = __nccwpck_require__(3284) +const fs = __nccwpck_require__(3506) +const path = __nccwpck_require__(6928) +const u = (__nccwpck_require__(5077).fromPromise) -inherits(LinkReader, Reader) +function getStats (src, dest, opts) { + const statFunc = opts.dereference + ? (file) => fs.stat(file, { bigint: true }) + : (file) => fs.lstat(file, { bigint: true }) + return Promise.all([ + statFunc(src), + statFunc(dest).catch(err => { + if (err.code === 'ENOENT') return null + throw err + }) + ]).then(([srcStat, destStat]) => ({ srcStat, destStat })) +} -function LinkReader (props) { - var self = this - if (!(self instanceof LinkReader)) { - throw new Error('LinkReader must be called as constructor.') +function getStatsSync (src, dest, opts) { + let destStat + const statFunc = opts.dereference + ? (file) => fs.statSync(file, { bigint: true }) + : (file) => fs.lstatSync(file, { bigint: true }) + const srcStat = statFunc(src) + try { + destStat = statFunc(dest) + } catch (err) { + if (err.code === 'ENOENT') return { srcStat, destStat: null } + throw err + } + return { srcStat, destStat } +} + +async function checkPaths (src, dest, funcName, opts) { + const { srcStat, destStat } = await getStats(src, dest, opts) + if (destStat) { + if (areIdentical(srcStat, destStat)) { + const srcBaseName = path.basename(src) + const destBaseName = path.basename(dest) + if (funcName === 'move' && + srcBaseName !== destBaseName && + srcBaseName.toLowerCase() === destBaseName.toLowerCase()) { + return { srcStat, destStat, isChangingCase: true } + } + throw new Error('Source and destination must not be the same.') + } + if (srcStat.isDirectory() && !destStat.isDirectory()) { + throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`) + } + if (!srcStat.isDirectory() && destStat.isDirectory()) { + throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`) + } } - if (!((props.type === 'Link' && props.Link) || - (props.type === 'SymbolicLink' && props.SymbolicLink))) { - throw new Error('Non-link type ' + props.type) + if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { + throw new Error(errMsg(src, dest, funcName)) } - Reader.call(self, props) + return { srcStat, destStat } } -// When piping a LinkReader into a LinkWriter, we have to -// already have the linkpath property set, so that has to -// happen *before* the "ready" event, which means we need to -// override the _stat method. -LinkReader.prototype._stat = function (currentStat) { - var self = this - fs.readlink(self._path, function (er, linkpath) { - if (er) return self.error(er) - self.linkpath = self.props.linkpath = linkpath - self.emit('linkpath', linkpath) - Reader.prototype._stat.call(self, currentStat) - }) -} +function checkPathsSync (src, dest, funcName, opts) { + const { srcStat, destStat } = getStatsSync(src, dest, opts) -LinkReader.prototype._read = function () { - var self = this - if (self._paused) return - // basically just a no-op, since we got all the info we need - // from the _stat method - if (!self._ended) { - self.emit('end') - self.emit('close') - self._ended = true + if (destStat) { + if (areIdentical(srcStat, destStat)) { + const srcBaseName = path.basename(src) + const destBaseName = path.basename(dest) + if (funcName === 'move' && + srcBaseName !== destBaseName && + srcBaseName.toLowerCase() === destBaseName.toLowerCase()) { + return { srcStat, destStat, isChangingCase: true } + } + throw new Error('Source and destination must not be the same.') + } + if (srcStat.isDirectory() && !destStat.isDirectory()) { + throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`) + } + if (!srcStat.isDirectory() && destStat.isDirectory()) { + throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`) + } } -} - - -/***/ }), - -/***/ 404: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = LinkWriter - -var fs = __nccwpck_require__(7758) -var Writer = __nccwpck_require__(8680) -var inherits = __nccwpck_require__(4124) -var path = __nccwpck_require__(1017) -var rimraf = __nccwpck_require__(4959) - -inherits(LinkWriter, Writer) -function LinkWriter (props) { - var self = this - if (!(self instanceof LinkWriter)) { - throw new Error('LinkWriter must be called as constructor.') + if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { + throw new Error(errMsg(src, dest, funcName)) } + return { srcStat, destStat } +} + +// recursively check if dest parent is a subdirectory of src. +// It works for all file types including symlinks since it +// checks the src and dest inodes. It starts from the deepest +// parent and stops once it reaches the src parent or the root path. +async function checkParentPaths (src, srcStat, dest, funcName) { + const srcParent = path.resolve(path.dirname(src)) + const destParent = path.resolve(path.dirname(dest)) + if (destParent === srcParent || destParent === path.parse(destParent).root) return - // should already be established as a Link type - if (!((props.type === 'Link' && props.Link) || - (props.type === 'SymbolicLink' && props.SymbolicLink))) { - throw new Error('Non-link type ' + props.type) + let destStat + try { + destStat = await fs.stat(destParent, { bigint: true }) + } catch (err) { + if (err.code === 'ENOENT') return + throw err } - if (props.linkpath === '') props.linkpath = '.' - if (!props.linkpath) { - self.error('Need linkpath property to create ' + props.type) + if (areIdentical(srcStat, destStat)) { + throw new Error(errMsg(src, dest, funcName)) } - Writer.call(this, props) + return checkParentPaths(src, srcStat, destParent, funcName) } -LinkWriter.prototype._create = function () { - // console.error(" LW _create") - var self = this - var hard = self.type === 'Link' || process.platform === 'win32' - var link = hard ? 'link' : 'symlink' - var lp = hard ? path.resolve(self.dirname, self.linkpath) : self.linkpath - - // can only change the link path by clobbering - // For hard links, let's just assume that's always the case, since - // there's no good way to read them if we don't already know. - if (hard) return clobber(self, lp, link) - - fs.readlink(self._path, function (er, p) { - // only skip creation if it's exactly the same link - if (p && p === lp) return finish(self) - clobber(self, lp, link) - }) +function checkParentPathsSync (src, srcStat, dest, funcName) { + const srcParent = path.resolve(path.dirname(src)) + const destParent = path.resolve(path.dirname(dest)) + if (destParent === srcParent || destParent === path.parse(destParent).root) return + let destStat + try { + destStat = fs.statSync(destParent, { bigint: true }) + } catch (err) { + if (err.code === 'ENOENT') return + throw err + } + if (areIdentical(srcStat, destStat)) { + throw new Error(errMsg(src, dest, funcName)) + } + return checkParentPathsSync(src, srcStat, destParent, funcName) } -function clobber (self, lp, link) { - rimraf(self._path, function (er) { - if (er) return self.error(er) - create(self, lp, link) - }) +function areIdentical (srcStat, destStat) { + return destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev } -function create (self, lp, link) { - fs[link](lp, self._path, function (er) { - // if this is a hard link, and we're in the process of writing out a - // directory, it's very possible that the thing we're linking to - // doesn't exist yet (especially if it was intended as a symlink), - // so swallow ENOENT errors here and just soldier in. - // Additionally, an EPERM or EACCES can happen on win32 if it's trying - // to make a link to a directory. Again, just skip it. - // A better solution would be to have fs.symlink be supported on - // windows in some nice fashion. - if (er) { - if ((er.code === 'ENOENT' || - er.code === 'EACCES' || - er.code === 'EPERM') && process.platform === 'win32') { - self.ready = true - self.emit('ready') - self.emit('end') - self.emit('close') - self.end = self._finish = function () {} - } else return self.error(er) - } - finish(self) - }) +// return true if dest is a subdir of src, otherwise false. +// It only checks the path strings. +function isSrcSubdir (src, dest) { + const srcArr = path.resolve(src).split(path.sep).filter(i => i) + const destArr = path.resolve(dest).split(path.sep).filter(i => i) + return srcArr.every((cur, i) => destArr[i] === cur) } -function finish (self) { - self.ready = true - self.emit('ready') - if (self._ended && !self._finished) self._finish() +function errMsg (src, dest, funcName) { + return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.` } -LinkWriter.prototype.end = function () { - // console.error("LW finish in end") - this._ended = true - if (this.ready) { - this._finished = true - this._finish() - } +module.exports = { + // checkPaths + checkPaths: u(checkPaths), + checkPathsSync, + // checkParent + checkParentPaths: u(checkParentPaths), + checkParentPathsSync, + // Misc + isSrcSubdir, + areIdentical } /***/ }), -/***/ 7328: +/***/ 6934: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// A reader for when we don't yet know what kind of thing -// the thing is. -module.exports = ProxyReader -var Reader = __nccwpck_require__(3284) -var getType = __nccwpck_require__(1600) -var inherits = __nccwpck_require__(4124) -var fs = __nccwpck_require__(7758) +const fs = __nccwpck_require__(3506) +const u = (__nccwpck_require__(5077).fromPromise) + +async function utimesMillis (path, atime, mtime) { + // if (!HAS_MILLIS_RES) return fs.utimes(path, atime, mtime, callback) + const fd = await fs.open(path, 'r+') -inherits(ProxyReader, Reader) + let closeErr = null -function ProxyReader (props) { - var self = this - if (!(self instanceof ProxyReader)) { - throw new Error('ProxyReader must be called as constructor.') + try { + await fs.futimes(fd, atime, mtime) + } finally { + try { + await fs.close(fd) + } catch (e) { + closeErr = e + } } - self.props = props - self._buffer = [] - self.ready = false + if (closeErr) { + throw closeErr + } +} - Reader.call(self, props) +function utimesMillisSync (path, atime, mtime) { + const fd = fs.openSync(path, 'r+') + fs.futimesSync(fd, atime, mtime) + return fs.closeSync(fd) } -ProxyReader.prototype._stat = function () { - var self = this - var props = self.props - // stat the thing to see what the proxy should be. - var stat = props.follow ? 'stat' : 'lstat' +module.exports = { + utimesMillis: u(utimesMillis), + utimesMillisSync +} - fs[stat](props.path, function (er, current) { - var type - if (er || !current) { - type = 'File' - } else { - type = getType(current) - } - props[type] = true - props.type = self.type = type +/***/ }), - self._old = current - self._addProxy(Reader(props, current)) - }) -} +/***/ 3964: +/***/ ((module) => { -ProxyReader.prototype._addProxy = function (proxy) { - var self = this - if (self._proxyTarget) { - return self.error('proxy already set') - } - - self._proxyTarget = proxy - proxy._proxy = self - - ;[ - 'error', - 'data', - 'end', - 'close', - 'linkpath', - 'entry', - 'entryEnd', - 'child', - 'childEnd', - 'warn', - 'stat' - ].forEach(function (ev) { - // console.error('~~ proxy event', ev, self.path) - proxy.on(ev, self.emit.bind(self, ev)) - }) - self.emit('proxy', proxy) - proxy.on('ready', function () { - // console.error("~~ proxy is ready!", self.path) - self.ready = true - self.emit('ready') - }) +module.exports = clone - var calls = self._buffer - self._buffer.length = 0 - calls.forEach(function (c) { - proxy[c[0]].apply(proxy, c[1]) - }) +var getPrototypeOf = Object.getPrototypeOf || function (obj) { + return obj.__proto__ } -ProxyReader.prototype.pause = function () { - return this._proxyTarget ? this._proxyTarget.pause() : false -} +function clone (obj) { + if (obj === null || typeof obj !== 'object') + return obj + + if (obj instanceof Object) + var copy = { __proto__: getPrototypeOf(obj) } + else + var copy = Object.create(null) + + Object.getOwnPropertyNames(obj).forEach(function (key) { + Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) + }) -ProxyReader.prototype.resume = function () { - return this._proxyTarget ? this._proxyTarget.resume() : false + return copy } /***/ }), -/***/ 2071: +/***/ 5744: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// A writer for when we don't know what kind of thing -// the thing is. That is, it's not explicitly set, -// so we're going to make it whatever the thing already -// is, or "File" -// -// Until then, collect all events. - -module.exports = ProxyWriter +var fs = __nccwpck_require__(9896) +var polyfills = __nccwpck_require__(3501) +var legacy = __nccwpck_require__(2270) +var clone = __nccwpck_require__(3964) -var Writer = __nccwpck_require__(8680) -var getType = __nccwpck_require__(1600) -var inherits = __nccwpck_require__(4124) -var collect = __nccwpck_require__(3317) -var fs = __nccwpck_require__(7147) +var util = __nccwpck_require__(9023) -inherits(ProxyWriter, Writer) - -function ProxyWriter (props) { - var self = this - if (!(self instanceof ProxyWriter)) { - throw new Error('ProxyWriter must be called as constructor.') - } - - self.props = props - self._needDrain = false +/* istanbul ignore next - node 0.x polyfill */ +var gracefulQueue +var previousSymbol - Writer.call(self, props) +/* istanbul ignore else - node 0.x polyfill */ +if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { + gracefulQueue = Symbol.for('graceful-fs.queue') + // This is used in testing by future versions + previousSymbol = Symbol.for('graceful-fs.previous') +} else { + gracefulQueue = '___graceful-fs.queue' + previousSymbol = '___graceful-fs.previous' } -ProxyWriter.prototype._stat = function () { - var self = this - var props = self.props - // stat the thing to see what the proxy should be. - var stat = props.follow ? 'stat' : 'lstat' +function noop () {} - fs[stat](props.path, function (er, current) { - var type - if (er || !current) { - type = 'File' - } else { - type = getType(current) +function publishQueue(context, queue) { + Object.defineProperty(context, gracefulQueue, { + get: function() { + return queue } - - props[type] = true - props.type = self.type = type - - self._old = current - self._addProxy(Writer(props, current)) }) } -ProxyWriter.prototype._addProxy = function (proxy) { - // console.error("~~ set proxy", this.path) - var self = this - if (self._proxy) { - return self.error('proxy already set') +var debug = noop +if (util.debuglog) + debug = util.debuglog('gfs4') +else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) + debug = function() { + var m = util.format.apply(util, arguments) + m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') + console.error(m) } - self._proxy = proxy - ;[ - 'ready', - 'error', - 'close', - 'pipe', - 'drain', - 'warn' - ].forEach(function (ev) { - proxy.on(ev, self.emit.bind(self, ev)) - }) +// Once time initialization +if (!fs[gracefulQueue]) { + // This queue can be shared by multiple loaded instances + var queue = global[gracefulQueue] || [] + publishQueue(fs, queue) + + // Patch fs.close/closeSync to shared queue version, because we need + // to retry() whenever a close happens *anywhere* in the program. + // This is essential when multiple graceful-fs instances are + // in play at the same time. + fs.close = (function (fs$close) { + function close (fd, cb) { + return fs$close.call(fs, fd, function (err) { + // This function uses the graceful-fs shared queue + if (!err) { + resetQueue() + } - self.emit('proxy', proxy) + if (typeof cb === 'function') + cb.apply(this, arguments) + }) + } - var calls = self._buffer - calls.forEach(function (c) { - // console.error("~~ ~~ proxy buffered call", c[0], c[1]) - proxy[c[0]].apply(proxy, c[1]) - }) - self._buffer.length = 0 - if (self._needsDrain) self.emit('drain') -} + Object.defineProperty(close, previousSymbol, { + value: fs$close + }) + return close + })(fs.close) -ProxyWriter.prototype.add = function (entry) { - // console.error("~~ proxy add") - collect(entry) + fs.closeSync = (function (fs$closeSync) { + function closeSync (fd) { + // This function uses the graceful-fs shared queue + fs$closeSync.apply(fs, arguments) + resetQueue() + } - if (!this._proxy) { - this._buffer.push(['add', [entry]]) - this._needDrain = true - return false - } - return this._proxy.add(entry) -} + Object.defineProperty(closeSync, previousSymbol, { + value: fs$closeSync + }) + return closeSync + })(fs.closeSync) -ProxyWriter.prototype.write = function (c) { - // console.error('~~ proxy write') - if (!this._proxy) { - this._buffer.push(['write', [c]]) - this._needDrain = true - return false + if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { + process.on('exit', function() { + debug(fs[gracefulQueue]) + __nccwpck_require__(2613).equal(fs[gracefulQueue].length, 0) + }) } - return this._proxy.write(c) } -ProxyWriter.prototype.end = function (c) { - // console.error('~~ proxy end') - if (!this._proxy) { - this._buffer.push(['end', [c]]) - return false - } - return this._proxy.end(c) +if (!global[gracefulQueue]) { + publishQueue(global, fs[gracefulQueue]); } +module.exports = patch(clone(fs)) +if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { + module.exports = patch(fs) + fs.__patched = true; +} -/***/ }), - -/***/ 3284: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function patch (fs) { + // Everything that references the open() function needs to be in here + polyfills(fs) + fs.gracefulify = patch -module.exports = Reader + fs.createReadStream = createReadStream + fs.createWriteStream = createWriteStream + var fs$readFile = fs.readFile + fs.readFile = readFile + function readFile (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null -var fs = __nccwpck_require__(7758) -var Stream = (__nccwpck_require__(2781).Stream) -var inherits = __nccwpck_require__(4124) -var path = __nccwpck_require__(1017) -var getType = __nccwpck_require__(1600) -var hardLinks = Reader.hardLinks = {} -var Abstract = __nccwpck_require__(9479) + return go$readFile(path, options, cb) -// Must do this *before* loading the child classes -inherits(Reader, Abstract) + function go$readFile (path, options, cb, startTime) { + return fs$readFile(path, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } -var LinkReader = __nccwpck_require__(8337) + var fs$writeFile = fs.writeFile + fs.writeFile = writeFile + function writeFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null -function Reader (props, currentStat) { - var self = this - if (!(self instanceof Reader)) return new Reader(props, currentStat) + return go$writeFile(path, data, options, cb) - if (typeof props === 'string') { - props = { path: props } + function go$writeFile (path, data, options, cb, startTime) { + return fs$writeFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } } - // polymorphism. - // call fstream.Reader(dir) to get a DirReader object, etc. - // Note that, unlike in the Writer case, ProxyReader is going - // to be the *normal* state of affairs, since we rarely know - // the type of a file prior to reading it. - - var type - var ClassType + var fs$appendFile = fs.appendFile + if (fs$appendFile) + fs.appendFile = appendFile + function appendFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null - if (props.type && typeof props.type === 'function') { - type = props.type - ClassType = type - } else { - type = getType(props) - ClassType = Reader - } + return go$appendFile(path, data, options, cb) - if (currentStat && !type) { - type = getType(currentStat) - props[type] = true - props.type = type + function go$appendFile (path, data, options, cb, startTime) { + return fs$appendFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } } - switch (type) { - case 'Directory': - ClassType = __nccwpck_require__(4486) - break - - case 'Link': - // XXX hard links are just files. - // However, it would be good to keep track of files' dev+inode - // and nlink values, and create a HardLinkReader that emits - // a linkpath value of the original copy, so that the tar - // writer can preserve them. - // ClassType = HardLinkReader - // break - - case 'File': - ClassType = __nccwpck_require__(8413) - break - - case 'SymbolicLink': - ClassType = LinkReader - break - - case 'Socket': - ClassType = __nccwpck_require__(2470) - break - - case null: - ClassType = __nccwpck_require__(7328) - break - } + var fs$copyFile = fs.copyFile + if (fs$copyFile) + fs.copyFile = copyFile + function copyFile (src, dest, flags, cb) { + if (typeof flags === 'function') { + cb = flags + flags = 0 + } + return go$copyFile(src, dest, flags, cb) - if (!(self instanceof ClassType)) { - return new ClassType(props) + function go$copyFile (src, dest, flags, cb, startTime) { + return fs$copyFile(src, dest, flags, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } } - Abstract.call(self) + var fs$readdir = fs.readdir + fs.readdir = readdir + var noReaddirOptionVersions = /^v[0-5]\./ + function readdir (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null - if (!props.path) { - self.error('Must provide a path', null, true) - } + var go$readdir = noReaddirOptionVersions.test(process.version) + ? function go$readdir (path, options, cb, startTime) { + return fs$readdir(path, fs$readdirCallback( + path, options, cb, startTime + )) + } + : function go$readdir (path, options, cb, startTime) { + return fs$readdir(path, options, fs$readdirCallback( + path, options, cb, startTime + )) + } - self.readable = true - self.writable = false + return go$readdir(path, options, cb) - self.type = type - self.props = props - self.depth = props.depth = props.depth || 0 - self.parent = props.parent || null - self.root = props.root || (props.parent && props.parent.root) || self + function fs$readdirCallback (path, options, cb, startTime) { + return function (err, files) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([ + go$readdir, + [path, options, cb], + err, + startTime || Date.now(), + Date.now() + ]) + else { + if (files && files.sort) + files.sort() - self._path = self.path = path.resolve(props.path) - if (process.platform === 'win32') { - self.path = self._path = self.path.replace(/\?/g, '_') - if (self._path.length >= 260) { - // how DOES one create files on the moon? - // if the path has spaces in it, then UNC will fail. - self._swallowErrors = true - // if (self._path.indexOf(" ") === -1) { - self._path = '\\\\?\\' + self.path.replace(/\//g, '\\') - // } + if (typeof cb === 'function') + cb.call(this, err, files) + } + } } } - self.basename = props.basename = path.basename(self.path) - self.dirname = props.dirname = path.dirname(self.path) - - // these have served their purpose, and are now just noisy clutter - props.parent = props.root = null - // console.error("\n\n\n%s setting size to", props.path, props.size) - self.size = props.size - self.filter = typeof props.filter === 'function' ? props.filter : null - if (props.sort === 'alpha') props.sort = alphasort - - // start the ball rolling. - // this will stat the thing, and then call self._read() - // to start reading whatever it is. - // console.error("calling stat", props.path, currentStat) - self._stat(currentStat) -} + if (process.version.substr(0, 4) === 'v0.8') { + var legStreams = legacy(fs) + ReadStream = legStreams.ReadStream + WriteStream = legStreams.WriteStream + } -function alphasort (a, b) { - return a === b ? 0 - : a.toLowerCase() > b.toLowerCase() ? 1 - : a.toLowerCase() < b.toLowerCase() ? -1 - : a > b ? 1 - : -1 -} + var fs$ReadStream = fs.ReadStream + if (fs$ReadStream) { + ReadStream.prototype = Object.create(fs$ReadStream.prototype) + ReadStream.prototype.open = ReadStream$open + } -Reader.prototype._stat = function (currentStat) { - var self = this - var props = self.props - var stat = props.follow ? 'stat' : 'lstat' - // console.error("Reader._stat", self._path, currentStat) - if (currentStat) process.nextTick(statCb.bind(null, null, currentStat)) - else fs[stat](self._path, statCb) + var fs$WriteStream = fs.WriteStream + if (fs$WriteStream) { + WriteStream.prototype = Object.create(fs$WriteStream.prototype) + WriteStream.prototype.open = WriteStream$open + } - function statCb (er, props_) { - // console.error("Reader._stat, statCb", self._path, props_, props_.nlink) - if (er) return self.error(er) + Object.defineProperty(fs, 'ReadStream', { + get: function () { + return ReadStream + }, + set: function (val) { + ReadStream = val + }, + enumerable: true, + configurable: true + }) + Object.defineProperty(fs, 'WriteStream', { + get: function () { + return WriteStream + }, + set: function (val) { + WriteStream = val + }, + enumerable: true, + configurable: true + }) - Object.keys(props_).forEach(function (k) { - props[k] = props_[k] - }) + // legacy names + var FileReadStream = ReadStream + Object.defineProperty(fs, 'FileReadStream', { + get: function () { + return FileReadStream + }, + set: function (val) { + FileReadStream = val + }, + enumerable: true, + configurable: true + }) + var FileWriteStream = WriteStream + Object.defineProperty(fs, 'FileWriteStream', { + get: function () { + return FileWriteStream + }, + set: function (val) { + FileWriteStream = val + }, + enumerable: true, + configurable: true + }) - // if it's not the expected size, then abort here. - if (undefined !== self.size && props.size !== self.size) { - return self.error('incorrect size') - } - self.size = props.size + function ReadStream (path, options) { + if (this instanceof ReadStream) + return fs$ReadStream.apply(this, arguments), this + else + return ReadStream.apply(Object.create(ReadStream.prototype), arguments) + } - var type = getType(props) - var handleHardlinks = props.hardlinks !== false + function ReadStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + if (that.autoClose) + that.destroy() - // special little thing for handling hardlinks. - if (handleHardlinks && type !== 'Directory' && props.nlink && props.nlink > 1) { - var k = props.dev + ':' + props.ino - // console.error("Reader has nlink", self._path, k) - if (hardLinks[k] === self._path || !hardLinks[k]) { - hardLinks[k] = self._path + that.emit('error', err) } else { - // switch into hardlink mode. - type = self.type = self.props.type = 'Link' - self.Link = self.props.Link = true - self.linkpath = self.props.linkpath = hardLinks[k] - // console.error("Hardlink detected, switching mode", self._path, self.linkpath) - // Setting __proto__ would arguably be the "correct" - // approach here, but that just seems too wrong. - self._stat = self._read = LinkReader.prototype._read - } - } - - if (self.type && self.type !== type) { - self.error('Unexpected type: ' + type) - } - - // if the filter doesn't pass, then just skip over this one. - // still have to emit end so that dir-walking can move on. - if (self.filter) { - var who = self._proxy || self - // special handling for ProxyReaders - if (!self.filter.call(who, who, props)) { - if (!self._disowned) { - self.abort() - self.emit('end') - self.emit('close') - } - return - } - } - - // last chance to abort or disown before the flow starts! - var events = ['_stat', 'stat', 'ready'] - var e = 0 - ;(function go () { - if (self._aborted) { - self.emit('end') - self.emit('close') - return - } - - if (self._paused && self.type !== 'Directory') { - self.once('resume', go) - return + that.fd = fd + that.emit('open', fd) + that.read() } + }) + } - var ev = events[e++] - if (!ev) { - return self._read() - } - self.emit(ev, props) - go() - })() + function WriteStream (path, options) { + if (this instanceof WriteStream) + return fs$WriteStream.apply(this, arguments), this + else + return WriteStream.apply(Object.create(WriteStream.prototype), arguments) } -} -Reader.prototype.pipe = function (dest) { - var self = this - if (typeof dest.add === 'function') { - // piping to a multi-compatible, and we've got directory entries. - self.on('entry', function (entry) { - var ret = dest.add(entry) - if (ret === false) { - self.pause() + function WriteStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + that.destroy() + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) } }) } - // console.error("R Pipe apply Stream Pipe") - return Stream.prototype.pipe.apply(this, arguments) -} - -Reader.prototype.pause = function (who) { - this._paused = true - who = who || this - this.emit('pause', who) - if (this._stream) this._stream.pause(who) -} - -Reader.prototype.resume = function (who) { - this._paused = false - who = who || this - this.emit('resume', who) - if (this._stream) this._stream.resume(who) - this._read() -} - -Reader.prototype._read = function () { - this.error('Cannot read unknown type: ' + this.type) -} - - -/***/ }), - -/***/ 2470: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -// Just get the stats, and then don't do anything. -// You can't really "read" from a socket. You "connect" to it. -// Mostly, this is here so that reading a dir with a socket in it -// doesn't blow up. - -module.exports = SocketReader + function createReadStream (path, options) { + return new fs.ReadStream(path, options) + } -var inherits = __nccwpck_require__(4124) -var Reader = __nccwpck_require__(3284) + function createWriteStream (path, options) { + return new fs.WriteStream(path, options) + } -inherits(SocketReader, Reader) + var fs$open = fs.open + fs.open = open + function open (path, flags, mode, cb) { + if (typeof mode === 'function') + cb = mode, mode = null -function SocketReader (props) { - var self = this - if (!(self instanceof SocketReader)) { - throw new Error('SocketReader must be called as constructor.') - } + return go$open(path, flags, mode, cb) - if (!(props.type === 'Socket' && props.Socket)) { - throw new Error('Non-socket type ' + props.type) + function go$open (path, flags, mode, cb, startTime) { + return fs$open(path, flags, mode, function (err, fd) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } } - Reader.call(self, props) + return fs } -SocketReader.prototype._read = function () { - var self = this - if (self._paused) return - // basically just a no-op, since we got all the info we have - // from the _stat method - if (!self._ended) { - self.emit('end') - self.emit('close') - self._ended = true - } +function enqueue (elem) { + debug('ENQUEUE', elem[0].name, elem[1]) + fs[gracefulQueue].push(elem) + retry() } +// keep track of the timeout between retry() calls +var retryTimer -/***/ }), - -/***/ 8680: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = Writer +// reset the startTime and lastTime to now +// this resets the start of the 60 second overall timeout as well as the +// delay between attempts so that we'll retry these jobs sooner +function resetQueue () { + var now = Date.now() + for (var i = 0; i < fs[gracefulQueue].length; ++i) { + // entries that are only a length of 2 are from an older version, don't + // bother modifying those since they'll be retried anyway. + if (fs[gracefulQueue][i].length > 2) { + fs[gracefulQueue][i][3] = now // startTime + fs[gracefulQueue][i][4] = now // lastTime + } + } + // call retry to make sure we're actively processing the queue + retry() +} -var fs = __nccwpck_require__(7758) -var inherits = __nccwpck_require__(4124) -var rimraf = __nccwpck_require__(4959) -var mkdir = __nccwpck_require__(6186) -var path = __nccwpck_require__(1017) -var umask = process.platform === 'win32' ? 0 : process.umask() -var getType = __nccwpck_require__(1600) -var Abstract = __nccwpck_require__(9479) +function retry () { + // clear the timer and remove it to help prevent unintended concurrency + clearTimeout(retryTimer) + retryTimer = undefined -// Must do this *before* loading the child classes -inherits(Writer, Abstract) + if (fs[gracefulQueue].length === 0) + return -Writer.dirmode = parseInt('0777', 8) & (~umask) -Writer.filemode = parseInt('0666', 8) & (~umask) + var elem = fs[gracefulQueue].shift() + var fn = elem[0] + var args = elem[1] + // these items may be unset if they were added by an older graceful-fs + var err = elem[2] + var startTime = elem[3] + var lastTime = elem[4] -var DirWriter = __nccwpck_require__(4745) -var LinkWriter = __nccwpck_require__(404) -var FileWriter = __nccwpck_require__(2539) -var ProxyWriter = __nccwpck_require__(2071) - -// props is the desired state. current is optionally the current stat, -// provided here so that subclasses can avoid statting the target -// more than necessary. -function Writer (props, current) { - var self = this - - if (typeof props === 'string') { - props = { path: props } + // if we don't have a startTime we have no way of knowing if we've waited + // long enough, so go ahead and retry this item now + if (startTime === undefined) { + debug('RETRY', fn.name, args) + fn.apply(null, args) + } else if (Date.now() - startTime >= 60000) { + // it's been more than 60 seconds total, bail now + debug('TIMEOUT', fn.name, args) + var cb = args.pop() + if (typeof cb === 'function') + cb.call(null, err) + } else { + // the amount of time between the last attempt and right now + var sinceAttempt = Date.now() - lastTime + // the amount of time between when we first tried, and when we last tried + // rounded up to at least 1 + var sinceStart = Math.max(lastTime - startTime, 1) + // backoff. wait longer than the total time we've been retrying, but only + // up to a maximum of 100ms + var desiredDelay = Math.min(sinceStart * 1.2, 100) + // it's been long enough since the last retry, do it again + if (sinceAttempt >= desiredDelay) { + debug('RETRY', fn.name, args) + fn.apply(null, args.concat([startTime])) + } else { + // if we can't do this job yet, push it to the end of the queue + // and let the next iteration check again + fs[gracefulQueue].push(elem) + } } - // polymorphism. - // call fstream.Writer(dir) to get a DirWriter object, etc. - var type = getType(props) - var ClassType = Writer - - switch (type) { - case 'Directory': - ClassType = DirWriter - break - case 'File': - ClassType = FileWriter - break - case 'Link': - case 'SymbolicLink': - ClassType = LinkWriter - break - case null: - default: - // Don't know yet what type to create, so we wrap in a proxy. - ClassType = ProxyWriter - break + // schedule our next run if one isn't already scheduled + if (retryTimer === undefined) { + retryTimer = setTimeout(retry, 0) } +} - if (!(self instanceof ClassType)) return new ClassType(props) - // now get down to business. +/***/ }), - Abstract.call(self) +/***/ 2270: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (!props.path) self.error('Must provide a path', null, true) +var Stream = (__nccwpck_require__(2203).Stream) - // props is what we want to set. - // set some convenience properties as well. - self.type = props.type - self.props = props - self.depth = props.depth || 0 - self.clobber = props.clobber === false ? props.clobber : true - self.parent = props.parent || null - self.root = props.root || (props.parent && props.parent.root) || self +module.exports = legacy - self._path = self.path = path.resolve(props.path) - if (process.platform === 'win32') { - self.path = self._path = self.path.replace(/\?/g, '_') - if (self._path.length >= 260) { - self._swallowErrors = true - self._path = '\\\\?\\' + self.path.replace(/\//g, '\\') - } +function legacy (fs) { + return { + ReadStream: ReadStream, + WriteStream: WriteStream } - self.basename = path.basename(props.path) - self.dirname = path.dirname(props.path) - self.linkpath = props.linkpath || null - - props.parent = props.root = null - // console.error("\n\n\n%s setting size to", props.path, props.size) - self.size = props.size + function ReadStream (path, options) { + if (!(this instanceof ReadStream)) return new ReadStream(path, options); - if (typeof props.mode === 'string') { - props.mode = parseInt(props.mode, 8) - } + Stream.call(this); - self.readable = false - self.writable = true + var self = this; - // buffer until ready, or while handling another entry - self._buffer = [] - self.ready = false + this.path = path; + this.fd = null; + this.readable = true; + this.paused = false; - self.filter = typeof props.filter === 'function' ? props.filter : null + this.flags = 'r'; + this.mode = 438; /*=0666*/ + this.bufferSize = 64 * 1024; - // start the ball rolling. - // this checks what's there already, and then calls - // self._create() to call the impl-specific creation stuff. - self._stat(current) -} + options = options || {}; -// Calling this means that it's something we can't create. -// Just assert that it's already there, otherwise raise a warning. -Writer.prototype._create = function () { - var self = this - fs[self.props.follow ? 'stat' : 'lstat'](self._path, function (er) { - if (er) { - return self.warn('Cannot create ' + self._path + '\n' + - 'Unsupported type: ' + self.type, 'ENOTSUP') + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; } - self._finish() - }) -} -Writer.prototype._stat = function (current) { - var self = this - var props = self.props - var stat = props.follow ? 'stat' : 'lstat' - var who = self._proxy || self + if (this.encoding) this.setEncoding(this.encoding); - if (current) statCb(null, current) - else fs[stat](self._path, statCb) + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.end === undefined) { + this.end = Infinity; + } else if ('number' !== typeof this.end) { + throw TypeError('end must be a Number'); + } - function statCb (er, current) { - if (self.filter && !self.filter.call(who, who, current)) { - self._aborted = true - self.emit('end') - self.emit('close') - return - } + if (this.start > this.end) { + throw new Error('start must be <= end'); + } - // if it's not there, great. We'll just create it. - // if it is there, then we'll need to change whatever differs - if (er || !current) { - return create(self) + this.pos = this.start; } - self._old = current - var currentType = getType(current) - - // if it's a type change, then we need to clobber or error. - // if it's not a type change, then let the impl take care of it. - if (currentType !== self.type || self.type === 'File' && current.nlink > 1) { - return rimraf(self._path, function (er) { - if (er) return self.error(er) - self._old = null - create(self) - }) + if (this.fd !== null) { + process.nextTick(function() { + self._read(); + }); + return; } - // otherwise, just handle in the app-specific way - // this creates a fs.WriteStream, or mkdir's, or whatever - create(self) - } -} - -function create (self) { - // console.error("W create", self._path, Writer.dirmode) - - // XXX Need to clobber non-dirs that are in the way, - // unless { clobber: false } in the props. - mkdir(path.dirname(self._path), Writer.dirmode, function (er, made) { - // console.error("W created", path.dirname(self._path), er) - if (er) return self.error(er) - - // later on, we have to set the mode and owner for these - self._madeDir = made - return self._create() - }) -} - -function endChmod (self, want, current, path, cb) { - var wantMode = want.mode - var chmod = want.follow || self.type !== 'SymbolicLink' - ? 'chmod' : 'lchmod' - - if (!fs[chmod]) return cb() - if (typeof wantMode !== 'number') return cb() - - var curMode = current.mode & parseInt('0777', 8) - wantMode = wantMode & parseInt('0777', 8) - if (wantMode === curMode) return cb() - - fs[chmod](path, wantMode, cb) -} - -function endChown (self, want, current, path, cb) { - // Don't even try it unless root. Too easy to EPERM. - if (process.platform === 'win32') return cb() - if (!process.getuid || process.getuid() !== 0) return cb() - if (typeof want.uid !== 'number' && - typeof want.gid !== 'number') return cb() - - if (current.uid === want.uid && - current.gid === want.gid) return cb() - - var chown = (self.props.follow || self.type !== 'SymbolicLink') - ? 'chown' : 'lchown' - if (!fs[chown]) return cb() - - if (typeof want.uid !== 'number') want.uid = current.uid - if (typeof want.gid !== 'number') want.gid = current.gid - - fs[chown](path, want.uid, want.gid, cb) -} - -function endUtimes (self, want, current, path, cb) { - if (!fs.utimes || process.platform === 'win32') return cb() - - var utimes = (want.follow || self.type !== 'SymbolicLink') - ? 'utimes' : 'lutimes' + fs.open(this.path, this.flags, this.mode, function (err, fd) { + if (err) { + self.emit('error', err); + self.readable = false; + return; + } - if (utimes === 'lutimes' && !fs[utimes]) { - utimes = 'utimes' + self.fd = fd; + self.emit('open', fd); + self._read(); + }) } - if (!fs[utimes]) return cb() - - var curA = current.atime - var curM = current.mtime - var meA = want.atime - var meM = want.mtime - - if (meA === undefined) meA = curA - if (meM === undefined) meM = curM - - if (!isDate(meA)) meA = new Date(meA) - if (!isDate(meM)) meA = new Date(meM) - - if (meA.getTime() === curA.getTime() && - meM.getTime() === curM.getTime()) return cb() + function WriteStream (path, options) { + if (!(this instanceof WriteStream)) return new WriteStream(path, options); - fs[utimes](path, meA, meM, cb) -} + Stream.call(this); -// XXX This function is beastly. Break it up! -Writer.prototype._finish = function () { - var self = this + this.path = path; + this.fd = null; + this.writable = true; - if (self._finishing) return - self._finishing = true + this.flags = 'w'; + this.encoding = 'binary'; + this.mode = 438; /*=0666*/ + this.bytesWritten = 0; - // console.error(" W Finish", self._path, self.size) + options = options || {}; - // set up all the things. - // At this point, we're already done writing whatever we've gotta write, - // adding files to the dir, etc. - var todo = 0 - var errState = null - var done = false + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } - if (self._old) { - // the times will almost *certainly* have changed. - // adds the utimes syscall, but remove another stat. - self._old.atime = new Date(0) - self._old.mtime = new Date(0) - // console.error(" W Finish Stale Stat", self._path, self.size) - setProps(self._old) - } else { - var stat = self.props.follow ? 'stat' : 'lstat' - // console.error(" W Finish Stating", self._path, self.size) - fs[stat](self._path, function (er, current) { - // console.error(" W Finish Stated", self._path, self.size, current) - if (er) { - // if we're in the process of writing out a - // directory, it's very possible that the thing we're linking to - // doesn't exist yet (especially if it was intended as a symlink), - // so swallow ENOENT errors here and just soldier on. - if (er.code === 'ENOENT' && - (self.type === 'Link' || self.type === 'SymbolicLink') && - process.platform === 'win32') { - self.ready = true - self.emit('ready') - self.emit('end') - self.emit('close') - self.end = self._finish = function () {} - return - } else return self.error(er) + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); } - setProps(self._old = current) - }) - } - - return - - function setProps (current) { - todo += 3 - endChmod(self, self.props, current, self._path, next('chmod')) - endChown(self, self.props, current, self._path, next('chown')) - endUtimes(self, self.props, current, self._path, next('utimes')) - } - - function next (what) { - return function (er) { - // console.error(" W Finish", what, todo) - if (errState) return - if (er) { - er.fstream_finish_call = what - return self.error(errState = er) + if (this.start < 0) { + throw new Error('start must be >= zero'); } - if (--todo > 0) return - if (done) return - done = true - // we may still need to set the mode/etc. on some parent dirs - // that were created previously. delay end/close until then. - if (!self._madeDir) return end() - else endMadeDir(self, self._path, end) - - function end (er) { - if (er) { - er.fstream_finish_call = 'setupMadeDir' - return self.error(er) - } - // all the props have been set, so we're completely done. - self.emit('end') - self.emit('close') - } + this.pos = this.start; } - } -} -function endMadeDir (self, p, cb) { - var made = self._madeDir - // everything *between* made and path.dirname(self._path) - // needs to be set up. Note that this may just be one dir. - var d = path.dirname(p) + this.busy = false; + this._queue = []; - endMadeDir_(self, d, function (er) { - if (er) return cb(er) - if (d === made) { - return cb() + if (this.fd === null) { + this._open = fs.open; + this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); + this.flush(); } - endMadeDir(self, d, cb) - }) + } } -function endMadeDir_ (self, p, cb) { - var dirProps = {} - Object.keys(self.props).forEach(function (k) { - dirProps[k] = self.props[k] - // only make non-readable dirs if explicitly requested. - if (k === 'mode' && self.type !== 'Directory') { - dirProps[k] = dirProps[k] | parseInt('0111', 8) - } - }) - - var todo = 3 - var errState = null - fs.stat(p, function (er, current) { - if (er) return cb(errState = er) - endChmod(self, dirProps, current, p, next) - endChown(self, dirProps, current, p, next) - endUtimes(self, dirProps, current, p, next) - }) +/***/ }), - function next (er) { - if (errState) return - if (er) return cb(errState = er) - if (--todo === 0) return cb() - } -} +/***/ 3501: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Writer.prototype.pipe = function () { - this.error("Can't pipe from writable stream") -} +var constants = __nccwpck_require__(9140) -Writer.prototype.add = function () { - this.error("Can't add to non-Directory type") -} +var origCwd = process.cwd +var cwd = null -Writer.prototype.write = function () { - return true -} +var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform -function objectToString (d) { - return Object.prototype.toString.call(d) +process.cwd = function() { + if (!cwd) + cwd = origCwd.call(process) + return cwd } +try { + process.cwd() +} catch (er) {} -function isDate (d) { - return typeof d === 'object' && objectToString(d) === '[object Date]' +// This check is needed until node.js 12 is required +if (typeof process.chdir === 'function') { + var chdir = process.chdir + process.chdir = function (d) { + cwd = null + chdir.call(process, d) + } + if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir) } +module.exports = patch -/***/ }), - -/***/ 1585: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -const {PassThrough: PassThroughStream} = __nccwpck_require__(2781); - -module.exports = options => { - options = {...options}; +function patch (fs) { + // (re-)implement some things that are known busted or missing. - const {array} = options; - let {encoding} = options; - const isBuffer = encoding === 'buffer'; - let objectMode = false; + // lchmod, broken prior to 0.6.2 + // back-port the fix here. + if (constants.hasOwnProperty('O_SYMLINK') && + process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { + patchLchmod(fs) + } - if (array) { - objectMode = !(encoding || isBuffer); - } else { - encoding = encoding || 'utf8'; - } + // lutimes implementation, or no-op + if (!fs.lutimes) { + patchLutimes(fs) + } - if (isBuffer) { - encoding = null; - } + // https://github.com/isaacs/node-graceful-fs/issues/4 + // Chown should not fail on einval or eperm if non-root. + // It should not fail on enosys ever, as this just indicates + // that a fs doesn't support the intended operation. - const stream = new PassThroughStream({objectMode}); + fs.chown = chownFix(fs.chown) + fs.fchown = chownFix(fs.fchown) + fs.lchown = chownFix(fs.lchown) - if (encoding) { - stream.setEncoding(encoding); - } + fs.chmod = chmodFix(fs.chmod) + fs.fchmod = chmodFix(fs.fchmod) + fs.lchmod = chmodFix(fs.lchmod) - let length = 0; - const chunks = []; + fs.chownSync = chownFixSync(fs.chownSync) + fs.fchownSync = chownFixSync(fs.fchownSync) + fs.lchownSync = chownFixSync(fs.lchownSync) - stream.on('data', chunk => { - chunks.push(chunk); + fs.chmodSync = chmodFixSync(fs.chmodSync) + fs.fchmodSync = chmodFixSync(fs.fchmodSync) + fs.lchmodSync = chmodFixSync(fs.lchmodSync) - if (objectMode) { - length = chunks.length; - } else { - length += chunk.length; - } - }); + fs.stat = statFix(fs.stat) + fs.fstat = statFix(fs.fstat) + fs.lstat = statFix(fs.lstat) - stream.getBufferedValue = () => { - if (array) { - return chunks; - } + fs.statSync = statFixSync(fs.statSync) + fs.fstatSync = statFixSync(fs.fstatSync) + fs.lstatSync = statFixSync(fs.lstatSync) - return isBuffer ? Buffer.concat(chunks, length) : chunks.join(''); - }; - - stream.getBufferedLength = () => length; - - return stream; -}; - - -/***/ }), - -/***/ 1766: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -const {constants: BufferConstants} = __nccwpck_require__(4300); -const stream = __nccwpck_require__(2781); -const {promisify} = __nccwpck_require__(3837); -const bufferStream = __nccwpck_require__(1585); - -const streamPipelinePromisified = promisify(stream.pipeline); - -class MaxBufferError extends Error { - constructor() { - super('maxBuffer exceeded'); - this.name = 'MaxBufferError'; - } -} - -async function getStream(inputStream, options) { - if (!inputStream) { - throw new Error('Expected a stream'); - } - - options = { - maxBuffer: Infinity, - ...options - }; - - const {maxBuffer} = options; - const stream = bufferStream(options); - - await new Promise((resolve, reject) => { - const rejectPromise = error => { - // Don't retrieve an oversized buffer. - if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) { - error.bufferedData = stream.getBufferedValue(); - } - - reject(error); - }; - - (async () => { - try { - await streamPipelinePromisified(inputStream, stream); - resolve(); - } catch (error) { - rejectPromise(error); - } - })(); - - stream.on('data', () => { - if (stream.getBufferedLength() > maxBuffer) { - rejectPromise(new MaxBufferError()); - } - }); - }); - - return stream.getBufferedValue(); -} + // if lchmod/lchown do not exist, then make them no-ops + if (fs.chmod && !fs.lchmod) { + fs.lchmod = function (path, mode, cb) { + if (cb) process.nextTick(cb) + } + fs.lchmodSync = function () {} + } + if (fs.chown && !fs.lchown) { + fs.lchown = function (path, uid, gid, cb) { + if (cb) process.nextTick(cb) + } + fs.lchownSync = function () {} + } -module.exports = getStream; -module.exports.buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'}); -module.exports.array = (stream, options) => getStream(stream, {...options, array: true}); -module.exports.MaxBufferError = MaxBufferError; + // on Windows, A/V software can lock the directory, causing this + // to fail with an EACCES or EPERM if the directory contains newly + // created files. Try again on failure, for up to 60 seconds. + // Set the timeout this long because some Windows Anti-Virus, such as Parity + // bit9, may lock files for up to a minute, causing npm package install + // failures. Also, take care to yield the scheduler. Windows scheduling gives + // CPU to a busy looping process, which can cause the program causing the lock + // contention to be starved of CPU by node, so the contention doesn't resolve. + if (platform === "win32") { + fs.rename = typeof fs.rename !== 'function' ? fs.rename + : (function (fs$rename) { + function rename (from, to, cb) { + var start = Date.now() + var backoff = 0; + fs$rename(from, to, function CB (er) { + if (er + && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") + && Date.now() - start < 60000) { + setTimeout(function() { + fs.stat(to, function (stater, st) { + if (stater && stater.code === "ENOENT") + fs$rename(from, to, CB); + else + cb(er) + }) + }, backoff) + if (backoff < 100) + backoff += 10; + return; + } + if (cb) cb(er) + }) + } + if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename) + return rename + })(fs.rename) + } -/***/ }), + // if read() returns EAGAIN, then just try it again. + fs.read = typeof fs.read !== 'function' ? fs.read + : (function (fs$read) { + function read (fd, buffer, offset, length, position, callback_) { + var callback + if (callback_ && typeof callback_ === 'function') { + var eagCounter = 0 + callback = function (er, _, __) { + if (er && er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } + callback_.apply(this, arguments) + } + } + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } -/***/ 7625: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // This ensures `util.promisify` works as it does for native `fs.read`. + if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read) + return read + })(fs.read) -exports.setopts = setopts -exports.ownProp = ownProp -exports.makeAbs = makeAbs -exports.finish = finish -exports.mark = mark -exports.isIgnored = isIgnored -exports.childrenIgnored = childrenIgnored + fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync + : (function (fs$readSync) { return function (fd, buffer, offset, length, position) { + var eagCounter = 0 + while (true) { + try { + return fs$readSync.call(fs, fd, buffer, offset, length, position) + } catch (er) { + if (er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + continue + } + throw er + } + } + }})(fs.readSync) -function ownProp (obj, field) { - return Object.prototype.hasOwnProperty.call(obj, field) -} + function patchLchmod (fs) { + fs.lchmod = function (path, mode, callback) { + fs.open( path + , constants.O_WRONLY | constants.O_SYMLINK + , mode + , function (err, fd) { + if (err) { + if (callback) callback(err) + return + } + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + fs.fchmod(fd, mode, function (err) { + fs.close(fd, function(err2) { + if (callback) callback(err || err2) + }) + }) + }) + } -var fs = __nccwpck_require__(7147) -var path = __nccwpck_require__(1017) -var minimatch = __nccwpck_require__(3973) -var isAbsolute = __nccwpck_require__(8714) -var Minimatch = minimatch.Minimatch + fs.lchmodSync = function (path, mode) { + var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) -function alphasort (a, b) { - return a.localeCompare(b, 'en') -} + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + var threw = true + var ret + try { + ret = fs.fchmodSync(fd, mode) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } + } -function setupIgnores (self, options) { - self.ignore = options.ignore || [] + function patchLutimes (fs) { + if (constants.hasOwnProperty("O_SYMLINK") && fs.futimes) { + fs.lutimes = function (path, at, mt, cb) { + fs.open(path, constants.O_SYMLINK, function (er, fd) { + if (er) { + if (cb) cb(er) + return + } + fs.futimes(fd, at, mt, function (er) { + fs.close(fd, function (er2) { + if (cb) cb(er || er2) + }) + }) + }) + } - if (!Array.isArray(self.ignore)) - self.ignore = [self.ignore] + fs.lutimesSync = function (path, at, mt) { + var fd = fs.openSync(path, constants.O_SYMLINK) + var ret + var threw = true + try { + ret = fs.futimesSync(fd, at, mt) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } - if (self.ignore.length) { - self.ignore = self.ignore.map(ignoreMap) + } else if (fs.futimes) { + fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } + fs.lutimesSync = function () {} + } } -} -// ignore patterns are always in dot:true mode. -function ignoreMap (pattern) { - var gmatcher = null - if (pattern.slice(-3) === '/**') { - var gpattern = pattern.replace(/(\/\*\*)+$/, '') - gmatcher = new Minimatch(gpattern, { dot: true }) + function chmodFix (orig) { + if (!orig) return orig + return function (target, mode, cb) { + return orig.call(fs, target, mode, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } } - return { - matcher: new Minimatch(pattern, { dot: true }), - gmatcher: gmatcher - } -} - -function setopts (self, pattern, options) { - if (!options) - options = {} - - // base-matching: just use globstar for that. - if (options.matchBase && -1 === pattern.indexOf("/")) { - if (options.noglobstar) { - throw new Error("base matching requires globstar") - } - pattern = "**/" + pattern - } - - self.silent = !!options.silent - self.pattern = pattern - self.strict = options.strict !== false - self.realpath = !!options.realpath - self.realpathCache = options.realpathCache || Object.create(null) - self.follow = !!options.follow - self.dot = !!options.dot - self.mark = !!options.mark - self.nodir = !!options.nodir - if (self.nodir) - self.mark = true - self.sync = !!options.sync - self.nounique = !!options.nounique - self.nonull = !!options.nonull - self.nosort = !!options.nosort - self.nocase = !!options.nocase - self.stat = !!options.stat - self.noprocess = !!options.noprocess - self.absolute = !!options.absolute - self.fs = options.fs || fs - - self.maxLength = options.maxLength || Infinity - self.cache = options.cache || Object.create(null) - self.statCache = options.statCache || Object.create(null) - self.symlinks = options.symlinks || Object.create(null) - - setupIgnores(self, options) - - self.changedCwd = false - var cwd = process.cwd() - if (!ownProp(options, "cwd")) - self.cwd = cwd - else { - self.cwd = path.resolve(options.cwd) - self.changedCwd = self.cwd !== cwd - } - - self.root = options.root || path.resolve(self.cwd, "/") - self.root = path.resolve(self.root) - if (process.platform === "win32") - self.root = self.root.replace(/\\/g, "/") - - // TODO: is an absolute `cwd` supposed to be resolved against `root`? - // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') - self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd) - if (process.platform === "win32") - self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") - self.nomount = !!options.nomount - - // disable comments and negation in Minimatch. - // Note that they are not supported in Glob itself anyway. - options.nonegate = true - options.nocomment = true - // always treat \ in patterns as escapes, not path separators - options.allowWindowsEscape = false - - self.minimatch = new Minimatch(pattern, options) - self.options = self.minimatch.options -} - -function finish (self) { - var nou = self.nounique - var all = nou ? [] : Object.create(null) - - for (var i = 0, l = self.matches.length; i < l; i ++) { - var matches = self.matches[i] - if (!matches || Object.keys(matches).length === 0) { - if (self.nonull) { - // do like the shell, and spit out the literal glob - var literal = self.minimatch.globSet[i] - if (nou) - all.push(literal) - else - all[literal] = true + function chmodFixSync (orig) { + if (!orig) return orig + return function (target, mode) { + try { + return orig.call(fs, target, mode) + } catch (er) { + if (!chownErOk(er)) throw er } - } else { - // had matches - var m = Object.keys(matches) - if (nou) - all.push.apply(all, m) - else - m.forEach(function (m) { - all[m] = true - }) } } - if (!nou) - all = Object.keys(all) - if (!self.nosort) - all = all.sort(alphasort) - - // at *some* point we statted all of these - if (self.mark) { - for (var i = 0; i < all.length; i++) { - all[i] = self._mark(all[i]) - } - if (self.nodir) { - all = all.filter(function (e) { - var notDir = !(/\/$/.test(e)) - var c = self.cache[e] || self.cache[makeAbs(self, e)] - if (notDir && c) - notDir = c !== 'DIR' && !Array.isArray(c) - return notDir + function chownFix (orig) { + if (!orig) return orig + return function (target, uid, gid, cb) { + return orig.call(fs, target, uid, gid, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) }) } } - if (self.ignore.length) - all = all.filter(function(m) { - return !isIgnored(self, m) - }) - - self.found = all -} - -function mark (self, p) { - var abs = makeAbs(self, p) - var c = self.cache[abs] - var m = p - if (c) { - var isDir = c === 'DIR' || Array.isArray(c) - var slash = p.slice(-1) === '/' - - if (isDir && !slash) - m += '/' - else if (!isDir && slash) - m = m.slice(0, -1) - - if (m !== p) { - var mabs = makeAbs(self, m) - self.statCache[mabs] = self.statCache[abs] - self.cache[mabs] = self.cache[abs] + function chownFixSync (orig) { + if (!orig) return orig + return function (target, uid, gid) { + try { + return orig.call(fs, target, uid, gid) + } catch (er) { + if (!chownErOk(er)) throw er + } } } - return m -} - -// lotta situps... -function makeAbs (self, f) { - var abs = f - if (f.charAt(0) === '/') { - abs = path.join(self.root, f) - } else if (isAbsolute(f) || f === '') { - abs = f - } else if (self.changedCwd) { - abs = path.resolve(self.cwd, f) - } else { - abs = path.resolve(f) - } - - if (process.platform === 'win32') - abs = abs.replace(/\\/g, '/') + function statFix (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } + function callback (er, stats) { + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + } + if (cb) cb.apply(this, arguments) + } + return options ? orig.call(fs, target, options, callback) + : orig.call(fs, target, callback) + } + } - return abs -} + function statFixSync (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options) { + var stats = options ? orig.call(fs, target, options) + : orig.call(fs, target) + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + } + return stats; + } + } + // ENOSYS means that the fs doesn't support the op. Just ignore + // that, because it doesn't matter. + // + // if there's no getuid, or if getuid() is something other + // than 0, and the error is EINVAL or EPERM, then just ignore + // it. + // + // This specific case is a silent failure in cp, install, tar, + // and most other unix tools that manage permissions. + // + // When running as root, or if other types of errors are + // encountered, then it's strict. + function chownErOk (er) { + if (!er) + return true -// Return true, if pattern ends with globstar '**', for the accompanying parent directory. -// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents -function isIgnored (self, path) { - if (!self.ignore.length) - return false + if (er.code === "ENOSYS") + return true - return self.ignore.some(function(item) { - return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) - }) -} + var nonroot = !process.getuid || process.getuid() !== 0 + if (nonroot) { + if (er.code === "EINVAL" || er.code === "EPERM") + return true + } -function childrenIgnored (self, path) { - if (!self.ignore.length) return false - - return self.ignore.some(function(item) { - return !!(item.gmatcher && item.gmatcher.match(path)) - }) + } } /***/ }), -/***/ 1957: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 4584: +/***/ ((module) => { -// Approach: -// -// 1. Get the minimatch set -// 2. For each pattern in the set, PROCESS(pattern, false) -// 3. Store matches per-set, then uniq them -// -// PROCESS(pattern, inGlobStar) -// Get the first [n] items from pattern that are all strings -// Join these together. This is PREFIX. -// If there is no more remaining, then stat(PREFIX) and -// add to matches if it succeeds. END. -// -// If inGlobStar and PREFIX is symlink and points to dir -// set ENTRIES = [] -// else readdir(PREFIX) as ENTRIES -// If fail, END -// -// with ENTRIES -// If pattern[n] is GLOBSTAR -// // handle the case where the globstar match is empty -// // by pruning it out, and testing the resulting pattern -// PROCESS(pattern[0..n] + pattern[n+1 .. $], false) -// // handle other cases. -// for ENTRY in ENTRIES (not dotfiles) -// // attach globstar + tail onto the entry -// // Mark that this entry is a globstar match -// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) -// -// else // not globstar -// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) -// Test ENTRY against pattern[n] -// If fails, continue -// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) -// -// Caveat: -// Cache all stats and readdirs results to minimize syscall. Since all -// we ever care about is existence and directory-ness, we can just keep -// `true` for files, and [children,...] for directories, or `false` for -// things that don't exist. -module.exports = glob +// rfc7231 6.1 +const statusCodeCacheableByDefault = new Set([ + 200, + 203, + 204, + 206, + 300, + 301, + 308, + 404, + 405, + 410, + 414, + 501, +]); -var rp = __nccwpck_require__(6863) -var minimatch = __nccwpck_require__(3973) -var Minimatch = minimatch.Minimatch -var inherits = __nccwpck_require__(4124) -var EE = (__nccwpck_require__(2361).EventEmitter) -var path = __nccwpck_require__(1017) -var assert = __nccwpck_require__(9491) -var isAbsolute = __nccwpck_require__(8714) -var globSync = __nccwpck_require__(9010) -var common = __nccwpck_require__(7625) -var setopts = common.setopts -var ownProp = common.ownProp -var inflight = __nccwpck_require__(2492) -var util = __nccwpck_require__(3837) -var childrenIgnored = common.childrenIgnored -var isIgnored = common.isIgnored +// This implementation does not understand partial responses (206) +const understoodStatuses = new Set([ + 200, + 203, + 204, + 300, + 301, + 302, + 303, + 307, + 308, + 404, + 405, + 410, + 414, + 501, +]); -var once = __nccwpck_require__(1223) +const errorStatusCodes = new Set([ + 500, + 502, + 503, + 504, +]); -function glob (pattern, options, cb) { - if (typeof options === 'function') cb = options, options = {} - if (!options) options = {} +const hopByHopHeaders = { + date: true, // included, because we add Age update Date + connection: true, + 'keep-alive': true, + 'proxy-authenticate': true, + 'proxy-authorization': true, + te: true, + trailer: true, + 'transfer-encoding': true, + upgrade: true, +}; - if (options.sync) { - if (cb) - throw new TypeError('callback provided to sync glob') - return globSync(pattern, options) - } +const excludedFromRevalidationUpdate = { + // Since the old body is reused, it doesn't make sense to change properties of the body + 'content-length': true, + 'content-encoding': true, + 'transfer-encoding': true, + 'content-range': true, +}; - return new Glob(pattern, options, cb) +function toNumberOrZero(s) { + const n = parseInt(s, 10); + return isFinite(n) ? n : 0; } -glob.sync = globSync -var GlobSync = glob.GlobSync = globSync.GlobSync - -// old api surface -glob.glob = glob - -function extend (origin, add) { - if (add === null || typeof add !== 'object') { - return origin - } - - var keys = Object.keys(add) - var i = keys.length - while (i--) { - origin[keys[i]] = add[keys[i]] - } - return origin +// RFC 5861 +function isErrorResponse(response) { + // consider undefined response as faulty + if(!response) { + return true + } + return errorStatusCodes.has(response.status); } -glob.hasMagic = function (pattern, options_) { - var options = extend({}, options_) - options.noprocess = true - - var g = new Glob(pattern, options) - var set = g.minimatch.set - - if (!pattern) - return false - - if (set.length > 1) - return true +function parseCacheControl(header) { + const cc = {}; + if (!header) return cc; - for (var j = 0; j < set[0].length; j++) { - if (typeof set[0][j] !== 'string') - return true - } + // TODO: When there is more than one value present for a given directive (e.g., two Expires header fields, multiple Cache-Control: max-age directives), + // the directive's value is considered invalid. Caches are encouraged to consider responses that have invalid freshness information to be stale + const parts = header.trim().split(/,/); + for (const part of parts) { + const [k, v] = part.split(/=/, 2); + cc[k.trim()] = v === undefined ? true : v.trim().replace(/^"|"$/g, ''); + } - return false + return cc; } -glob.Glob = Glob -inherits(Glob, EE) -function Glob (pattern, options, cb) { - if (typeof options === 'function') { - cb = options - options = null - } - - if (options && options.sync) { - if (cb) - throw new TypeError('callback provided to sync glob') - return new GlobSync(pattern, options) - } - - if (!(this instanceof Glob)) - return new Glob(pattern, options, cb) - - setopts(this, pattern, options) - this._didRealPath = false - - // process each pattern in the minimatch set - var n = this.minimatch.set.length - - // The matches are stored as {: true,...} so that - // duplicates are automagically pruned. - // Later, we do an Object.keys() on these. - // Keep them as a list so we can fill in when nonull is set. - this.matches = new Array(n) +function formatCacheControl(cc) { + let parts = []; + for (const k in cc) { + const v = cc[k]; + parts.push(v === true ? k : k + '=' + v); + } + if (!parts.length) { + return undefined; + } + return parts.join(', '); +} - if (typeof cb === 'function') { - cb = once(cb) - this.on('error', cb) - this.on('end', function (matches) { - cb(null, matches) - }) - } +module.exports = class CachePolicy { + constructor( + req, + res, + { + shared, + cacheHeuristic, + immutableMinTimeToLive, + ignoreCargoCult, + _fromObject, + } = {} + ) { + if (_fromObject) { + this._fromObject(_fromObject); + return; + } - var self = this - this._processing = 0 + if (!res || !res.headers) { + throw Error('Response headers missing'); + } + this._assertRequestHasHeaders(req); - this._emitQueue = [] - this._processQueue = [] - this.paused = false + this._responseTime = this.now(); + this._isShared = shared !== false; + this._cacheHeuristic = + undefined !== cacheHeuristic ? cacheHeuristic : 0.1; // 10% matches IE + this._immutableMinTtl = + undefined !== immutableMinTimeToLive + ? immutableMinTimeToLive + : 24 * 3600 * 1000; - if (this.noprocess) - return this + this._status = 'status' in res ? res.status : 200; + this._resHeaders = res.headers; + this._rescc = parseCacheControl(res.headers['cache-control']); + this._method = 'method' in req ? req.method : 'GET'; + this._url = req.url; + this._host = req.headers.host; + this._noAuthorization = !req.headers.authorization; + this._reqHeaders = res.headers.vary ? req.headers : null; // Don't keep all request headers if they won't be used + this._reqcc = parseCacheControl(req.headers['cache-control']); - if (n === 0) - return done() + // Assume that if someone uses legacy, non-standard uncecessary options they don't understand caching, + // so there's no point stricly adhering to the blindly copy&pasted directives. + if ( + ignoreCargoCult && + 'pre-check' in this._rescc && + 'post-check' in this._rescc + ) { + delete this._rescc['pre-check']; + delete this._rescc['post-check']; + delete this._rescc['no-cache']; + delete this._rescc['no-store']; + delete this._rescc['must-revalidate']; + this._resHeaders = Object.assign({}, this._resHeaders, { + 'cache-control': formatCacheControl(this._rescc), + }); + delete this._resHeaders.expires; + delete this._resHeaders.pragma; + } - var sync = true - for (var i = 0; i < n; i ++) { - this._process(this.minimatch.set[i], i, false, done) - } - sync = false + // When the Cache-Control header field is not present in a request, caches MUST consider the no-cache request pragma-directive + // as having the same effect as if "Cache-Control: no-cache" were present (see Section 5.2.1). + if ( + res.headers['cache-control'] == null && + /no-cache/.test(res.headers.pragma) + ) { + this._rescc['no-cache'] = true; + } + } - function done () { - --self._processing - if (self._processing <= 0) { - if (sync) { - process.nextTick(function () { - self._finish() - }) - } else { - self._finish() - } + now() { + return Date.now(); } - } -} -Glob.prototype._finish = function () { - assert(this instanceof Glob) - if (this.aborted) - return - - if (this.realpath && !this._didRealpath) - return this._realpath() + storable() { + // The "no-store" request directive indicates that a cache MUST NOT store any part of either this request or any response to it. + return !!( + !this._reqcc['no-store'] && + // A cache MUST NOT store a response to any request, unless: + // The request method is understood by the cache and defined as being cacheable, and + ('GET' === this._method || + 'HEAD' === this._method || + ('POST' === this._method && this._hasExplicitExpiration())) && + // the response status code is understood by the cache, and + understoodStatuses.has(this._status) && + // the "no-store" cache directive does not appear in request or response header fields, and + !this._rescc['no-store'] && + // the "private" response directive does not appear in the response, if the cache is shared, and + (!this._isShared || !this._rescc.private) && + // the Authorization header field does not appear in the request, if the cache is shared, + (!this._isShared || + this._noAuthorization || + this._allowsStoringAuthenticated()) && + // the response either: + // contains an Expires header field, or + (this._resHeaders.expires || + // contains a max-age response directive, or + // contains a s-maxage response directive and the cache is shared, or + // contains a public response directive. + this._rescc['max-age'] || + (this._isShared && this._rescc['s-maxage']) || + this._rescc.public || + // has a status code that is defined as cacheable by default + statusCodeCacheableByDefault.has(this._status)) + ); + } - common.finish(this) - this.emit('end', this.found) -} + _hasExplicitExpiration() { + // 4.2.1 Calculating Freshness Lifetime + return ( + (this._isShared && this._rescc['s-maxage']) || + this._rescc['max-age'] || + this._resHeaders.expires + ); + } -Glob.prototype._realpath = function () { - if (this._didRealpath) - return + _assertRequestHasHeaders(req) { + if (!req || !req.headers) { + throw Error('Request headers missing'); + } + } - this._didRealpath = true + satisfiesWithoutRevalidation(req) { + this._assertRequestHasHeaders(req); - var n = this.matches.length - if (n === 0) - return this._finish() + // When presented with a request, a cache MUST NOT reuse a stored response, unless: + // the presented request does not contain the no-cache pragma (Section 5.4), nor the no-cache cache directive, + // unless the stored response is successfully validated (Section 4.3), and + const requestCC = parseCacheControl(req.headers['cache-control']); + if (requestCC['no-cache'] || /no-cache/.test(req.headers.pragma)) { + return false; + } - var self = this - for (var i = 0; i < this.matches.length; i++) - this._realpathSet(i, next) + if (requestCC['max-age'] && this.age() > requestCC['max-age']) { + return false; + } - function next () { - if (--n === 0) - self._finish() - } -} + if ( + requestCC['min-fresh'] && + this.timeToLive() < 1000 * requestCC['min-fresh'] + ) { + return false; + } -Glob.prototype._realpathSet = function (index, cb) { - var matchset = this.matches[index] - if (!matchset) - return cb() + // the stored response is either: + // fresh, or allowed to be served stale + if (this.stale()) { + const allowsStale = + requestCC['max-stale'] && + !this._rescc['must-revalidate'] && + (true === requestCC['max-stale'] || + requestCC['max-stale'] > this.age() - this.maxAge()); + if (!allowsStale) { + return false; + } + } - var found = Object.keys(matchset) - var self = this - var n = found.length + return this._requestMatches(req, false); + } - if (n === 0) - return cb() + _requestMatches(req, allowHeadMethod) { + // The presented effective request URI and that of the stored response match, and + return ( + (!this._url || this._url === req.url) && + this._host === req.headers.host && + // the request method associated with the stored response allows it to be used for the presented request, and + (!req.method || + this._method === req.method || + (allowHeadMethod && 'HEAD' === req.method)) && + // selecting header fields nominated by the stored response (if any) match those presented, and + this._varyMatches(req) + ); + } - var set = this.matches[index] = Object.create(null) - found.forEach(function (p, i) { - // If there's a problem with the stat, then it means that - // one or more of the links in the realpath couldn't be - // resolved. just return the abs value in that case. - p = self._makeAbs(p) - rp.realpath(p, self.realpathCache, function (er, real) { - if (!er) - set[real] = true - else if (er.syscall === 'stat') - set[p] = true - else - self.emit('error', er) // srsly wtf right here + _allowsStoringAuthenticated() { + // following Cache-Control response directives (Section 5.2.2) have such an effect: must-revalidate, public, and s-maxage. + return ( + this._rescc['must-revalidate'] || + this._rescc.public || + this._rescc['s-maxage'] + ); + } - if (--n === 0) { - self.matches[index] = set - cb() - } - }) - }) -} + _varyMatches(req) { + if (!this._resHeaders.vary) { + return true; + } -Glob.prototype._mark = function (p) { - return common.mark(this, p) -} + // A Vary header field-value of "*" always fails to match + if (this._resHeaders.vary === '*') { + return false; + } -Glob.prototype._makeAbs = function (f) { - return common.makeAbs(this, f) -} + const fields = this._resHeaders.vary + .trim() + .toLowerCase() + .split(/\s*,\s*/); + for (const name of fields) { + if (req.headers[name] !== this._reqHeaders[name]) return false; + } + return true; + } -Glob.prototype.abort = function () { - this.aborted = true - this.emit('abort') -} + _copyWithoutHopByHopHeaders(inHeaders) { + const headers = {}; + for (const name in inHeaders) { + if (hopByHopHeaders[name]) continue; + headers[name] = inHeaders[name]; + } + // 9.1. Connection + if (inHeaders.connection) { + const tokens = inHeaders.connection.trim().split(/\s*,\s*/); + for (const name of tokens) { + delete headers[name]; + } + } + if (headers.warning) { + const warnings = headers.warning.split(/,/).filter(warning => { + return !/^\s*1[0-9][0-9]/.test(warning); + }); + if (!warnings.length) { + delete headers.warning; + } else { + headers.warning = warnings.join(',').trim(); + } + } + return headers; + } -Glob.prototype.pause = function () { - if (!this.paused) { - this.paused = true - this.emit('pause') - } -} + responseHeaders() { + const headers = this._copyWithoutHopByHopHeaders(this._resHeaders); + const age = this.age(); -Glob.prototype.resume = function () { - if (this.paused) { - this.emit('resume') - this.paused = false - if (this._emitQueue.length) { - var eq = this._emitQueue.slice(0) - this._emitQueue.length = 0 - for (var i = 0; i < eq.length; i ++) { - var e = eq[i] - this._emitMatch(e[0], e[1]) - } - } - if (this._processQueue.length) { - var pq = this._processQueue.slice(0) - this._processQueue.length = 0 - for (var i = 0; i < pq.length; i ++) { - var p = pq[i] - this._processing-- - this._process(p[0], p[1], p[2], p[3]) - } + // A cache SHOULD generate 113 warning if it heuristically chose a freshness + // lifetime greater than 24 hours and the response's age is greater than 24 hours. + if ( + age > 3600 * 24 && + !this._hasExplicitExpiration() && + this.maxAge() > 3600 * 24 + ) { + headers.warning = + (headers.warning ? `${headers.warning}, ` : '') + + '113 - "rfc7234 5.5.4"'; + } + headers.age = `${Math.round(age)}`; + headers.date = new Date(this.now()).toUTCString(); + return headers; } - } -} - -Glob.prototype._process = function (pattern, index, inGlobStar, cb) { - assert(this instanceof Glob) - assert(typeof cb === 'function') - if (this.aborted) - return + /** + * Value of the Date response header or current time if Date was invalid + * @return timestamp + */ + date() { + const serverDate = Date.parse(this._resHeaders.date); + if (isFinite(serverDate)) { + return serverDate; + } + return this._responseTime; + } - this._processing++ - if (this.paused) { - this._processQueue.push([pattern, index, inGlobStar, cb]) - return - } + /** + * Value of the Age header, in seconds, updated for the current time. + * May be fractional. + * + * @return Number + */ + age() { + let age = this._ageValue(); - //console.error('PROCESS %d', this._processing, pattern) + const residentTime = (this.now() - this._responseTime) / 1000; + return age + residentTime; + } - // Get the first [n] parts of pattern that are all strings. - var n = 0 - while (typeof pattern[n] === 'string') { - n ++ - } - // now n is the index of the first one that is *not* a string. + _ageValue() { + return toNumberOrZero(this._resHeaders.age); + } - // see if there's anything else - var prefix - switch (n) { - // if not, then this is rather simple - case pattern.length: - this._processSimple(pattern.join('/'), index, cb) - return + /** + * Value of applicable max-age (or heuristic equivalent) in seconds. This counts since response's `Date`. + * + * For an up-to-date value, see `timeToLive()`. + * + * @return Number + */ + maxAge() { + if (!this.storable() || this._rescc['no-cache']) { + return 0; + } - case 0: - // pattern *starts* with some non-trivial item. - // going to readdir(cwd), but not include the prefix in matches. - prefix = null - break + // Shared responses with cookies are cacheable according to the RFC, but IMHO it'd be unwise to do so by default + // so this implementation requires explicit opt-in via public header + if ( + this._isShared && + (this._resHeaders['set-cookie'] && + !this._rescc.public && + !this._rescc.immutable) + ) { + return 0; + } - default: - // pattern has some string bits in the front. - // whatever it starts with, whether that's 'absolute' like /foo/bar, - // or 'relative' like '../baz' - prefix = pattern.slice(0, n).join('/') - break - } + if (this._resHeaders.vary === '*') { + return 0; + } - var remain = pattern.slice(n) + if (this._isShared) { + if (this._rescc['proxy-revalidate']) { + return 0; + } + // if a response includes the s-maxage directive, a shared cache recipient MUST ignore the Expires field. + if (this._rescc['s-maxage']) { + return toNumberOrZero(this._rescc['s-maxage']); + } + } - // get the list of entries. - var read - if (prefix === null) - read = '.' - else if (isAbsolute(prefix) || - isAbsolute(pattern.map(function (p) { - return typeof p === 'string' ? p : '[*]' - }).join('/'))) { - if (!prefix || !isAbsolute(prefix)) - prefix = '/' + prefix - read = prefix - } else - read = prefix + // If a response includes a Cache-Control field with the max-age directive, a recipient MUST ignore the Expires field. + if (this._rescc['max-age']) { + return toNumberOrZero(this._rescc['max-age']); + } - var abs = this._makeAbs(read) + const defaultMinTtl = this._rescc.immutable ? this._immutableMinTtl : 0; - //if ignored, skip _processing - if (childrenIgnored(this, read)) - return cb() - - var isGlobStar = remain[0] === minimatch.GLOBSTAR - if (isGlobStar) - this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) - else - this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) -} - -Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { - var self = this - this._readdir(abs, inGlobStar, function (er, entries) { - return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) - }) -} + const serverDate = this.date(); + if (this._resHeaders.expires) { + const expires = Date.parse(this._resHeaders.expires); + // A cache recipient MUST interpret invalid date formats, especially the value "0", as representing a time in the past (i.e., "already expired"). + if (Number.isNaN(expires) || expires < serverDate) { + return 0; + } + return Math.max(defaultMinTtl, (expires - serverDate) / 1000); + } -Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + if (this._resHeaders['last-modified']) { + const lastModified = Date.parse(this._resHeaders['last-modified']); + if (isFinite(lastModified) && serverDate > lastModified) { + return Math.max( + defaultMinTtl, + ((serverDate - lastModified) / 1000) * this._cacheHeuristic + ); + } + } - // if the abs isn't a dir, then nothing can match! - if (!entries) - return cb() + return defaultMinTtl; + } - // It will only match dot entries if it starts with a dot, or if - // dot is set. Stuff like @(.foo|.bar) isn't allowed. - var pn = remain[0] - var negate = !!this.minimatch.negate - var rawGlob = pn._glob - var dotOk = this.dot || rawGlob.charAt(0) === '.' - - var matchedEntries = [] - for (var i = 0; i < entries.length; i++) { - var e = entries[i] - if (e.charAt(0) !== '.' || dotOk) { - var m - if (negate && !prefix) { - m = !e.match(pn) - } else { - m = e.match(pn) - } - if (m) - matchedEntries.push(e) + timeToLive() { + const age = this.maxAge() - this.age(); + const staleIfErrorAge = age + toNumberOrZero(this._rescc['stale-if-error']); + const staleWhileRevalidateAge = age + toNumberOrZero(this._rescc['stale-while-revalidate']); + return Math.max(0, age, staleIfErrorAge, staleWhileRevalidateAge) * 1000; } - } - //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) + stale() { + return this.maxAge() <= this.age(); + } - var len = matchedEntries.length - // If there are no matched entries, then nothing matches. - if (len === 0) - return cb() + _useStaleIfError() { + return this.maxAge() + toNumberOrZero(this._rescc['stale-if-error']) > this.age(); + } - // if this is the last remaining pattern bit, then no need for - // an additional stat *unless* the user has specified mark or - // stat explicitly. We know they exist, since readdir returned - // them. + useStaleWhileRevalidate() { + return this.maxAge() + toNumberOrZero(this._rescc['stale-while-revalidate']) > this.age(); + } - if (remain.length === 1 && !this.mark && !this.stat) { - if (!this.matches[index]) - this.matches[index] = Object.create(null) + static fromObject(obj) { + return new this(undefined, undefined, { _fromObject: obj }); + } - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - if (prefix) { - if (prefix !== '/') - e = prefix + '/' + e - else - e = prefix + e - } + _fromObject(obj) { + if (this._responseTime) throw Error('Reinitialized'); + if (!obj || obj.v !== 1) throw Error('Invalid serialization'); - if (e.charAt(0) === '/' && !this.nomount) { - e = path.join(this.root, e) - } - this._emitMatch(index, e) + this._responseTime = obj.t; + this._isShared = obj.sh; + this._cacheHeuristic = obj.ch; + this._immutableMinTtl = + obj.imm !== undefined ? obj.imm : 24 * 3600 * 1000; + this._status = obj.st; + this._resHeaders = obj.resh; + this._rescc = obj.rescc; + this._method = obj.m; + this._url = obj.u; + this._host = obj.h; + this._noAuthorization = obj.a; + this._reqHeaders = obj.reqh; + this._reqcc = obj.reqcc; } - // This was the last one, and no stats were needed - return cb() - } - // now test all matched entries as stand-ins for that part - // of the pattern. - remain.shift() - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - var newPattern - if (prefix) { - if (prefix !== '/') - e = prefix + '/' + e - else - e = prefix + e + toObject() { + return { + v: 1, + t: this._responseTime, + sh: this._isShared, + ch: this._cacheHeuristic, + imm: this._immutableMinTtl, + st: this._status, + resh: this._resHeaders, + rescc: this._rescc, + m: this._method, + u: this._url, + h: this._host, + a: this._noAuthorization, + reqh: this._reqHeaders, + reqcc: this._reqcc, + }; } - this._process([e].concat(remain), index, inGlobStar, cb) - } - cb() -} -Glob.prototype._emitMatch = function (index, e) { - if (this.aborted) - return + /** + * Headers for sending to the origin server to revalidate stale response. + * Allows server to return 304 to allow reuse of the previous response. + * + * Hop by hop headers are always stripped. + * Revalidation headers may be added or removed, depending on request. + */ + revalidationHeaders(incomingReq) { + this._assertRequestHasHeaders(incomingReq); + const headers = this._copyWithoutHopByHopHeaders(incomingReq.headers); - if (isIgnored(this, e)) - return + // This implementation does not understand range requests + delete headers['if-range']; - if (this.paused) { - this._emitQueue.push([index, e]) - return - } + if (!this._requestMatches(incomingReq, true) || !this.storable()) { + // revalidation allowed via HEAD + // not for the same resource, or wasn't allowed to be cached anyway + delete headers['if-none-match']; + delete headers['if-modified-since']; + return headers; + } - var abs = isAbsolute(e) ? e : this._makeAbs(e) + /* MUST send that entity-tag in any cache validation request (using If-Match or If-None-Match) if an entity-tag has been provided by the origin server. */ + if (this._resHeaders.etag) { + headers['if-none-match'] = headers['if-none-match'] + ? `${headers['if-none-match']}, ${this._resHeaders.etag}` + : this._resHeaders.etag; + } - if (this.mark) - e = this._mark(e) + // Clients MAY issue simple (non-subrange) GET requests with either weak validators or strong validators. Clients MUST NOT use weak validators in other forms of request. + const forbidsWeakValidators = + headers['accept-ranges'] || + headers['if-match'] || + headers['if-unmodified-since'] || + (this._method && this._method != 'GET'); - if (this.absolute) - e = abs + /* SHOULD send the Last-Modified value in non-subrange cache validation requests (using If-Modified-Since) if only a Last-Modified value has been provided by the origin server. + Note: This implementation does not understand partial responses (206) */ + if (forbidsWeakValidators) { + delete headers['if-modified-since']; - if (this.matches[index][e]) - return + if (headers['if-none-match']) { + const etags = headers['if-none-match'] + .split(/,/) + .filter(etag => { + return !/^\s*W\//.test(etag); + }); + if (!etags.length) { + delete headers['if-none-match']; + } else { + headers['if-none-match'] = etags.join(',').trim(); + } + } + } else if ( + this._resHeaders['last-modified'] && + !headers['if-modified-since'] + ) { + headers['if-modified-since'] = this._resHeaders['last-modified']; + } - if (this.nodir) { - var c = this.cache[abs] - if (c === 'DIR' || Array.isArray(c)) - return - } + return headers; + } - this.matches[index][e] = true + /** + * Creates new CachePolicy with information combined from the previews response, + * and the new revalidation response. + * + * Returns {policy, modified} where modified is a boolean indicating + * whether the response body has been modified, and old cached body can't be used. + * + * @return {Object} {policy: CachePolicy, modified: Boolean} + */ + revalidatedPolicy(request, response) { + this._assertRequestHasHeaders(request); + if(this._useStaleIfError() && isErrorResponse(response)) { // I consider the revalidation request unsuccessful + return { + modified: false, + matches: false, + policy: this, + }; + } + if (!response || !response.headers) { + throw Error('Response headers missing'); + } - var st = this.statCache[abs] - if (st) - this.emit('stat', e, st) + // These aren't going to be supported exactly, since one CachePolicy object + // doesn't know about all the other cached objects. + let matches = false; + if (response.status !== undefined && response.status != 304) { + matches = false; + } else if ( + response.headers.etag && + !/^\s*W\//.test(response.headers.etag) + ) { + // "All of the stored responses with the same strong validator are selected. + // If none of the stored responses contain the same strong validator, + // then the cache MUST NOT use the new response to update any stored responses." + matches = + this._resHeaders.etag && + this._resHeaders.etag.replace(/^\s*W\//, '') === + response.headers.etag; + } else if (this._resHeaders.etag && response.headers.etag) { + // "If the new response contains a weak validator and that validator corresponds + // to one of the cache's stored responses, + // then the most recent of those matching stored responses is selected for update." + matches = + this._resHeaders.etag.replace(/^\s*W\//, '') === + response.headers.etag.replace(/^\s*W\//, ''); + } else if (this._resHeaders['last-modified']) { + matches = + this._resHeaders['last-modified'] === + response.headers['last-modified']; + } else { + // If the new response does not include any form of validator (such as in the case where + // a client generates an If-Modified-Since request from a source other than the Last-Modified + // response header field), and there is only one stored response, and that stored response also + // lacks a validator, then that stored response is selected for update. + if ( + !this._resHeaders.etag && + !this._resHeaders['last-modified'] && + !response.headers.etag && + !response.headers['last-modified'] + ) { + matches = true; + } + } - this.emit('match', e) -} + if (!matches) { + return { + policy: new this.constructor(request, response), + // Client receiving 304 without body, even if it's invalid/mismatched has no option + // but to reuse a cached body. We don't have a good way to tell clients to do + // error recovery in such case. + modified: response.status != 304, + matches: false, + }; + } -Glob.prototype._readdirInGlobStar = function (abs, cb) { - if (this.aborted) - return + // use other header fields provided in the 304 (Not Modified) response to replace all instances + // of the corresponding header fields in the stored response. + const headers = {}; + for (const k in this._resHeaders) { + headers[k] = + k in response.headers && !excludedFromRevalidationUpdate[k] + ? response.headers[k] + : this._resHeaders[k]; + } - // follow all symlinked directories forever - // just proceed as if this is a non-globstar situation - if (this.follow) - return this._readdir(abs, false, cb) + const newResponse = Object.assign({}, response, { + status: this._status, + method: this._method, + headers, + }); + return { + policy: new this.constructor(request, newResponse, { + shared: this._isShared, + cacheHeuristic: this._cacheHeuristic, + immutableMinTimeToLive: this._immutableMinTtl, + }), + modified: false, + matches: true, + }; + } +}; - var lstatkey = 'lstat\0' + abs - var self = this - var lstatcb = inflight(lstatkey, lstatcb_) - if (lstatcb) - self.fs.lstat(abs, lstatcb) +/***/ }), - function lstatcb_ (er, lstat) { - if (er && er.code === 'ENOENT') - return cb() +/***/ 685: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var isSym = lstat && lstat.isSymbolicLink() - self.symlinks[abs] = isSym - // If it's not a symlink or a dir, then it's definitely a regular file. - // don't bother doing a readdir in that case. - if (!isSym && lstat && !lstat.isDirectory()) { - self.cache[abs] = 'FILE' - cb() - } else - self._readdir(abs, false, cb) - } -} - -Glob.prototype._readdir = function (abs, inGlobStar, cb) { - if (this.aborted) - return - - cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) - if (!cb) - return - - //console.error('RD %j %j', +inGlobStar, abs) - if (inGlobStar && !ownProp(this.symlinks, abs)) - return this._readdirInGlobStar(abs, cb) +// See https://github.com/facebook/jest/issues/2549 +// eslint-disable-next-line node/prefer-global/url +const {URL} = __nccwpck_require__(7016); +const EventEmitter = __nccwpck_require__(4434); +const tls = __nccwpck_require__(4756); +const http2 = __nccwpck_require__(5675); +const QuickLRU = __nccwpck_require__(5475); +const delayAsyncDestroy = __nccwpck_require__(811); - if (ownProp(this.cache, abs)) { - var c = this.cache[abs] - if (!c || c === 'FILE') - return cb() +const kCurrentStreamCount = Symbol('currentStreamCount'); +const kRequest = Symbol('request'); +const kOriginSet = Symbol('cachedOriginSet'); +const kGracefullyClosing = Symbol('gracefullyClosing'); +const kLength = Symbol('length'); - if (Array.isArray(c)) - return cb(null, c) - } +const nameKeys = [ + // Not an Agent option actually + 'createConnection', - var self = this - self.fs.readdir(abs, readdirCb(this, abs, cb)) -} + // `http2.connect()` options + 'maxDeflateDynamicTableSize', + 'maxSettings', + 'maxSessionMemory', + 'maxHeaderListPairs', + 'maxOutstandingPings', + 'maxReservedRemoteStreams', + 'maxSendHeaderBlockLength', + 'paddingStrategy', + 'peerMaxConcurrentStreams', + 'settings', -function readdirCb (self, abs, cb) { - return function (er, entries) { - if (er) - self._readdirError(abs, er, cb) - else - self._readdirEntries(abs, entries, cb) - } -} + // `tls.connect()` source options + 'family', + 'localAddress', + 'rejectUnauthorized', -Glob.prototype._readdirEntries = function (abs, entries, cb) { - if (this.aborted) - return + // `tls.connect()` secure context options + 'pskCallback', + 'minDHSize', - // if we haven't asked to stat everything, then just - // assume that everything in there exists, so we can avoid - // having to stat it a second time. - if (!this.mark && !this.stat) { - for (var i = 0; i < entries.length; i ++) { - var e = entries[i] - if (abs === '/') - e = abs + e - else - e = abs + '/' + e - this.cache[e] = true - } - } + // `tls.connect()` destination options + // - `servername` is automatically validated, skip it + // - `host` and `port` just describe the destination server, + 'path', + 'socket', - this.cache[abs] = entries - return cb(null, entries) -} + // `tls.createSecureContext()` options + 'ca', + 'cert', + 'sigalgs', + 'ciphers', + 'clientCertEngine', + 'crl', + 'dhparam', + 'ecdhCurve', + 'honorCipherOrder', + 'key', + 'privateKeyEngine', + 'privateKeyIdentifier', + 'maxVersion', + 'minVersion', + 'pfx', + 'secureOptions', + 'secureProtocol', + 'sessionIdContext', + 'ticketKeys' +]; -Glob.prototype._readdirError = function (f, er, cb) { - if (this.aborted) - return +const getSortedIndex = (array, value, compare) => { + let low = 0; + let high = array.length; - // handle errors, and cache the information - switch (er.code) { - case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 - case 'ENOTDIR': // totally normal. means it *does* exist. - var abs = this._makeAbs(f) - this.cache[abs] = 'FILE' - if (abs === this.cwdAbs) { - var error = new Error(er.code + ' invalid cwd ' + this.cwd) - error.path = this.cwd - error.code = er.code - this.emit('error', error) - this.abort() - } - break + while (low < high) { + const mid = (low + high) >>> 1; - case 'ENOENT': // not terribly unusual - case 'ELOOP': - case 'ENAMETOOLONG': - case 'UNKNOWN': - this.cache[this._makeAbs(f)] = false - break + if (compare(array[mid], value)) { + low = mid + 1; + } else { + high = mid; + } + } - default: // some unusual error. Treat as failure. - this.cache[this._makeAbs(f)] = false - if (this.strict) { - this.emit('error', er) - // If the error is handled, then we abort - // if not, we threw out of here - this.abort() - } - if (!this.silent) - console.error('glob error', er) - break - } + return low; +}; - return cb() -} +const compareSessions = (a, b) => a.remoteSettings.maxConcurrentStreams > b.remoteSettings.maxConcurrentStreams; -Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { - var self = this - this._readdir(abs, inGlobStar, function (er, entries) { - self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) - }) -} +// See https://tools.ietf.org/html/rfc8336 +const closeCoveredSessions = (where, session) => { + // Clients SHOULD NOT emit new requests on any connection whose Origin + // Set is a proper subset of another connection's Origin Set, and they + // SHOULD close it once all outstanding requests are satisfied. + for (let index = 0; index < where.length; index++) { + const coveredSession = where[index]; + if ( + // Unfortunately `.every()` returns true for an empty array + coveredSession[kOriginSet].length > 0 -Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { - //console.error('pgs2', prefix, remain[0], entries) + // The set is a proper subset when its length is less than the other set. + && coveredSession[kOriginSet].length < session[kOriginSet].length - // no entries means not a dir, so it can never have matches - // foo.txt/** doesn't match foo.txt - if (!entries) - return cb() + // And the other set includes all elements of the subset. + && coveredSession[kOriginSet].every(origin => session[kOriginSet].includes(origin)) - // test without the globstar, and with every child both below - // and replacing the globstar. - var remainWithoutGlobStar = remain.slice(1) - var gspref = prefix ? [ prefix ] : [] - var noGlobStar = gspref.concat(remainWithoutGlobStar) + // Makes sure that the session can handle all requests from the covered session. + && (coveredSession[kCurrentStreamCount] + session[kCurrentStreamCount]) <= session.remoteSettings.maxConcurrentStreams + ) { + // This allows pending requests to finish and prevents making new requests. + gracefullyClose(coveredSession); + } + } +}; - // the noGlobStar pattern exits the inGlobStar state - this._process(noGlobStar, index, false, cb) +// This is basically inverted `closeCoveredSessions(...)`. +const closeSessionIfCovered = (where, coveredSession) => { + for (let index = 0; index < where.length; index++) { + const session = where[index]; - var isSym = this.symlinks[abs] - var len = entries.length + if ( + coveredSession[kOriginSet].length > 0 + && coveredSession[kOriginSet].length < session[kOriginSet].length + && coveredSession[kOriginSet].every(origin => session[kOriginSet].includes(origin)) + && (coveredSession[kCurrentStreamCount] + session[kCurrentStreamCount]) <= session.remoteSettings.maxConcurrentStreams + ) { + gracefullyClose(coveredSession); - // If it's a symlink, and we're in a globstar, then stop - if (isSym && inGlobStar) - return cb() + return true; + } + } - for (var i = 0; i < len; i++) { - var e = entries[i] - if (e.charAt(0) === '.' && !this.dot) - continue + return false; +}; - // these two cases enter the inGlobStar state - var instead = gspref.concat(entries[i], remainWithoutGlobStar) - this._process(instead, index, true, cb) +const gracefullyClose = session => { + session[kGracefullyClosing] = true; - var below = gspref.concat(entries[i], remain) - this._process(below, index, true, cb) - } + if (session[kCurrentStreamCount] === 0) { + session.close(); + } +}; - cb() -} +class Agent extends EventEmitter { + constructor({timeout = 0, maxSessions = Number.POSITIVE_INFINITY, maxEmptySessions = 10, maxCachedTlsSessions = 100} = {}) { + super(); -Glob.prototype._processSimple = function (prefix, index, cb) { - // XXX review this. Shouldn't it be doing the mounting etc - // before doing stat? kinda weird? - var self = this - this._stat(prefix, function (er, exists) { - self._processSimple2(prefix, index, er, exists, cb) - }) -} -Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { + // SESSIONS[NORMALIZED_OPTIONS] = []; + this.sessions = {}; - //console.error('ps2', prefix, exists) + // The queue for creating new sessions. It looks like this: + // QUEUE[NORMALIZED_OPTIONS][NORMALIZED_ORIGIN] = ENTRY_FUNCTION + // + // It's faster when there are many origins. If there's only one, then QUEUE[`${options}:${origin}`] is faster. + // I guess object creation / deletion is causing the slowdown. + // + // The entry function has `listeners`, `completed` and `destroyed` properties. + // `listeners` is an array of objects containing `resolve` and `reject` functions. + // `completed` is a boolean. It's set to true after ENTRY_FUNCTION is executed. + // `destroyed` is a boolean. If it's set to true, the session will be destroyed if hasn't connected yet. + this.queue = {}; - if (!this.matches[index]) - this.matches[index] = Object.create(null) + // Each session will use this timeout value. + this.timeout = timeout; - // If it doesn't exist, then just mark the lack of results - if (!exists) - return cb() + // Max sessions in total + this.maxSessions = maxSessions; - if (prefix && isAbsolute(prefix) && !this.nomount) { - var trail = /[\/\\]$/.test(prefix) - if (prefix.charAt(0) === '/') { - prefix = path.join(this.root, prefix) - } else { - prefix = path.resolve(this.root, prefix) - if (trail) - prefix += '/' - } - } + // Max empty sessions in total + this.maxEmptySessions = maxEmptySessions; - if (process.platform === 'win32') - prefix = prefix.replace(/\\/g, '/') + this._emptySessionCount = 0; + this._sessionCount = 0; - // Mark this as a match - this._emitMatch(index, prefix) - cb() -} + // We don't support push streams by default. + this.settings = { + enablePush: false, + initialWindowSize: 1024 * 1024 * 32 // 32MB, see https://github.com/nodejs/node/issues/38426 + }; -// Returns either 'DIR', 'FILE', or false -Glob.prototype._stat = function (f, cb) { - var abs = this._makeAbs(f) - var needDir = f.slice(-1) === '/' + // Reusing TLS sessions increases performance. + this.tlsSessionCache = new QuickLRU({maxSize: maxCachedTlsSessions}); + } - if (f.length > this.maxLength) - return cb() + get protocol() { + return 'https:'; + } - if (!this.stat && ownProp(this.cache, abs)) { - var c = this.cache[abs] + normalizeOptions(options) { + let normalized = ''; - if (Array.isArray(c)) - c = 'DIR' + for (let index = 0; index < nameKeys.length; index++) { + const key = nameKeys[index]; - // It exists, but maybe not how we need it - if (!needDir || c === 'DIR') - return cb(null, c) + normalized += ':'; - if (needDir && c === 'FILE') - return cb() + if (options && options[key] !== undefined) { + normalized += options[key]; + } + } - // otherwise we have to stat, because maybe c=true - // if we know it exists, but not what it is. - } + return normalized; + } - var exists - var stat = this.statCache[abs] - if (stat !== undefined) { - if (stat === false) - return cb(null, stat) - else { - var type = stat.isDirectory() ? 'DIR' : 'FILE' - if (needDir && type === 'FILE') - return cb() - else - return cb(null, type, stat) - } - } + _processQueue() { + if (this._sessionCount >= this.maxSessions) { + this.closeEmptySessions(this.maxSessions - this._sessionCount + 1); + return; + } - var self = this - var statcb = inflight('stat\0' + abs, lstatcb_) - if (statcb) - self.fs.lstat(abs, statcb) + // eslint-disable-next-line guard-for-in + for (const normalizedOptions in this.queue) { + // eslint-disable-next-line guard-for-in + for (const normalizedOrigin in this.queue[normalizedOptions]) { + const item = this.queue[normalizedOptions][normalizedOrigin]; - function lstatcb_ (er, lstat) { - if (lstat && lstat.isSymbolicLink()) { - // If it's a symlink, then treat it as the target, unless - // the target does not exist, then treat it as a file. - return self.fs.stat(abs, function (er, stat) { - if (er) - self._stat2(f, abs, null, lstat, cb) - else - self._stat2(f, abs, er, stat, cb) - }) - } else { - self._stat2(f, abs, er, lstat, cb) - } - } -} + // The entry function can be run only once. + if (!item.completed) { + item.completed = true; -Glob.prototype._stat2 = function (f, abs, er, stat, cb) { - if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { - this.statCache[abs] = false - return cb() - } + item(); + } + } + } + } - var needDir = f.slice(-1) === '/' - this.statCache[abs] = stat + _isBetterSession(thisStreamCount, thatStreamCount) { + return thisStreamCount > thatStreamCount; + } - if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) - return cb(null, false, stat) + _accept(session, listeners, normalizedOrigin, options) { + let index = 0; - var c = true - if (stat) - c = stat.isDirectory() ? 'DIR' : 'FILE' - this.cache[abs] = this.cache[abs] || c + while (index < listeners.length && session[kCurrentStreamCount] < session.remoteSettings.maxConcurrentStreams) { + // We assume `resolve(...)` calls `request(...)` *directly*, + // otherwise the session will get overloaded. + listeners[index].resolve(session); - if (needDir && c === 'FILE') - return cb() + index++; + } - return cb(null, c, stat) -} + listeners.splice(0, index); + if (listeners.length > 0) { + this.getSession(normalizedOrigin, options, listeners); + listeners.length = 0; + } + } -/***/ }), + getSession(origin, options, listeners) { + return new Promise((resolve, reject) => { + if (Array.isArray(listeners) && listeners.length > 0) { + listeners = [...listeners]; -/***/ 9010: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Resolve the current promise ASAP, we're just moving the listeners. + // They will be executed at a different time. + resolve(); + } else { + listeners = [{resolve, reject}]; + } -module.exports = globSync -globSync.GlobSync = GlobSync + try { + // Parse origin + if (typeof origin === 'string') { + origin = new URL(origin); + } else if (!(origin instanceof URL)) { + throw new TypeError('The `origin` argument needs to be a string or an URL object'); + } -var rp = __nccwpck_require__(6863) -var minimatch = __nccwpck_require__(3973) -var Minimatch = minimatch.Minimatch -var Glob = (__nccwpck_require__(1957).Glob) -var util = __nccwpck_require__(3837) -var path = __nccwpck_require__(1017) -var assert = __nccwpck_require__(9491) -var isAbsolute = __nccwpck_require__(8714) -var common = __nccwpck_require__(7625) -var setopts = common.setopts -var ownProp = common.ownProp -var childrenIgnored = common.childrenIgnored -var isIgnored = common.isIgnored + if (options) { + // Validate servername + const {servername} = options; + const {hostname} = origin; + if (servername && hostname !== servername) { + throw new Error(`Origin ${hostname} differs from servername ${servername}`); + } + } + } catch (error) { + for (let index = 0; index < listeners.length; index++) { + listeners[index].reject(error); + } -function globSync (pattern, options) { - if (typeof options === 'function' || arguments.length === 3) - throw new TypeError('callback provided to sync glob\n'+ - 'See: https://github.com/isaacs/node-glob/issues/167') + return; + } - return new GlobSync(pattern, options).found -} + const normalizedOptions = this.normalizeOptions(options); + const normalizedOrigin = origin.origin; -function GlobSync (pattern, options) { - if (!pattern) - throw new Error('must provide pattern') + if (normalizedOptions in this.sessions) { + const sessions = this.sessions[normalizedOptions]; - if (typeof options === 'function' || arguments.length === 3) - throw new TypeError('callback provided to sync glob\n'+ - 'See: https://github.com/isaacs/node-glob/issues/167') + let maxConcurrentStreams = -1; + let currentStreamsCount = -1; + let optimalSession; - if (!(this instanceof GlobSync)) - return new GlobSync(pattern, options) + // We could just do this.sessions[normalizedOptions].find(...) but that isn't optimal. + // Additionally, we are looking for session which has biggest current pending streams count. + // + // |------------| |------------| |------------| |------------| + // | Session: A | | Session: B | | Session: C | | Session: D | + // | Pending: 5 |-| Pending: 8 |-| Pending: 9 |-| Pending: 4 | + // | Max: 10 | | Max: 10 | | Max: 9 | | Max: 5 | + // |------------| |------------| |------------| |------------| + // ^ + // | + // pick this one -- + // + for (let index = 0; index < sessions.length; index++) { + const session = sessions[index]; - setopts(this, pattern, options) + const sessionMaxConcurrentStreams = session.remoteSettings.maxConcurrentStreams; - if (this.noprocess) - return this + if (sessionMaxConcurrentStreams < maxConcurrentStreams) { + break; + } - var n = this.minimatch.set.length - this.matches = new Array(n) - for (var i = 0; i < n; i ++) { - this._process(this.minimatch.set[i], i, false) - } - this._finish() -} + if (!session[kOriginSet].includes(normalizedOrigin)) { + continue; + } -GlobSync.prototype._finish = function () { - assert.ok(this instanceof GlobSync) - if (this.realpath) { - var self = this - this.matches.forEach(function (matchset, index) { - var set = self.matches[index] = Object.create(null) - for (var p in matchset) { - try { - p = self._makeAbs(p) - var real = rp.realpathSync(p, self.realpathCache) - set[real] = true - } catch (er) { - if (er.syscall === 'stat') - set[self._makeAbs(p)] = true - else - throw er - } - } - }) - } - common.finish(this) -} + const sessionCurrentStreamsCount = session[kCurrentStreamCount]; + if ( + sessionCurrentStreamsCount >= sessionMaxConcurrentStreams + || session[kGracefullyClosing] + // Unfortunately the `close` event isn't called immediately, + // so `session.destroyed` is `true`, but `session.closed` is `false`. + || session.destroyed + ) { + continue; + } -GlobSync.prototype._process = function (pattern, index, inGlobStar) { - assert.ok(this instanceof GlobSync) + // We only need set this once. + if (!optimalSession) { + maxConcurrentStreams = sessionMaxConcurrentStreams; + } - // Get the first [n] parts of pattern that are all strings. - var n = 0 - while (typeof pattern[n] === 'string') { - n ++ - } - // now n is the index of the first one that is *not* a string. + // Either get the session which has biggest current stream count or the lowest. + if (this._isBetterSession(sessionCurrentStreamsCount, currentStreamsCount)) { + optimalSession = session; + currentStreamsCount = sessionCurrentStreamsCount; + } + } - // See if there's anything else - var prefix - switch (n) { - // if not, then this is rather simple - case pattern.length: - this._processSimple(pattern.join('/'), index) - return + if (optimalSession) { + this._accept(optimalSession, listeners, normalizedOrigin, options); + return; + } + } - case 0: - // pattern *starts* with some non-trivial item. - // going to readdir(cwd), but not include the prefix in matches. - prefix = null - break + if (normalizedOptions in this.queue) { + if (normalizedOrigin in this.queue[normalizedOptions]) { + // There's already an item in the queue, just attach ourselves to it. + this.queue[normalizedOptions][normalizedOrigin].listeners.push(...listeners); + return; + } + } else { + this.queue[normalizedOptions] = { + [kLength]: 0 + }; + } - default: - // pattern has some string bits in the front. - // whatever it starts with, whether that's 'absolute' like /foo/bar, - // or 'relative' like '../baz' - prefix = pattern.slice(0, n).join('/') - break - } + // The entry must be removed from the queue IMMEDIATELY when: + // 1. the session connects successfully, + // 2. an error occurs. + const removeFromQueue = () => { + // Our entry can be replaced. We cannot remove the new one. + if (normalizedOptions in this.queue && this.queue[normalizedOptions][normalizedOrigin] === entry) { + delete this.queue[normalizedOptions][normalizedOrigin]; - var remain = pattern.slice(n) + if (--this.queue[normalizedOptions][kLength] === 0) { + delete this.queue[normalizedOptions]; + } + } + }; - // get the list of entries. - var read - if (prefix === null) - read = '.' - else if (isAbsolute(prefix) || - isAbsolute(pattern.map(function (p) { - return typeof p === 'string' ? p : '[*]' - }).join('/'))) { - if (!prefix || !isAbsolute(prefix)) - prefix = '/' + prefix - read = prefix - } else - read = prefix + // The main logic is here + const entry = async () => { + this._sessionCount++; - var abs = this._makeAbs(read) + const name = `${normalizedOrigin}:${normalizedOptions}`; + let receivedSettings = false; + let socket; - //if ignored, skip processing - if (childrenIgnored(this, read)) - return + try { + const computedOptions = {...options}; - var isGlobStar = remain[0] === minimatch.GLOBSTAR - if (isGlobStar) - this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) - else - this._processReaddir(prefix, read, abs, remain, index, inGlobStar) -} + if (computedOptions.settings === undefined) { + computedOptions.settings = this.settings; + } + if (computedOptions.session === undefined) { + computedOptions.session = this.tlsSessionCache.get(name); + } -GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { - var entries = this._readdir(abs, inGlobStar) + const createConnection = computedOptions.createConnection || this.createConnection; - // if the abs isn't a dir, then nothing can match! - if (!entries) - return + // A hacky workaround to enable async `createConnection` + socket = await createConnection.call(this, origin, computedOptions); + computedOptions.createConnection = () => socket; - // It will only match dot entries if it starts with a dot, or if - // dot is set. Stuff like @(.foo|.bar) isn't allowed. - var pn = remain[0] - var negate = !!this.minimatch.negate - var rawGlob = pn._glob - var dotOk = this.dot || rawGlob.charAt(0) === '.' - - var matchedEntries = [] - for (var i = 0; i < entries.length; i++) { - var e = entries[i] - if (e.charAt(0) !== '.' || dotOk) { - var m - if (negate && !prefix) { - m = !e.match(pn) - } else { - m = e.match(pn) - } - if (m) - matchedEntries.push(e) - } - } + const session = http2.connect(origin, computedOptions); + session[kCurrentStreamCount] = 0; + session[kGracefullyClosing] = false; - var len = matchedEntries.length - // If there are no matched entries, then nothing matches. - if (len === 0) - return + // Node.js return https://false:443 instead of https://1.1.1.1:443 + const getOriginSet = () => { + const {socket} = session; - // if this is the last remaining pattern bit, then no need for - // an additional stat *unless* the user has specified mark or - // stat explicitly. We know they exist, since readdir returned - // them. + let originSet; + if (socket.servername === false) { + socket.servername = socket.remoteAddress; + originSet = session.originSet; + socket.servername = false; + } else { + originSet = session.originSet; + } - if (remain.length === 1 && !this.mark && !this.stat) { - if (!this.matches[index]) - this.matches[index] = Object.create(null) + return originSet; + }; - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - if (prefix) { - if (prefix.slice(-1) !== '/') - e = prefix + '/' + e - else - e = prefix + e - } + const isFree = () => session[kCurrentStreamCount] < session.remoteSettings.maxConcurrentStreams; - if (e.charAt(0) === '/' && !this.nomount) { - e = path.join(this.root, e) - } - this._emitMatch(index, e) - } - // This was the last one, and no stats were needed - return - } + session.socket.once('session', tlsSession => { + this.tlsSessionCache.set(name, tlsSession); + }); - // now test all matched entries as stand-ins for that part - // of the pattern. - remain.shift() - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - var newPattern - if (prefix) - newPattern = [prefix, e] - else - newPattern = [e] - this._process(newPattern.concat(remain), index, inGlobStar) - } -} + session.once('error', error => { + // Listeners are empty when the session successfully connected. + for (let index = 0; index < listeners.length; index++) { + listeners[index].reject(error); + } + // The connection got broken, purge the cache. + this.tlsSessionCache.delete(name); + }); -GlobSync.prototype._emitMatch = function (index, e) { - if (isIgnored(this, e)) - return + session.setTimeout(this.timeout, () => { + // Terminates all streams owned by this session. + session.destroy(); + }); - var abs = this._makeAbs(e) + session.once('close', () => { + this._sessionCount--; - if (this.mark) - e = this._mark(e) + if (receivedSettings) { + // Assumes session `close` is emitted after request `close` + this._emptySessionCount--; - if (this.absolute) { - e = abs - } + // This cannot be moved to the stream logic, + // because there may be a session that hadn't made a single request. + const where = this.sessions[normalizedOptions]; - if (this.matches[index][e]) - return + if (where.length === 1) { + delete this.sessions[normalizedOptions]; + } else { + where.splice(where.indexOf(session), 1); + } + } else { + // Broken connection + removeFromQueue(); - if (this.nodir) { - var c = this.cache[abs] - if (c === 'DIR' || Array.isArray(c)) - return - } + const error = new Error('Session closed without receiving a SETTINGS frame'); + error.code = 'HTTP2WRAPPER_NOSETTINGS'; - this.matches[index][e] = true + for (let index = 0; index < listeners.length; index++) { + listeners[index].reject(error); + } + } - if (this.stat) - this._stat(e) -} + // There may be another session awaiting. + this._processQueue(); + }); + // Iterates over the queue and processes listeners. + const processListeners = () => { + const queue = this.queue[normalizedOptions]; + if (!queue) { + return; + } -GlobSync.prototype._readdirInGlobStar = function (abs) { - // follow all symlinked directories forever - // just proceed as if this is a non-globstar situation - if (this.follow) - return this._readdir(abs, false) + const originSet = session[kOriginSet]; - var entries - var lstat - var stat - try { - lstat = this.fs.lstatSync(abs) - } catch (er) { - if (er.code === 'ENOENT') { - // lstat failed, doesn't exist - return null - } - } + for (let index = 0; index < originSet.length; index++) { + const origin = originSet[index]; - var isSym = lstat && lstat.isSymbolicLink() - this.symlinks[abs] = isSym + if (origin in queue) { + const {listeners, completed} = queue[origin]; - // If it's not a symlink or a dir, then it's definitely a regular file. - // don't bother doing a readdir in that case. - if (!isSym && lstat && !lstat.isDirectory()) - this.cache[abs] = 'FILE' - else - entries = this._readdir(abs, false) + let index = 0; - return entries -} + // Prevents session overloading. + while (index < listeners.length && isFree()) { + // We assume `resolve(...)` calls `request(...)` *directly*, + // otherwise the session will get overloaded. + listeners[index].resolve(session); -GlobSync.prototype._readdir = function (abs, inGlobStar) { - var entries + index++; + } - if (inGlobStar && !ownProp(this.symlinks, abs)) - return this._readdirInGlobStar(abs) + queue[origin].listeners.splice(0, index); - if (ownProp(this.cache, abs)) { - var c = this.cache[abs] - if (!c || c === 'FILE') - return null + if (queue[origin].listeners.length === 0 && !completed) { + delete queue[origin]; - if (Array.isArray(c)) - return c - } + if (--queue[kLength] === 0) { + delete this.queue[normalizedOptions]; + break; + } + } - try { - return this._readdirEntries(abs, this.fs.readdirSync(abs)) - } catch (er) { - this._readdirError(abs, er) - return null - } -} + // We're no longer free, no point in continuing. + if (!isFree()) { + break; + } + } + } + }; -GlobSync.prototype._readdirEntries = function (abs, entries) { - // if we haven't asked to stat everything, then just - // assume that everything in there exists, so we can avoid - // having to stat it a second time. - if (!this.mark && !this.stat) { - for (var i = 0; i < entries.length; i ++) { - var e = entries[i] - if (abs === '/') - e = abs + e - else - e = abs + '/' + e - this.cache[e] = true - } - } + // The Origin Set cannot shrink. No need to check if it suddenly became covered by another one. + session.on('origin', () => { + session[kOriginSet] = getOriginSet() || []; + session[kGracefullyClosing] = false; + closeSessionIfCovered(this.sessions[normalizedOptions], session); - this.cache[abs] = entries + if (session[kGracefullyClosing] || !isFree()) { + return; + } - // mark and cache dir-ness - return entries -} + processListeners(); -GlobSync.prototype._readdirError = function (f, er) { - // handle errors, and cache the information - switch (er.code) { - case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 - case 'ENOTDIR': // totally normal. means it *does* exist. - var abs = this._makeAbs(f) - this.cache[abs] = 'FILE' - if (abs === this.cwdAbs) { - var error = new Error(er.code + ' invalid cwd ' + this.cwd) - error.path = this.cwd - error.code = er.code - throw error - } - break + if (!isFree()) { + return; + } - case 'ENOENT': // not terribly unusual - case 'ELOOP': - case 'ENAMETOOLONG': - case 'UNKNOWN': - this.cache[this._makeAbs(f)] = false - break + // Close covered sessions (if possible). + closeCoveredSessions(this.sessions[normalizedOptions], session); + }); - default: // some unusual error. Treat as failure. - this.cache[this._makeAbs(f)] = false - if (this.strict) - throw er - if (!this.silent) - console.error('glob error', er) - break - } -} + session.once('remoteSettings', () => { + // The Agent could have been destroyed already. + if (entry.destroyed) { + const error = new Error('Agent has been destroyed'); -GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { + for (let index = 0; index < listeners.length; index++) { + listeners[index].reject(error); + } - var entries = this._readdir(abs, inGlobStar) + session.destroy(); + return; + } - // no entries means not a dir, so it can never have matches - // foo.txt/** doesn't match foo.txt - if (!entries) - return + // See https://github.com/nodejs/node/issues/38426 + if (session.setLocalWindowSize) { + session.setLocalWindowSize(1024 * 1024 * 4); // 4 MB + } - // test without the globstar, and with every child both below - // and replacing the globstar. - var remainWithoutGlobStar = remain.slice(1) - var gspref = prefix ? [ prefix ] : [] - var noGlobStar = gspref.concat(remainWithoutGlobStar) + session[kOriginSet] = getOriginSet() || []; - // the noGlobStar pattern exits the inGlobStar state - this._process(noGlobStar, index, false) + if (session.socket.encrypted) { + const mainOrigin = session[kOriginSet][0]; + if (mainOrigin !== normalizedOrigin) { + const error = new Error(`Requested origin ${normalizedOrigin} does not match server ${mainOrigin}`); - var len = entries.length - var isSym = this.symlinks[abs] + for (let index = 0; index < listeners.length; index++) { + listeners[index].reject(error); + } - // If it's a symlink, and we're in a globstar, then stop - if (isSym && inGlobStar) - return + session.destroy(); + return; + } + } - for (var i = 0; i < len; i++) { - var e = entries[i] - if (e.charAt(0) === '.' && !this.dot) - continue + removeFromQueue(); - // these two cases enter the inGlobStar state - var instead = gspref.concat(entries[i], remainWithoutGlobStar) - this._process(instead, index, true) + { + const where = this.sessions; - var below = gspref.concat(entries[i], remain) - this._process(below, index, true) - } -} + if (normalizedOptions in where) { + const sessions = where[normalizedOptions]; + sessions.splice(getSortedIndex(sessions, session, compareSessions), 0, session); + } else { + where[normalizedOptions] = [session]; + } + } -GlobSync.prototype._processSimple = function (prefix, index) { - // XXX review this. Shouldn't it be doing the mounting etc - // before doing stat? kinda weird? - var exists = this._stat(prefix) + receivedSettings = true; + this._emptySessionCount++; - if (!this.matches[index]) - this.matches[index] = Object.create(null) + this.emit('session', session); + this._accept(session, listeners, normalizedOrigin, options); - // If it doesn't exist, then just mark the lack of results - if (!exists) - return + if (session[kCurrentStreamCount] === 0 && this._emptySessionCount > this.maxEmptySessions) { + this.closeEmptySessions(this._emptySessionCount - this.maxEmptySessions); + } - if (prefix && isAbsolute(prefix) && !this.nomount) { - var trail = /[\/\\]$/.test(prefix) - if (prefix.charAt(0) === '/') { - prefix = path.join(this.root, prefix) - } else { - prefix = path.resolve(this.root, prefix) - if (trail) - prefix += '/' - } - } + // `session.remoteSettings.maxConcurrentStreams` might get increased + session.on('remoteSettings', () => { + if (!isFree()) { + return; + } - if (process.platform === 'win32') - prefix = prefix.replace(/\\/g, '/') + processListeners(); - // Mark this as a match - this._emitMatch(index, prefix) -} + if (!isFree()) { + return; + } -// Returns either 'DIR', 'FILE', or false -GlobSync.prototype._stat = function (f) { - var abs = this._makeAbs(f) - var needDir = f.slice(-1) === '/' + // In case the Origin Set changes + closeCoveredSessions(this.sessions[normalizedOptions], session); + }); + }); - if (f.length > this.maxLength) - return false + // Shim `session.request()` in order to catch all streams + session[kRequest] = session.request; + session.request = (headers, streamOptions) => { + if (session[kGracefullyClosing]) { + throw new Error('The session is gracefully closing. No new streams are allowed.'); + } - if (!this.stat && ownProp(this.cache, abs)) { - var c = this.cache[abs] + const stream = session[kRequest](headers, streamOptions); - if (Array.isArray(c)) - c = 'DIR' + // The process won't exit until the session is closed or all requests are gone. + session.ref(); - // It exists, but maybe not how we need it - if (!needDir || c === 'DIR') - return c + if (session[kCurrentStreamCount]++ === 0) { + this._emptySessionCount--; + } - if (needDir && c === 'FILE') - return false + stream.once('close', () => { + if (--session[kCurrentStreamCount] === 0) { + this._emptySessionCount++; + session.unref(); - // otherwise we have to stat, because maybe c=true - // if we know it exists, but not what it is. - } + if (this._emptySessionCount > this.maxEmptySessions || session[kGracefullyClosing]) { + session.close(); + return; + } + } - var exists - var stat = this.statCache[abs] - if (!stat) { - var lstat - try { - lstat = this.fs.lstatSync(abs) - } catch (er) { - if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { - this.statCache[abs] = false - return false - } - } + if (session.destroyed || session.closed) { + return; + } - if (lstat && lstat.isSymbolicLink()) { - try { - stat = this.fs.statSync(abs) - } catch (er) { - stat = lstat - } - } else { - stat = lstat - } - } + if (isFree() && !closeSessionIfCovered(this.sessions[normalizedOptions], session)) { + closeCoveredSessions(this.sessions[normalizedOptions], session); + processListeners(); - this.statCache[abs] = stat + if (session[kCurrentStreamCount] === 0) { + this._processQueue(); + } + } + }); - var c = true - if (stat) - c = stat.isDirectory() ? 'DIR' : 'FILE' + return stream; + }; + } catch (error) { + removeFromQueue(); + this._sessionCount--; - this.cache[abs] = this.cache[abs] || c + for (let index = 0; index < listeners.length; index++) { + listeners[index].reject(error); + } + } + }; - if (needDir && c === 'FILE') - return false + entry.listeners = listeners; + entry.completed = false; + entry.destroyed = false; - return c -} + this.queue[normalizedOptions][normalizedOrigin] = entry; + this.queue[normalizedOptions][kLength]++; + this._processQueue(); + }); + } -GlobSync.prototype._mark = function (p) { - return common.mark(this, p) -} + request(origin, options, headers, streamOptions) { + return new Promise((resolve, reject) => { + this.getSession(origin, options, [{ + reject, + resolve: session => { + try { + const stream = session.request(headers, streamOptions); -GlobSync.prototype._makeAbs = function (f) { - return common.makeAbs(this, f) -} + // Do not throw before `request(...)` has been awaited + delayAsyncDestroy(stream); + resolve(stream); + } catch (error) { + reject(error); + } + } + }]); + }); + } -/***/ }), + async createConnection(origin, options) { + return Agent.connect(origin, options); + } -/***/ 7356: -/***/ ((module) => { + static connect(origin, options) { + options.ALPNProtocols = ['h2']; + const port = origin.port || 443; + const host = origin.hostname; + if (typeof options.servername === 'undefined') { + options.servername = host; + } -module.exports = clone + const socket = tls.connect(port, host, options); -var getPrototypeOf = Object.getPrototypeOf || function (obj) { - return obj.__proto__ -} + if (options.socket) { + socket._peername = { + family: undefined, + address: undefined, + port + }; + } -function clone (obj) { - if (obj === null || typeof obj !== 'object') - return obj + return socket; + } - if (obj instanceof Object) - var copy = { __proto__: getPrototypeOf(obj) } - else - var copy = Object.create(null) + closeEmptySessions(maxCount = Number.POSITIVE_INFINITY) { + let closedCount = 0; - Object.getOwnPropertyNames(obj).forEach(function (key) { - Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) - }) + const {sessions} = this; - return copy -} + // eslint-disable-next-line guard-for-in + for (const key in sessions) { + const thisSessions = sessions[key]; + for (let index = 0; index < thisSessions.length; index++) { + const session = thisSessions[index]; -/***/ }), + if (session[kCurrentStreamCount] === 0) { + closedCount++; + session.close(); -/***/ 7758: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (closedCount >= maxCount) { + return closedCount; + } + } + } + } -var fs = __nccwpck_require__(7147) -var polyfills = __nccwpck_require__(263) -var legacy = __nccwpck_require__(3086) -var clone = __nccwpck_require__(7356) + return closedCount; + } -var util = __nccwpck_require__(3837) + destroy(reason) { + const {sessions, queue} = this; -/* istanbul ignore next - node 0.x polyfill */ -var gracefulQueue -var previousSymbol + // eslint-disable-next-line guard-for-in + for (const key in sessions) { + const thisSessions = sessions[key]; -/* istanbul ignore else - node 0.x polyfill */ -if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { - gracefulQueue = Symbol.for('graceful-fs.queue') - // This is used in testing by future versions - previousSymbol = Symbol.for('graceful-fs.previous') -} else { - gracefulQueue = '___graceful-fs.queue' - previousSymbol = '___graceful-fs.previous' -} + for (let index = 0; index < thisSessions.length; index++) { + thisSessions[index].destroy(reason); + } + } -function noop () {} + // eslint-disable-next-line guard-for-in + for (const normalizedOptions in queue) { + const entries = queue[normalizedOptions]; -function publishQueue(context, queue) { - Object.defineProperty(context, gracefulQueue, { - get: function() { - return queue - } - }) + // eslint-disable-next-line guard-for-in + for (const normalizedOrigin in entries) { + entries[normalizedOrigin].destroyed = true; + } + } + + // New requests should NOT attach to destroyed sessions + this.queue = {}; + this.tlsSessionCache.clear(); + } + + get emptySessionCount() { + return this._emptySessionCount; + } + + get pendingSessionCount() { + return this._sessionCount - this._emptySessionCount; + } + + get sessionCount() { + return this._sessionCount; + } } -var debug = noop -if (util.debuglog) - debug = util.debuglog('gfs4') -else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) - debug = function() { - var m = util.format.apply(util, arguments) - m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') - console.error(m) - } +Agent.kCurrentStreamCount = kCurrentStreamCount; +Agent.kGracefullyClosing = kGracefullyClosing; -// Once time initialization -if (!fs[gracefulQueue]) { - // This queue can be shared by multiple loaded instances - var queue = global[gracefulQueue] || [] - publishQueue(fs, queue) +module.exports = { + Agent, + globalAgent: new Agent() +}; - // Patch fs.close/closeSync to shared queue version, because we need - // to retry() whenever a close happens *anywhere* in the program. - // This is essential when multiple graceful-fs instances are - // in play at the same time. - fs.close = (function (fs$close) { - function close (fd, cb) { - return fs$close.call(fs, fd, function (err) { - // This function uses the graceful-fs shared queue - if (!err) { - resetQueue() - } - if (typeof cb === 'function') - cb.apply(this, arguments) - }) - } +/***/ }), - Object.defineProperty(close, previousSymbol, { - value: fs$close - }) - return close - })(fs.close) +/***/ 9213: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - fs.closeSync = (function (fs$closeSync) { - function closeSync (fd) { - // This function uses the graceful-fs shared queue - fs$closeSync.apply(fs, arguments) - resetQueue() - } - Object.defineProperty(closeSync, previousSymbol, { - value: fs$closeSync - }) - return closeSync - })(fs.closeSync) +// See https://github.com/facebook/jest/issues/2549 +// eslint-disable-next-line node/prefer-global/url +const {URL, urlToHttpOptions} = __nccwpck_require__(7016); +const http = __nccwpck_require__(8611); +const https = __nccwpck_require__(5692); +const resolveALPN = __nccwpck_require__(8824); +const QuickLRU = __nccwpck_require__(5475); +const {Agent, globalAgent} = __nccwpck_require__(685); +const Http2ClientRequest = __nccwpck_require__(7605); +const calculateServerName = __nccwpck_require__(2850); +const delayAsyncDestroy = __nccwpck_require__(811); - if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { - process.on('exit', function() { - debug(fs[gracefulQueue]) - __nccwpck_require__(9491).equal(fs[gracefulQueue].length, 0) - }) - } -} +const cache = new QuickLRU({maxSize: 100}); +const queue = new Map(); -if (!global[gracefulQueue]) { - publishQueue(global, fs[gracefulQueue]); -} +const installSocket = (agent, socket, options) => { + socket._httpMessage = {shouldKeepAlive: true}; -module.exports = patch(clone(fs)) -if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { - module.exports = patch(fs) - fs.__patched = true; -} + const onFree = () => { + agent.emit('free', socket, options); + }; -function patch (fs) { - // Everything that references the open() function needs to be in here - polyfills(fs) - fs.gracefulify = patch + socket.on('free', onFree); - fs.createReadStream = createReadStream - fs.createWriteStream = createWriteStream - var fs$readFile = fs.readFile - fs.readFile = readFile - function readFile (path, options, cb) { - if (typeof options === 'function') - cb = options, options = null + const onClose = () => { + agent.removeSocket(socket, options); + }; - return go$readFile(path, options, cb) + socket.on('close', onClose); - function go$readFile (path, options, cb, startTime) { - return fs$readFile(path, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } + const onTimeout = () => { + const {freeSockets} = agent; - var fs$writeFile = fs.writeFile - fs.writeFile = writeFile - function writeFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null + for (const sockets of Object.values(freeSockets)) { + if (sockets.includes(socket)) { + socket.destroy(); + return; + } + } + }; - return go$writeFile(path, data, options, cb) + socket.on('timeout', onTimeout); - function go$writeFile (path, data, options, cb, startTime) { - return fs$writeFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } + const onRemove = () => { + agent.removeSocket(socket, options); + socket.off('close', onClose); + socket.off('free', onFree); + socket.off('timeout', onTimeout); + socket.off('agentRemove', onRemove); + }; - var fs$appendFile = fs.appendFile - if (fs$appendFile) - fs.appendFile = appendFile - function appendFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null + socket.on('agentRemove', onRemove); - return go$appendFile(path, data, options, cb) + agent.emit('free', socket, options); +}; - function go$appendFile (path, data, options, cb, startTime) { - return fs$appendFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } +const createResolveProtocol = (cache, queue = new Map(), connect = undefined) => { + return async options => { + const name = `${options.host}:${options.port}:${options.ALPNProtocols.sort()}`; - var fs$copyFile = fs.copyFile - if (fs$copyFile) - fs.copyFile = copyFile - function copyFile (src, dest, flags, cb) { - if (typeof flags === 'function') { - cb = flags - flags = 0 - } - return go$copyFile(src, dest, flags, cb) + if (!cache.has(name)) { + if (queue.has(name)) { + const result = await queue.get(name); + return {alpnProtocol: result.alpnProtocol}; + } - function go$copyFile (src, dest, flags, cb, startTime) { - return fs$copyFile(src, dest, flags, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } + const {path} = options; + options.path = options.socketPath; - var fs$readdir = fs.readdir - fs.readdir = readdir - var noReaddirOptionVersions = /^v[0-5]\./ - function readdir (path, options, cb) { - if (typeof options === 'function') - cb = options, options = null + const resultPromise = resolveALPN(options, connect); + queue.set(name, resultPromise); - var go$readdir = noReaddirOptionVersions.test(process.version) - ? function go$readdir (path, options, cb, startTime) { - return fs$readdir(path, fs$readdirCallback( - path, options, cb, startTime - )) - } - : function go$readdir (path, options, cb, startTime) { - return fs$readdir(path, options, fs$readdirCallback( - path, options, cb, startTime - )) - } + try { + const result = await resultPromise; - return go$readdir(path, options, cb) + cache.set(name, result.alpnProtocol); + queue.delete(name); - function fs$readdirCallback (path, options, cb, startTime) { - return function (err, files) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([ - go$readdir, - [path, options, cb], - err, - startTime || Date.now(), - Date.now() - ]) - else { - if (files && files.sort) - files.sort() + options.path = path; - if (typeof cb === 'function') - cb.call(this, err, files) - } - } - } - } + return result; + } catch (error) { + queue.delete(name); - if (process.version.substr(0, 4) === 'v0.8') { - var legStreams = legacy(fs) - ReadStream = legStreams.ReadStream - WriteStream = legStreams.WriteStream - } + options.path = path; - var fs$ReadStream = fs.ReadStream - if (fs$ReadStream) { - ReadStream.prototype = Object.create(fs$ReadStream.prototype) - ReadStream.prototype.open = ReadStream$open - } + throw error; + } + } - var fs$WriteStream = fs.WriteStream - if (fs$WriteStream) { - WriteStream.prototype = Object.create(fs$WriteStream.prototype) - WriteStream.prototype.open = WriteStream$open - } + return {alpnProtocol: cache.get(name)}; + }; +}; - Object.defineProperty(fs, 'ReadStream', { - get: function () { - return ReadStream - }, - set: function (val) { - ReadStream = val - }, - enumerable: true, - configurable: true - }) - Object.defineProperty(fs, 'WriteStream', { - get: function () { - return WriteStream - }, - set: function (val) { - WriteStream = val - }, - enumerable: true, - configurable: true - }) +const defaultResolveProtocol = createResolveProtocol(cache, queue); - // legacy names - var FileReadStream = ReadStream - Object.defineProperty(fs, 'FileReadStream', { - get: function () { - return FileReadStream - }, - set: function (val) { - FileReadStream = val - }, - enumerable: true, - configurable: true - }) - var FileWriteStream = WriteStream - Object.defineProperty(fs, 'FileWriteStream', { - get: function () { - return FileWriteStream - }, - set: function (val) { - FileWriteStream = val - }, - enumerable: true, - configurable: true - }) +module.exports = async (input, options, callback) => { + if (typeof input === 'string') { + input = urlToHttpOptions(new URL(input)); + } else if (input instanceof URL) { + input = urlToHttpOptions(input); + } else { + input = {...input}; + } - function ReadStream (path, options) { - if (this instanceof ReadStream) - return fs$ReadStream.apply(this, arguments), this - else - return ReadStream.apply(Object.create(ReadStream.prototype), arguments) - } + if (typeof options === 'function' || options === undefined) { + // (options, callback) + callback = options; + options = input; + } else { + // (input, options, callback) + options = Object.assign(input, options); + } - function ReadStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - if (that.autoClose) - that.destroy() + options.ALPNProtocols = options.ALPNProtocols || ['h2', 'http/1.1']; - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - that.read() - } - }) - } + if (!Array.isArray(options.ALPNProtocols) || options.ALPNProtocols.length === 0) { + throw new Error('The `ALPNProtocols` option must be an Array with at least one entry'); + } - function WriteStream (path, options) { - if (this instanceof WriteStream) - return fs$WriteStream.apply(this, arguments), this - else - return WriteStream.apply(Object.create(WriteStream.prototype), arguments) - } + options.protocol = options.protocol || 'https:'; + const isHttps = options.protocol === 'https:'; - function WriteStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - that.destroy() - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - } - }) - } + options.host = options.hostname || options.host || 'localhost'; + options.session = options.tlsSession; + options.servername = options.servername || calculateServerName((options.headers && options.headers.host) || options.host); + options.port = options.port || (isHttps ? 443 : 80); + options._defaultAgent = isHttps ? https.globalAgent : http.globalAgent; - function createReadStream (path, options) { - return new fs.ReadStream(path, options) - } + const resolveProtocol = options.resolveProtocol || defaultResolveProtocol; - function createWriteStream (path, options) { - return new fs.WriteStream(path, options) - } + // Note: We don't support `h2session` here - var fs$open = fs.open - fs.open = open - function open (path, flags, mode, cb) { - if (typeof mode === 'function') - cb = mode, mode = null + let {agent} = options; + if (agent !== undefined && agent !== false && agent.constructor.name !== 'Object') { + throw new Error('The `options.agent` can be only an object `http`, `https` or `http2` properties'); + } - return go$open(path, flags, mode, cb) + if (isHttps) { + options.resolveSocket = true; - function go$open (path, flags, mode, cb, startTime) { - return fs$open(path, flags, mode, function (err, fd) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } + let {socket, alpnProtocol, timeout} = await resolveProtocol(options); - return fs -} + if (timeout) { + if (socket) { + socket.destroy(); + } -function enqueue (elem) { - debug('ENQUEUE', elem[0].name, elem[1]) - fs[gracefulQueue].push(elem) - retry() -} + const error = new Error(`Timed out resolving ALPN: ${options.timeout} ms`); + error.code = 'ETIMEDOUT'; + error.ms = options.timeout; -// keep track of the timeout between retry() calls -var retryTimer + throw error; + } -// reset the startTime and lastTime to now -// this resets the start of the 60 second overall timeout as well as the -// delay between attempts so that we'll retry these jobs sooner -function resetQueue () { - var now = Date.now() - for (var i = 0; i < fs[gracefulQueue].length; ++i) { - // entries that are only a length of 2 are from an older version, don't - // bother modifying those since they'll be retried anyway. - if (fs[gracefulQueue][i].length > 2) { - fs[gracefulQueue][i][3] = now // startTime - fs[gracefulQueue][i][4] = now // lastTime - } - } - // call retry to make sure we're actively processing the queue - retry() -} + // We can't accept custom `createConnection` because the API is different for HTTP/2 + if (socket && options.createConnection) { + socket.destroy(); + socket = undefined; + } -function retry () { - // clear the timer and remove it to help prevent unintended concurrency - clearTimeout(retryTimer) - retryTimer = undefined + delete options.resolveSocket; - if (fs[gracefulQueue].length === 0) - return + const isHttp2 = alpnProtocol === 'h2'; - var elem = fs[gracefulQueue].shift() - var fn = elem[0] - var args = elem[1] - // these items may be unset if they were added by an older graceful-fs - var err = elem[2] - var startTime = elem[3] - var lastTime = elem[4] + if (agent) { + agent = isHttp2 ? agent.http2 : agent.https; + options.agent = agent; + } - // if we don't have a startTime we have no way of knowing if we've waited - // long enough, so go ahead and retry this item now - if (startTime === undefined) { - debug('RETRY', fn.name, args) - fn.apply(null, args) - } else if (Date.now() - startTime >= 60000) { - // it's been more than 60 seconds total, bail now - debug('TIMEOUT', fn.name, args) - var cb = args.pop() - if (typeof cb === 'function') - cb.call(null, err) - } else { - // the amount of time between the last attempt and right now - var sinceAttempt = Date.now() - lastTime - // the amount of time between when we first tried, and when we last tried - // rounded up to at least 1 - var sinceStart = Math.max(lastTime - startTime, 1) - // backoff. wait longer than the total time we've been retrying, but only - // up to a maximum of 100ms - var desiredDelay = Math.min(sinceStart * 1.2, 100) - // it's been long enough since the last retry, do it again - if (sinceAttempt >= desiredDelay) { - debug('RETRY', fn.name, args) - fn.apply(null, args.concat([startTime])) - } else { - // if we can't do this job yet, push it to the end of the queue - // and let the next iteration check again - fs[gracefulQueue].push(elem) - } - } + if (agent === undefined) { + agent = isHttp2 ? globalAgent : https.globalAgent; + } - // schedule our next run if one isn't already scheduled - if (retryTimer === undefined) { - retryTimer = setTimeout(retry, 0) - } -} + if (socket) { + if (agent === false) { + socket.destroy(); + } else { + const defaultCreateConnection = (isHttp2 ? Agent : https.Agent).prototype.createConnection; + if (agent.createConnection === defaultCreateConnection) { + if (isHttp2) { + options._reuseSocket = socket; + } else { + installSocket(agent, socket, options); + } + } else { + socket.destroy(); + } + } + } -/***/ }), + if (isHttp2) { + return delayAsyncDestroy(new Http2ClientRequest(options, callback)); + } + } else if (agent) { + options.agent = agent.http; + } -/***/ 3086: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // If we're sending HTTP/1.1, handle any explicitly set H2 headers in the options: + if (options.headers) { + options.headers = {...options.headers}; -var Stream = (__nccwpck_require__(2781).Stream) + // :authority is equivalent to the HTTP/1.1 host header + if (options.headers[':authority']) { + if (!options.headers.host) { + options.headers.host = options.headers[':authority']; + } -module.exports = legacy + delete options.headers[':authority']; + } -function legacy (fs) { - return { - ReadStream: ReadStream, - WriteStream: WriteStream - } + // Remove other HTTP/2 headers as they have their counterparts in the options + delete options.headers[':method']; + delete options.headers[':scheme']; + delete options.headers[':path']; + } - function ReadStream (path, options) { - if (!(this instanceof ReadStream)) return new ReadStream(path, options); + return delayAsyncDestroy(http.request(options, callback)); +}; - Stream.call(this); +module.exports.protocolCache = cache; +module.exports.resolveProtocol = defaultResolveProtocol; +module.exports.createResolveProtocol = createResolveProtocol; - var self = this; - this.path = path; - this.fd = null; - this.readable = true; - this.paused = false; +/***/ }), - this.flags = 'r'; - this.mode = 438; /*=0666*/ - this.bufferSize = 64 * 1024; +/***/ 7605: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - options = options || {}; - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } +// See https://github.com/facebook/jest/issues/2549 +// eslint-disable-next-line node/prefer-global/url +const {URL, urlToHttpOptions} = __nccwpck_require__(7016); +const http2 = __nccwpck_require__(5675); +const {Writable} = __nccwpck_require__(2203); +const {Agent, globalAgent} = __nccwpck_require__(685); +const IncomingMessage = __nccwpck_require__(2156); +const proxyEvents = __nccwpck_require__(118); +const { + ERR_INVALID_ARG_TYPE, + ERR_INVALID_PROTOCOL, + ERR_HTTP_HEADERS_SENT +} = __nccwpck_require__(9731); +const validateHeaderName = __nccwpck_require__(1212); +const validateHeaderValue = __nccwpck_require__(6462); +const proxySocketHandler = __nccwpck_require__(7083); - if (this.encoding) this.setEncoding(this.encoding); +const { + HTTP2_HEADER_STATUS, + HTTP2_HEADER_METHOD, + HTTP2_HEADER_PATH, + HTTP2_HEADER_AUTHORITY, + HTTP2_METHOD_CONNECT +} = http2.constants; - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.end === undefined) { - this.end = Infinity; - } else if ('number' !== typeof this.end) { - throw TypeError('end must be a Number'); - } +const kHeaders = Symbol('headers'); +const kOrigin = Symbol('origin'); +const kSession = Symbol('session'); +const kOptions = Symbol('options'); +const kFlushedHeaders = Symbol('flushedHeaders'); +const kJobs = Symbol('jobs'); +const kPendingAgentPromise = Symbol('pendingAgentPromise'); - if (this.start > this.end) { - throw new Error('start must be <= end'); - } +class ClientRequest extends Writable { + constructor(input, options, callback) { + super({ + autoDestroy: false, + emitClose: false + }); - this.pos = this.start; - } + if (typeof input === 'string') { + input = urlToHttpOptions(new URL(input)); + } else if (input instanceof URL) { + input = urlToHttpOptions(input); + } else { + input = {...input}; + } - if (this.fd !== null) { - process.nextTick(function() { - self._read(); - }); - return; - } + if (typeof options === 'function' || options === undefined) { + // (options, callback) + callback = options; + options = input; + } else { + // (input, options, callback) + options = Object.assign(input, options); + } - fs.open(this.path, this.flags, this.mode, function (err, fd) { - if (err) { - self.emit('error', err); - self.readable = false; - return; - } + if (options.h2session) { + this[kSession] = options.h2session; - self.fd = fd; - self.emit('open', fd); - self._read(); - }) - } + if (this[kSession].destroyed) { + throw new Error('The session has been closed already'); + } - function WriteStream (path, options) { - if (!(this instanceof WriteStream)) return new WriteStream(path, options); + this.protocol = this[kSession].socket.encrypted ? 'https:' : 'http:'; + } else if (options.agent === false) { + this.agent = new Agent({maxEmptySessions: 0}); + } else if (typeof options.agent === 'undefined' || options.agent === null) { + this.agent = globalAgent; + } else if (typeof options.agent.request === 'function') { + this.agent = options.agent; + } else { + throw new ERR_INVALID_ARG_TYPE('options.agent', ['http2wrapper.Agent-like Object', 'undefined', 'false'], options.agent); + } - Stream.call(this); + if (this.agent) { + this.protocol = this.agent.protocol; + } - this.path = path; - this.fd = null; - this.writable = true; + if (options.protocol && options.protocol !== this.protocol) { + throw new ERR_INVALID_PROTOCOL(options.protocol, this.protocol); + } - this.flags = 'w'; - this.encoding = 'binary'; - this.mode = 438; /*=0666*/ - this.bytesWritten = 0; + if (!options.port) { + options.port = options.defaultPort || (this.agent && this.agent.defaultPort) || 443; + } - options = options || {}; + options.host = options.hostname || options.host || 'localhost'; - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } + // Unused + delete options.hostname; - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.start < 0) { - throw new Error('start must be >= zero'); - } + const {timeout} = options; + options.timeout = undefined; - this.pos = this.start; - } + this[kHeaders] = Object.create(null); + this[kJobs] = []; - this.busy = false; - this._queue = []; + this[kPendingAgentPromise] = undefined; - if (this.fd === null) { - this._open = fs.open; - this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); - this.flush(); - } - } -} + this.socket = null; + this.connection = null; + this.method = options.method || 'GET'; -/***/ }), + if (!(this.method === 'CONNECT' && (options.path === '/' || options.path === undefined))) { + this.path = options.path; + } -/***/ 263: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this.res = null; + this.aborted = false; + this.reusedSocket = false; -var constants = __nccwpck_require__(2057) + const {headers} = options; + if (headers) { + // eslint-disable-next-line guard-for-in + for (const header in headers) { + this.setHeader(header, headers[header]); + } + } -var origCwd = process.cwd -var cwd = null + if (options.auth && !('authorization' in this[kHeaders])) { + this[kHeaders].authorization = 'Basic ' + Buffer.from(options.auth).toString('base64'); + } -var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform + options.session = options.tlsSession; + options.path = options.socketPath; -process.cwd = function() { - if (!cwd) - cwd = origCwd.call(process) - return cwd -} -try { - process.cwd() -} catch (er) {} + this[kOptions] = options; -// This check is needed until node.js 12 is required -if (typeof process.chdir === 'function') { - var chdir = process.chdir - process.chdir = function (d) { - cwd = null - chdir.call(process, d) - } - if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir) -} + // Clients that generate HTTP/2 requests directly SHOULD use the :authority pseudo-header field instead of the Host header field. + this[kOrigin] = new URL(`${this.protocol}//${options.servername || options.host}:${options.port}`); -module.exports = patch + // A socket is being reused + const reuseSocket = options._reuseSocket; + if (reuseSocket) { + options.createConnection = (...args) => { + if (reuseSocket.destroyed) { + return this.agent.createConnection(...args); + } -function patch (fs) { - // (re-)implement some things that are known busted or missing. + return reuseSocket; + }; - // lchmod, broken prior to 0.6.2 - // back-port the fix here. - if (constants.hasOwnProperty('O_SYMLINK') && - process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { - patchLchmod(fs) - } + // eslint-disable-next-line promise/prefer-await-to-then + this.agent.getSession(this[kOrigin], this[kOptions]).catch(() => {}); + } - // lutimes implementation, or no-op - if (!fs.lutimes) { - patchLutimes(fs) - } + if (timeout) { + this.setTimeout(timeout); + } - // https://github.com/isaacs/node-graceful-fs/issues/4 - // Chown should not fail on einval or eperm if non-root. - // It should not fail on enosys ever, as this just indicates - // that a fs doesn't support the intended operation. + if (callback) { + this.once('response', callback); + } - fs.chown = chownFix(fs.chown) - fs.fchown = chownFix(fs.fchown) - fs.lchown = chownFix(fs.lchown) + this[kFlushedHeaders] = false; + } - fs.chmod = chmodFix(fs.chmod) - fs.fchmod = chmodFix(fs.fchmod) - fs.lchmod = chmodFix(fs.lchmod) + get method() { + return this[kHeaders][HTTP2_HEADER_METHOD]; + } - fs.chownSync = chownFixSync(fs.chownSync) - fs.fchownSync = chownFixSync(fs.fchownSync) - fs.lchownSync = chownFixSync(fs.lchownSync) + set method(value) { + if (value) { + this[kHeaders][HTTP2_HEADER_METHOD] = value.toUpperCase(); + } + } - fs.chmodSync = chmodFixSync(fs.chmodSync) - fs.fchmodSync = chmodFixSync(fs.fchmodSync) - fs.lchmodSync = chmodFixSync(fs.lchmodSync) + get path() { + const header = this.method === 'CONNECT' ? HTTP2_HEADER_AUTHORITY : HTTP2_HEADER_PATH; - fs.stat = statFix(fs.stat) - fs.fstat = statFix(fs.fstat) - fs.lstat = statFix(fs.lstat) + return this[kHeaders][header]; + } - fs.statSync = statFixSync(fs.statSync) - fs.fstatSync = statFixSync(fs.fstatSync) - fs.lstatSync = statFixSync(fs.lstatSync) + set path(value) { + if (value) { + const header = this.method === 'CONNECT' ? HTTP2_HEADER_AUTHORITY : HTTP2_HEADER_PATH; - // if lchmod/lchown do not exist, then make them no-ops - if (fs.chmod && !fs.lchmod) { - fs.lchmod = function (path, mode, cb) { - if (cb) process.nextTick(cb) - } - fs.lchmodSync = function () {} - } - if (fs.chown && !fs.lchown) { - fs.lchown = function (path, uid, gid, cb) { - if (cb) process.nextTick(cb) - } - fs.lchownSync = function () {} - } + this[kHeaders][header] = value; + } + } - // on Windows, A/V software can lock the directory, causing this - // to fail with an EACCES or EPERM if the directory contains newly - // created files. Try again on failure, for up to 60 seconds. + get host() { + return this[kOrigin].hostname; + } - // Set the timeout this long because some Windows Anti-Virus, such as Parity - // bit9, may lock files for up to a minute, causing npm package install - // failures. Also, take care to yield the scheduler. Windows scheduling gives - // CPU to a busy looping process, which can cause the program causing the lock - // contention to be starved of CPU by node, so the contention doesn't resolve. - if (platform === "win32") { - fs.rename = typeof fs.rename !== 'function' ? fs.rename - : (function (fs$rename) { - function rename (from, to, cb) { - var start = Date.now() - var backoff = 0; - fs$rename(from, to, function CB (er) { - if (er - && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") - && Date.now() - start < 60000) { - setTimeout(function() { - fs.stat(to, function (stater, st) { - if (stater && stater.code === "ENOENT") - fs$rename(from, to, CB); - else - cb(er) - }) - }, backoff) - if (backoff < 100) - backoff += 10; - return; - } - if (cb) cb(er) - }) - } - if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename) - return rename - })(fs.rename) - } + set host(_value) { + // Do nothing as this is read only. + } - // if read() returns EAGAIN, then just try it again. - fs.read = typeof fs.read !== 'function' ? fs.read - : (function (fs$read) { - function read (fd, buffer, offset, length, position, callback_) { - var callback - if (callback_ && typeof callback_ === 'function') { - var eagCounter = 0 - callback = function (er, _, __) { - if (er && er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - } - callback_.apply(this, arguments) - } - } - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - } + get _mustNotHaveABody() { + return this.method === 'GET' || this.method === 'HEAD' || this.method === 'DELETE'; + } - // This ensures `util.promisify` works as it does for native `fs.read`. - if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read) - return read - })(fs.read) + _write(chunk, encoding, callback) { + // https://github.com/nodejs/node/blob/654df09ae0c5e17d1b52a900a545f0664d8c7627/lib/internal/http2/util.js#L148-L156 + if (this._mustNotHaveABody) { + callback(new Error('The GET, HEAD and DELETE methods must NOT have a body')); + /* istanbul ignore next: Node.js 12 throws directly */ + return; + } - fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync - : (function (fs$readSync) { return function (fd, buffer, offset, length, position) { - var eagCounter = 0 - while (true) { - try { - return fs$readSync.call(fs, fd, buffer, offset, length, position) - } catch (er) { - if (er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - continue - } - throw er - } - } - }})(fs.readSync) + this.flushHeaders(); - function patchLchmod (fs) { - fs.lchmod = function (path, mode, callback) { - fs.open( path - , constants.O_WRONLY | constants.O_SYMLINK - , mode - , function (err, fd) { - if (err) { - if (callback) callback(err) - return - } - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - fs.fchmod(fd, mode, function (err) { - fs.close(fd, function(err2) { - if (callback) callback(err || err2) - }) - }) - }) - } + const callWrite = () => this._request.write(chunk, encoding, callback); + if (this._request) { + callWrite(); + } else { + this[kJobs].push(callWrite); + } + } - fs.lchmodSync = function (path, mode) { - var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) + _final(callback) { + this.flushHeaders(); - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - var threw = true - var ret - try { - ret = fs.fchmodSync(fd, mode) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret - } - } + const callEnd = () => { + // For GET, HEAD and DELETE and CONNECT + if (this._mustNotHaveABody || this.method === 'CONNECT') { + callback(); + return; + } - function patchLutimes (fs) { - if (constants.hasOwnProperty("O_SYMLINK") && fs.futimes) { - fs.lutimes = function (path, at, mt, cb) { - fs.open(path, constants.O_SYMLINK, function (er, fd) { - if (er) { - if (cb) cb(er) - return - } - fs.futimes(fd, at, mt, function (er) { - fs.close(fd, function (er2) { - if (cb) cb(er || er2) - }) - }) - }) - } - - fs.lutimesSync = function (path, at, mt) { - var fd = fs.openSync(path, constants.O_SYMLINK) - var ret - var threw = true - try { - ret = fs.futimesSync(fd, at, mt) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret - } + this._request.end(callback); + }; - } else if (fs.futimes) { - fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } - fs.lutimesSync = function () {} - } - } + if (this._request) { + callEnd(); + } else { + this[kJobs].push(callEnd); + } + } - function chmodFix (orig) { - if (!orig) return orig - return function (target, mode, cb) { - return orig.call(fs, target, mode, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) - } - } + abort() { + if (this.res && this.res.complete) { + return; + } - function chmodFixSync (orig) { - if (!orig) return orig - return function (target, mode) { - try { - return orig.call(fs, target, mode) - } catch (er) { - if (!chownErOk(er)) throw er - } - } - } + if (!this.aborted) { + process.nextTick(() => this.emit('abort')); + } + this.aborted = true; - function chownFix (orig) { - if (!orig) return orig - return function (target, uid, gid, cb) { - return orig.call(fs, target, uid, gid, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) - } - } + this.destroy(); + } - function chownFixSync (orig) { - if (!orig) return orig - return function (target, uid, gid) { - try { - return orig.call(fs, target, uid, gid) - } catch (er) { - if (!chownErOk(er)) throw er - } - } - } + async _destroy(error, callback) { + if (this.res) { + this.res._dump(); + } - function statFix (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, options, cb) { - if (typeof options === 'function') { - cb = options - options = null - } - function callback (er, stats) { - if (stats) { - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - } - if (cb) cb.apply(this, arguments) - } - return options ? orig.call(fs, target, options, callback) - : orig.call(fs, target, callback) - } - } + if (this._request) { + this._request.destroy(); + } else { + process.nextTick(() => { + this.emit('close'); + }); + } - function statFixSync (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, options) { - var stats = options ? orig.call(fs, target, options) - : orig.call(fs, target) - if (stats) { - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - } - return stats; - } - } + try { + await this[kPendingAgentPromise]; + } catch (internalError) { + if (this.aborted) { + error = internalError; + } + } - // ENOSYS means that the fs doesn't support the op. Just ignore - // that, because it doesn't matter. - // - // if there's no getuid, or if getuid() is something other - // than 0, and the error is EINVAL or EPERM, then just ignore - // it. - // - // This specific case is a silent failure in cp, install, tar, - // and most other unix tools that manage permissions. - // - // When running as root, or if other types of errors are - // encountered, then it's strict. - function chownErOk (er) { - if (!er) - return true + callback(error); + } - if (er.code === "ENOSYS") - return true + async flushHeaders() { + if (this[kFlushedHeaders] || this.destroyed) { + return; + } - var nonroot = !process.getuid || process.getuid() !== 0 - if (nonroot) { - if (er.code === "EINVAL" || er.code === "EPERM") - return true - } + this[kFlushedHeaders] = true; - return false - } -} + const isConnectMethod = this.method === HTTP2_METHOD_CONNECT; + // The real magic is here + const onStream = stream => { + this._request = stream; -/***/ }), + if (this.destroyed) { + stream.destroy(); + return; + } -/***/ 1002: -/***/ ((module) => { + // Forwards `timeout`, `continue`, `close` and `error` events to this instance. + if (!isConnectMethod) { + // TODO: Should we proxy `close` here? + proxyEvents(stream, this, ['timeout', 'continue']); + } + stream.once('error', error => { + this.destroy(error); + }); -// rfc7231 6.1 -const statusCodeCacheableByDefault = new Set([ - 200, - 203, - 204, - 206, - 300, - 301, - 308, - 404, - 405, - 410, - 414, - 501, -]); + stream.once('aborted', () => { + const {res} = this; + if (res) { + res.aborted = true; + res.emit('aborted'); + res.destroy(); + } else { + this.destroy(new Error('The server aborted the HTTP/2 stream')); + } + }); -// This implementation does not understand partial responses (206) -const understoodStatuses = new Set([ - 200, - 203, - 204, - 300, - 301, - 302, - 303, - 307, - 308, - 404, - 405, - 410, - 414, - 501, -]); + const onResponse = (headers, flags, rawHeaders) => { + // If we were to emit raw request stream, it would be as fast as the native approach. + // Note that wrapping the raw stream in a Proxy instance won't improve the performance (already tested it). + const response = new IncomingMessage(this.socket, stream.readableHighWaterMark); + this.res = response; -const errorStatusCodes = new Set([ - 500, - 502, - 503, - 504, -]); + // Undocumented, but it is used by `cacheable-request` + response.url = `${this[kOrigin].origin}${this.path}`; -const hopByHopHeaders = { - date: true, // included, because we add Age update Date - connection: true, - 'keep-alive': true, - 'proxy-authenticate': true, - 'proxy-authorization': true, - te: true, - trailer: true, - 'transfer-encoding': true, - upgrade: true, -}; + response.req = this; + response.statusCode = headers[HTTP2_HEADER_STATUS]; + response.headers = headers; + response.rawHeaders = rawHeaders; -const excludedFromRevalidationUpdate = { - // Since the old body is reused, it doesn't make sense to change properties of the body - 'content-length': true, - 'content-encoding': true, - 'transfer-encoding': true, - 'content-range': true, -}; + response.once('end', () => { + response.complete = true; -function toNumberOrZero(s) { - const n = parseInt(s, 10); - return isFinite(n) ? n : 0; -} + // Has no effect, just be consistent with the Node.js behavior + response.socket = null; + response.connection = null; + }); -// RFC 5861 -function isErrorResponse(response) { - // consider undefined response as faulty - if(!response) { - return true - } - return errorStatusCodes.has(response.status); -} + if (isConnectMethod) { + response.upgrade = true; -function parseCacheControl(header) { - const cc = {}; - if (!header) return cc; + // The HTTP1 API says the socket is detached here, + // but we can't do that so we pass the original HTTP2 request. + if (this.emit('connect', response, stream, Buffer.alloc(0))) { + this.emit('close'); + } else { + // No listeners attached, destroy the original request. + stream.destroy(); + } + } else { + // Forwards data + stream.on('data', chunk => { + if (!response._dumped && !response.push(chunk)) { + stream.pause(); + } + }); - // TODO: When there is more than one value present for a given directive (e.g., two Expires header fields, multiple Cache-Control: max-age directives), - // the directive's value is considered invalid. Caches are encouraged to consider responses that have invalid freshness information to be stale - const parts = header.trim().split(/,/); - for (const part of parts) { - const [k, v] = part.split(/=/, 2); - cc[k.trim()] = v === undefined ? true : v.trim().replace(/^"|"$/g, ''); - } + stream.once('end', () => { + if (!this.aborted) { + response.push(null); + } + }); - return cc; -} + if (!this.emit('response', response)) { + // No listeners attached, dump the response. + response._dump(); + } + } + }; -function formatCacheControl(cc) { - let parts = []; - for (const k in cc) { - const v = cc[k]; - parts.push(v === true ? k : k + '=' + v); - } - if (!parts.length) { - return undefined; - } - return parts.join(', '); -} + // This event tells we are ready to listen for the data. + stream.once('response', onResponse); -module.exports = class CachePolicy { - constructor( - req, - res, - { - shared, - cacheHeuristic, - immutableMinTimeToLive, - ignoreCargoCult, - _fromObject, - } = {} - ) { - if (_fromObject) { - this._fromObject(_fromObject); - return; - } + // Emits `information` event + stream.once('headers', headers => this.emit('information', {statusCode: headers[HTTP2_HEADER_STATUS]})); - if (!res || !res.headers) { - throw Error('Response headers missing'); - } - this._assertRequestHasHeaders(req); + stream.once('trailers', (trailers, flags, rawTrailers) => { + const {res} = this; - this._responseTime = this.now(); - this._isShared = shared !== false; - this._cacheHeuristic = - undefined !== cacheHeuristic ? cacheHeuristic : 0.1; // 10% matches IE - this._immutableMinTtl = - undefined !== immutableMinTimeToLive - ? immutableMinTimeToLive - : 24 * 3600 * 1000; + // https://github.com/nodejs/node/issues/41251 + if (res === null) { + onResponse(trailers, flags, rawTrailers); + return; + } - this._status = 'status' in res ? res.status : 200; - this._resHeaders = res.headers; - this._rescc = parseCacheControl(res.headers['cache-control']); - this._method = 'method' in req ? req.method : 'GET'; - this._url = req.url; - this._host = req.headers.host; - this._noAuthorization = !req.headers.authorization; - this._reqHeaders = res.headers.vary ? req.headers : null; // Don't keep all request headers if they won't be used - this._reqcc = parseCacheControl(req.headers['cache-control']); + // Assigns trailers to the response object. + res.trailers = trailers; + res.rawTrailers = rawTrailers; + }); - // Assume that if someone uses legacy, non-standard uncecessary options they don't understand caching, - // so there's no point stricly adhering to the blindly copy&pasted directives. - if ( - ignoreCargoCult && - 'pre-check' in this._rescc && - 'post-check' in this._rescc - ) { - delete this._rescc['pre-check']; - delete this._rescc['post-check']; - delete this._rescc['no-cache']; - delete this._rescc['no-store']; - delete this._rescc['must-revalidate']; - this._resHeaders = Object.assign({}, this._resHeaders, { - 'cache-control': formatCacheControl(this._rescc), - }); - delete this._resHeaders.expires; - delete this._resHeaders.pragma; - } + stream.once('close', () => { + const {aborted, res} = this; + if (res) { + if (aborted) { + res.aborted = true; + res.emit('aborted'); + res.destroy(); + } - // When the Cache-Control header field is not present in a request, caches MUST consider the no-cache request pragma-directive - // as having the same effect as if "Cache-Control: no-cache" were present (see Section 5.2.1). - if ( - res.headers['cache-control'] == null && - /no-cache/.test(res.headers.pragma) - ) { - this._rescc['no-cache'] = true; - } - } + const finish = () => { + res.emit('close'); - now() { - return Date.now(); - } + this.destroy(); + this.emit('close'); + }; - storable() { - // The "no-store" request directive indicates that a cache MUST NOT store any part of either this request or any response to it. - return !!( - !this._reqcc['no-store'] && - // A cache MUST NOT store a response to any request, unless: - // The request method is understood by the cache and defined as being cacheable, and - ('GET' === this._method || - 'HEAD' === this._method || - ('POST' === this._method && this._hasExplicitExpiration())) && - // the response status code is understood by the cache, and - understoodStatuses.has(this._status) && - // the "no-store" cache directive does not appear in request or response header fields, and - !this._rescc['no-store'] && - // the "private" response directive does not appear in the response, if the cache is shared, and - (!this._isShared || !this._rescc.private) && - // the Authorization header field does not appear in the request, if the cache is shared, - (!this._isShared || - this._noAuthorization || - this._allowsStoringAuthenticated()) && - // the response either: - // contains an Expires header field, or - (this._resHeaders.expires || - // contains a max-age response directive, or - // contains a s-maxage response directive and the cache is shared, or - // contains a public response directive. - this._rescc['max-age'] || - (this._isShared && this._rescc['s-maxage']) || - this._rescc.public || - // has a status code that is defined as cacheable by default - statusCodeCacheableByDefault.has(this._status)) - ); - } + if (res.readable) { + res.once('end', finish); + } else { + finish(); + } - _hasExplicitExpiration() { - // 4.2.1 Calculating Freshness Lifetime - return ( - (this._isShared && this._rescc['s-maxage']) || - this._rescc['max-age'] || - this._resHeaders.expires - ); - } + return; + } - _assertRequestHasHeaders(req) { - if (!req || !req.headers) { - throw Error('Request headers missing'); - } - } + if (!this.destroyed) { + this.destroy(new Error('The HTTP/2 stream has been early terminated')); + this.emit('close'); + return; + } - satisfiesWithoutRevalidation(req) { - this._assertRequestHasHeaders(req); + this.destroy(); + this.emit('close'); + }); - // When presented with a request, a cache MUST NOT reuse a stored response, unless: - // the presented request does not contain the no-cache pragma (Section 5.4), nor the no-cache cache directive, - // unless the stored response is successfully validated (Section 4.3), and - const requestCC = parseCacheControl(req.headers['cache-control']); - if (requestCC['no-cache'] || /no-cache/.test(req.headers.pragma)) { - return false; - } + this.socket = new Proxy(stream, proxySocketHandler); - if (requestCC['max-age'] && this.age() > requestCC['max-age']) { - return false; - } + for (const job of this[kJobs]) { + job(); + } - if ( - requestCC['min-fresh'] && - this.timeToLive() < 1000 * requestCC['min-fresh'] - ) { - return false; - } + this[kJobs].length = 0; - // the stored response is either: - // fresh, or allowed to be served stale - if (this.stale()) { - const allowsStale = - requestCC['max-stale'] && - !this._rescc['must-revalidate'] && - (true === requestCC['max-stale'] || - requestCC['max-stale'] > this.age() - this.maxAge()); - if (!allowsStale) { - return false; - } - } - - return this._requestMatches(req, false); - } + this.emit('socket', this.socket); + }; - _requestMatches(req, allowHeadMethod) { - // The presented effective request URI and that of the stored response match, and - return ( - (!this._url || this._url === req.url) && - this._host === req.headers.host && - // the request method associated with the stored response allows it to be used for the presented request, and - (!req.method || - this._method === req.method || - (allowHeadMethod && 'HEAD' === req.method)) && - // selecting header fields nominated by the stored response (if any) match those presented, and - this._varyMatches(req) - ); - } + if (!(HTTP2_HEADER_AUTHORITY in this[kHeaders]) && !isConnectMethod) { + this[kHeaders][HTTP2_HEADER_AUTHORITY] = this[kOrigin].host; + } - _allowsStoringAuthenticated() { - // following Cache-Control response directives (Section 5.2.2) have such an effect: must-revalidate, public, and s-maxage. - return ( - this._rescc['must-revalidate'] || - this._rescc.public || - this._rescc['s-maxage'] - ); - } + // Makes a HTTP2 request + if (this[kSession]) { + try { + onStream(this[kSession].request(this[kHeaders])); + } catch (error) { + this.destroy(error); + } + } else { + this.reusedSocket = true; - _varyMatches(req) { - if (!this._resHeaders.vary) { - return true; - } + try { + const promise = this.agent.request(this[kOrigin], this[kOptions], this[kHeaders]); + this[kPendingAgentPromise] = promise; - // A Vary header field-value of "*" always fails to match - if (this._resHeaders.vary === '*') { - return false; - } + onStream(await promise); - const fields = this._resHeaders.vary - .trim() - .toLowerCase() - .split(/\s*,\s*/); - for (const name of fields) { - if (req.headers[name] !== this._reqHeaders[name]) return false; - } - return true; - } + this[kPendingAgentPromise] = false; + } catch (error) { + this[kPendingAgentPromise] = false; - _copyWithoutHopByHopHeaders(inHeaders) { - const headers = {}; - for (const name in inHeaders) { - if (hopByHopHeaders[name]) continue; - headers[name] = inHeaders[name]; - } - // 9.1. Connection - if (inHeaders.connection) { - const tokens = inHeaders.connection.trim().split(/\s*,\s*/); - for (const name of tokens) { - delete headers[name]; - } - } - if (headers.warning) { - const warnings = headers.warning.split(/,/).filter(warning => { - return !/^\s*1[0-9][0-9]/.test(warning); - }); - if (!warnings.length) { - delete headers.warning; - } else { - headers.warning = warnings.join(',').trim(); - } - } - return headers; - } + this.destroy(error); + } + } + } - responseHeaders() { - const headers = this._copyWithoutHopByHopHeaders(this._resHeaders); - const age = this.age(); + get connection() { + return this.socket; + } - // A cache SHOULD generate 113 warning if it heuristically chose a freshness - // lifetime greater than 24 hours and the response's age is greater than 24 hours. - if ( - age > 3600 * 24 && - !this._hasExplicitExpiration() && - this.maxAge() > 3600 * 24 - ) { - headers.warning = - (headers.warning ? `${headers.warning}, ` : '') + - '113 - "rfc7234 5.5.4"'; - } - headers.age = `${Math.round(age)}`; - headers.date = new Date(this.now()).toUTCString(); - return headers; - } + set connection(value) { + this.socket = value; + } - /** - * Value of the Date response header or current time if Date was invalid - * @return timestamp - */ - date() { - const serverDate = Date.parse(this._resHeaders.date); - if (isFinite(serverDate)) { - return serverDate; - } - return this._responseTime; - } + getHeaderNames() { + return Object.keys(this[kHeaders]); + } - /** - * Value of the Age header, in seconds, updated for the current time. - * May be fractional. - * - * @return Number - */ - age() { - let age = this._ageValue(); + hasHeader(name) { + if (typeof name !== 'string') { + throw new ERR_INVALID_ARG_TYPE('name', 'string', name); + } - const residentTime = (this.now() - this._responseTime) / 1000; - return age + residentTime; - } + return Boolean(this[kHeaders][name.toLowerCase()]); + } - _ageValue() { - return toNumberOrZero(this._resHeaders.age); - } + getHeader(name) { + if (typeof name !== 'string') { + throw new ERR_INVALID_ARG_TYPE('name', 'string', name); + } - /** - * Value of applicable max-age (or heuristic equivalent) in seconds. This counts since response's `Date`. - * - * For an up-to-date value, see `timeToLive()`. - * - * @return Number - */ - maxAge() { - if (!this.storable() || this._rescc['no-cache']) { - return 0; - } + return this[kHeaders][name.toLowerCase()]; + } - // Shared responses with cookies are cacheable according to the RFC, but IMHO it'd be unwise to do so by default - // so this implementation requires explicit opt-in via public header - if ( - this._isShared && - (this._resHeaders['set-cookie'] && - !this._rescc.public && - !this._rescc.immutable) - ) { - return 0; - } + get headersSent() { + return this[kFlushedHeaders]; + } - if (this._resHeaders.vary === '*') { - return 0; - } + removeHeader(name) { + if (typeof name !== 'string') { + throw new ERR_INVALID_ARG_TYPE('name', 'string', name); + } - if (this._isShared) { - if (this._rescc['proxy-revalidate']) { - return 0; - } - // if a response includes the s-maxage directive, a shared cache recipient MUST ignore the Expires field. - if (this._rescc['s-maxage']) { - return toNumberOrZero(this._rescc['s-maxage']); - } - } + if (this.headersSent) { + throw new ERR_HTTP_HEADERS_SENT('remove'); + } - // If a response includes a Cache-Control field with the max-age directive, a recipient MUST ignore the Expires field. - if (this._rescc['max-age']) { - return toNumberOrZero(this._rescc['max-age']); - } + delete this[kHeaders][name.toLowerCase()]; + } - const defaultMinTtl = this._rescc.immutable ? this._immutableMinTtl : 0; + setHeader(name, value) { + if (this.headersSent) { + throw new ERR_HTTP_HEADERS_SENT('set'); + } - const serverDate = this.date(); - if (this._resHeaders.expires) { - const expires = Date.parse(this._resHeaders.expires); - // A cache recipient MUST interpret invalid date formats, especially the value "0", as representing a time in the past (i.e., "already expired"). - if (Number.isNaN(expires) || expires < serverDate) { - return 0; - } - return Math.max(defaultMinTtl, (expires - serverDate) / 1000); - } + validateHeaderName(name); + validateHeaderValue(name, value); - if (this._resHeaders['last-modified']) { - const lastModified = Date.parse(this._resHeaders['last-modified']); - if (isFinite(lastModified) && serverDate > lastModified) { - return Math.max( - defaultMinTtl, - ((serverDate - lastModified) / 1000) * this._cacheHeuristic - ); - } - } + const lowercased = name.toLowerCase(); - return defaultMinTtl; - } + if (lowercased === 'connection') { + if (value.toLowerCase() === 'keep-alive') { + return; + } - timeToLive() { - const age = this.maxAge() - this.age(); - const staleIfErrorAge = age + toNumberOrZero(this._rescc['stale-if-error']); - const staleWhileRevalidateAge = age + toNumberOrZero(this._rescc['stale-while-revalidate']); - return Math.max(0, age, staleIfErrorAge, staleWhileRevalidateAge) * 1000; - } + throw new Error(`Invalid 'connection' header: ${value}`); + } - stale() { - return this.maxAge() <= this.age(); - } + if (lowercased === 'host' && this.method === 'CONNECT') { + this[kHeaders][HTTP2_HEADER_AUTHORITY] = value; + } else { + this[kHeaders][lowercased] = value; + } + } - _useStaleIfError() { - return this.maxAge() + toNumberOrZero(this._rescc['stale-if-error']) > this.age(); - } + setNoDelay() { + // HTTP2 sockets cannot be malformed, do nothing. + } - useStaleWhileRevalidate() { - return this.maxAge() + toNumberOrZero(this._rescc['stale-while-revalidate']) > this.age(); - } + setSocketKeepAlive() { + // HTTP2 sockets cannot be malformed, do nothing. + } - static fromObject(obj) { - return new this(undefined, undefined, { _fromObject: obj }); - } + setTimeout(ms, callback) { + const applyTimeout = () => this._request.setTimeout(ms, callback); - _fromObject(obj) { - if (this._responseTime) throw Error('Reinitialized'); - if (!obj || obj.v !== 1) throw Error('Invalid serialization'); + if (this._request) { + applyTimeout(); + } else { + this[kJobs].push(applyTimeout); + } - this._responseTime = obj.t; - this._isShared = obj.sh; - this._cacheHeuristic = obj.ch; - this._immutableMinTtl = - obj.imm !== undefined ? obj.imm : 24 * 3600 * 1000; - this._status = obj.st; - this._resHeaders = obj.resh; - this._rescc = obj.rescc; - this._method = obj.m; - this._url = obj.u; - this._host = obj.h; - this._noAuthorization = obj.a; - this._reqHeaders = obj.reqh; - this._reqcc = obj.reqcc; - } + return this; + } - toObject() { - return { - v: 1, - t: this._responseTime, - sh: this._isShared, - ch: this._cacheHeuristic, - imm: this._immutableMinTtl, - st: this._status, - resh: this._resHeaders, - rescc: this._rescc, - m: this._method, - u: this._url, - h: this._host, - a: this._noAuthorization, - reqh: this._reqHeaders, - reqcc: this._reqcc, - }; - } + get maxHeadersCount() { + if (!this.destroyed && this._request) { + return this._request.session.localSettings.maxHeaderListSize; + } - /** - * Headers for sending to the origin server to revalidate stale response. - * Allows server to return 304 to allow reuse of the previous response. - * - * Hop by hop headers are always stripped. - * Revalidation headers may be added or removed, depending on request. - */ - revalidationHeaders(incomingReq) { - this._assertRequestHasHeaders(incomingReq); - const headers = this._copyWithoutHopByHopHeaders(incomingReq.headers); + return undefined; + } - // This implementation does not understand range requests - delete headers['if-range']; + set maxHeadersCount(_value) { + // Updating HTTP2 settings would affect all requests, do nothing. + } +} - if (!this._requestMatches(incomingReq, true) || !this.storable()) { - // revalidation allowed via HEAD - // not for the same resource, or wasn't allowed to be cached anyway - delete headers['if-none-match']; - delete headers['if-modified-since']; - return headers; - } +module.exports = ClientRequest; - /* MUST send that entity-tag in any cache validation request (using If-Match or If-None-Match) if an entity-tag has been provided by the origin server. */ - if (this._resHeaders.etag) { - headers['if-none-match'] = headers['if-none-match'] - ? `${headers['if-none-match']}, ${this._resHeaders.etag}` - : this._resHeaders.etag; - } - // Clients MAY issue simple (non-subrange) GET requests with either weak validators or strong validators. Clients MUST NOT use weak validators in other forms of request. - const forbidsWeakValidators = - headers['accept-ranges'] || - headers['if-match'] || - headers['if-unmodified-since'] || - (this._method && this._method != 'GET'); +/***/ }), - /* SHOULD send the Last-Modified value in non-subrange cache validation requests (using If-Modified-Since) if only a Last-Modified value has been provided by the origin server. - Note: This implementation does not understand partial responses (206) */ - if (forbidsWeakValidators) { - delete headers['if-modified-since']; +/***/ 2156: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (headers['if-none-match']) { - const etags = headers['if-none-match'] - .split(/,/) - .filter(etag => { - return !/^\s*W\//.test(etag); - }); - if (!etags.length) { - delete headers['if-none-match']; - } else { - headers['if-none-match'] = etags.join(',').trim(); - } - } - } else if ( - this._resHeaders['last-modified'] && - !headers['if-modified-since'] - ) { - headers['if-modified-since'] = this._resHeaders['last-modified']; - } - return headers; - } +const {Readable} = __nccwpck_require__(2203); - /** - * Creates new CachePolicy with information combined from the previews response, - * and the new revalidation response. - * - * Returns {policy, modified} where modified is a boolean indicating - * whether the response body has been modified, and old cached body can't be used. - * - * @return {Object} {policy: CachePolicy, modified: Boolean} - */ - revalidatedPolicy(request, response) { - this._assertRequestHasHeaders(request); - if(this._useStaleIfError() && isErrorResponse(response)) { // I consider the revalidation request unsuccessful - return { - modified: false, - matches: false, - policy: this, - }; - } - if (!response || !response.headers) { - throw Error('Response headers missing'); - } +class IncomingMessage extends Readable { + constructor(socket, highWaterMark) { + super({ + emitClose: false, + autoDestroy: true, + highWaterMark + }); - // These aren't going to be supported exactly, since one CachePolicy object - // doesn't know about all the other cached objects. - let matches = false; - if (response.status !== undefined && response.status != 304) { - matches = false; - } else if ( - response.headers.etag && - !/^\s*W\//.test(response.headers.etag) - ) { - // "All of the stored responses with the same strong validator are selected. - // If none of the stored responses contain the same strong validator, - // then the cache MUST NOT use the new response to update any stored responses." - matches = - this._resHeaders.etag && - this._resHeaders.etag.replace(/^\s*W\//, '') === - response.headers.etag; - } else if (this._resHeaders.etag && response.headers.etag) { - // "If the new response contains a weak validator and that validator corresponds - // to one of the cache's stored responses, - // then the most recent of those matching stored responses is selected for update." - matches = - this._resHeaders.etag.replace(/^\s*W\//, '') === - response.headers.etag.replace(/^\s*W\//, ''); - } else if (this._resHeaders['last-modified']) { - matches = - this._resHeaders['last-modified'] === - response.headers['last-modified']; - } else { - // If the new response does not include any form of validator (such as in the case where - // a client generates an If-Modified-Since request from a source other than the Last-Modified - // response header field), and there is only one stored response, and that stored response also - // lacks a validator, then that stored response is selected for update. - if ( - !this._resHeaders.etag && - !this._resHeaders['last-modified'] && - !response.headers.etag && - !response.headers['last-modified'] - ) { - matches = true; - } - } + this.statusCode = null; + this.statusMessage = ''; + this.httpVersion = '2.0'; + this.httpVersionMajor = 2; + this.httpVersionMinor = 0; + this.headers = {}; + this.trailers = {}; + this.req = null; - if (!matches) { - return { - policy: new this.constructor(request, response), - // Client receiving 304 without body, even if it's invalid/mismatched has no option - // but to reuse a cached body. We don't have a good way to tell clients to do - // error recovery in such case. - modified: response.status != 304, - matches: false, - }; - } + this.aborted = false; + this.complete = false; + this.upgrade = null; - // use other header fields provided in the 304 (Not Modified) response to replace all instances - // of the corresponding header fields in the stored response. - const headers = {}; - for (const k in this._resHeaders) { - headers[k] = - k in response.headers && !excludedFromRevalidationUpdate[k] - ? response.headers[k] - : this._resHeaders[k]; - } + this.rawHeaders = []; + this.rawTrailers = []; - const newResponse = Object.assign({}, response, { - status: this._status, - method: this._method, - headers, - }); - return { - policy: new this.constructor(request, newResponse, { - shared: this._isShared, - cacheHeuristic: this._cacheHeuristic, - immutableMinTimeToLive: this._immutableMinTtl, - }), - modified: false, - matches: true, - }; - } -}; + this.socket = socket; + this._dumped = false; + } -/***/ }), - -/***/ 9898: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -// See https://github.com/facebook/jest/issues/2549 -// eslint-disable-next-line node/prefer-global/url -const {URL} = __nccwpck_require__(7310); -const EventEmitter = __nccwpck_require__(2361); -const tls = __nccwpck_require__(4404); -const http2 = __nccwpck_require__(5158); -const QuickLRU = __nccwpck_require__(9273); -const delayAsyncDestroy = __nccwpck_require__(9237); - -const kCurrentStreamCount = Symbol('currentStreamCount'); -const kRequest = Symbol('request'); -const kOriginSet = Symbol('cachedOriginSet'); -const kGracefullyClosing = Symbol('gracefullyClosing'); -const kLength = Symbol('length'); - -const nameKeys = [ - // Not an Agent option actually - 'createConnection', - - // `http2.connect()` options - 'maxDeflateDynamicTableSize', - 'maxSettings', - 'maxSessionMemory', - 'maxHeaderListPairs', - 'maxOutstandingPings', - 'maxReservedRemoteStreams', - 'maxSendHeaderBlockLength', - 'paddingStrategy', - 'peerMaxConcurrentStreams', - 'settings', + get connection() { + return this.socket; + } - // `tls.connect()` source options - 'family', - 'localAddress', - 'rejectUnauthorized', + set connection(value) { + this.socket = value; + } - // `tls.connect()` secure context options - 'pskCallback', - 'minDHSize', + _destroy(error, callback) { + if (!this.readableEnded) { + this.aborted = true; + } - // `tls.connect()` destination options - // - `servername` is automatically validated, skip it - // - `host` and `port` just describe the destination server, - 'path', - 'socket', + // See https://github.com/nodejs/node/issues/35303 + callback(); - // `tls.createSecureContext()` options - 'ca', - 'cert', - 'sigalgs', - 'ciphers', - 'clientCertEngine', - 'crl', - 'dhparam', - 'ecdhCurve', - 'honorCipherOrder', - 'key', - 'privateKeyEngine', - 'privateKeyIdentifier', - 'maxVersion', - 'minVersion', - 'pfx', - 'secureOptions', - 'secureProtocol', - 'sessionIdContext', - 'ticketKeys' -]; + this.req._request.destroy(error); + } -const getSortedIndex = (array, value, compare) => { - let low = 0; - let high = array.length; + setTimeout(ms, callback) { + this.req.setTimeout(ms, callback); + return this; + } - while (low < high) { - const mid = (low + high) >>> 1; + _dump() { + if (!this._dumped) { + this._dumped = true; - if (compare(array[mid], value)) { - low = mid + 1; - } else { - high = mid; + this.removeAllListeners('data'); + this.resume(); } } - return low; -}; - -const compareSessions = (a, b) => a.remoteSettings.maxConcurrentStreams > b.remoteSettings.maxConcurrentStreams; + _read() { + if (this.req) { + this.req._request.resume(); + } + } +} -// See https://tools.ietf.org/html/rfc8336 -const closeCoveredSessions = (where, session) => { - // Clients SHOULD NOT emit new requests on any connection whose Origin - // Set is a proper subset of another connection's Origin Set, and they - // SHOULD close it once all outstanding requests are satisfied. - for (let index = 0; index < where.length; index++) { - const coveredSession = where[index]; +module.exports = IncomingMessage; - if ( - // Unfortunately `.every()` returns true for an empty array - coveredSession[kOriginSet].length > 0 - // The set is a proper subset when its length is less than the other set. - && coveredSession[kOriginSet].length < session[kOriginSet].length +/***/ }), - // And the other set includes all elements of the subset. - && coveredSession[kOriginSet].every(origin => session[kOriginSet].includes(origin)) +/***/ 4956: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Makes sure that the session can handle all requests from the covered session. - && (coveredSession[kCurrentStreamCount] + session[kCurrentStreamCount]) <= session.remoteSettings.maxConcurrentStreams - ) { - // This allows pending requests to finish and prevents making new requests. - gracefullyClose(coveredSession); - } - } -}; -// This is basically inverted `closeCoveredSessions(...)`. -const closeSessionIfCovered = (where, coveredSession) => { - for (let index = 0; index < where.length; index++) { - const session = where[index]; +const http2 = __nccwpck_require__(5675); +const { + Agent, + globalAgent +} = __nccwpck_require__(685); +const ClientRequest = __nccwpck_require__(7605); +const IncomingMessage = __nccwpck_require__(2156); +const auto = __nccwpck_require__(9213); +const { + HttpOverHttp2, + HttpsOverHttp2 +} = __nccwpck_require__(9126); +const Http2OverHttp2 = __nccwpck_require__(3747); +const { + Http2OverHttp, + Http2OverHttps +} = __nccwpck_require__(278); +const validateHeaderName = __nccwpck_require__(1212); +const validateHeaderValue = __nccwpck_require__(6462); - if ( - coveredSession[kOriginSet].length > 0 - && coveredSession[kOriginSet].length < session[kOriginSet].length - && coveredSession[kOriginSet].every(origin => session[kOriginSet].includes(origin)) - && (coveredSession[kCurrentStreamCount] + session[kCurrentStreamCount]) <= session.remoteSettings.maxConcurrentStreams - ) { - gracefullyClose(coveredSession); +const request = (url, options, callback) => new ClientRequest(url, options, callback); - return true; - } - } +const get = (url, options, callback) => { + // eslint-disable-next-line unicorn/prevent-abbreviations + const req = new ClientRequest(url, options, callback); + req.end(); - return false; + return req; }; -const gracefullyClose = session => { - session[kGracefullyClosing] = true; - - if (session[kCurrentStreamCount] === 0) { - session.close(); - } +module.exports = { + ...http2, + ClientRequest, + IncomingMessage, + Agent, + globalAgent, + request, + get, + auto, + proxies: { + HttpOverHttp2, + HttpsOverHttp2, + Http2OverHttp2, + Http2OverHttp, + Http2OverHttps + }, + validateHeaderName, + validateHeaderValue }; -class Agent extends EventEmitter { - constructor({timeout = 0, maxSessions = Number.POSITIVE_INFINITY, maxEmptySessions = 10, maxCachedTlsSessions = 100} = {}) { - super(); - // SESSIONS[NORMALIZED_OPTIONS] = []; - this.sessions = {}; +/***/ }), - // The queue for creating new sessions. It looks like this: - // QUEUE[NORMALIZED_OPTIONS][NORMALIZED_ORIGIN] = ENTRY_FUNCTION - // - // It's faster when there are many origins. If there's only one, then QUEUE[`${options}:${origin}`] is faster. - // I guess object creation / deletion is causing the slowdown. - // - // The entry function has `listeners`, `completed` and `destroyed` properties. - // `listeners` is an array of objects containing `resolve` and `reject` functions. - // `completed` is a boolean. It's set to true after ENTRY_FUNCTION is executed. - // `destroyed` is a boolean. If it's set to true, the session will be destroyed if hasn't connected yet. - this.queue = {}; +/***/ 2037: +/***/ ((module) => { - // Each session will use this timeout value. - this.timeout = timeout; - // Max sessions in total - this.maxSessions = maxSessions; - // Max empty sessions in total - this.maxEmptySessions = maxEmptySessions; +module.exports = self => { + const {username, password} = self.proxyOptions.url; - this._emptySessionCount = 0; - this._sessionCount = 0; + if (username || password) { + const data = `${username}:${password}`; + const authorization = `Basic ${Buffer.from(data).toString('base64')}`; - // We don't support push streams by default. - this.settings = { - enablePush: false, - initialWindowSize: 1024 * 1024 * 32 // 32MB, see https://github.com/nodejs/node/issues/38426 + return { + 'proxy-authorization': authorization, + authorization }; - - // Reusing TLS sessions increases performance. - this.tlsSessionCache = new QuickLRU({maxSize: maxCachedTlsSessions}); } - get protocol() { - return 'https:'; - } + return {}; +}; - normalizeOptions(options) { - let normalized = ''; - for (let index = 0; index < nameKeys.length; index++) { - const key = nameKeys[index]; +/***/ }), - normalized += ':'; +/***/ 9126: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (options && options[key] !== undefined) { - normalized += options[key]; - } - } - return normalized; - } +const tls = __nccwpck_require__(4756); +const http = __nccwpck_require__(8611); +const https = __nccwpck_require__(5692); +const JSStreamSocket = __nccwpck_require__(5056); +const {globalAgent} = __nccwpck_require__(685); +const UnexpectedStatusCodeError = __nccwpck_require__(5930); +const initialize = __nccwpck_require__(4833); +const getAuthorizationHeaders = __nccwpck_require__(2037); - _processQueue() { - if (this._sessionCount >= this.maxSessions) { - this.closeEmptySessions(this.maxSessions - this._sessionCount + 1); - return; - } +const createConnection = (self, options, callback) => { + (async () => { + try { + const {proxyOptions} = self; + const {url, headers, raw} = proxyOptions; - // eslint-disable-next-line guard-for-in - for (const normalizedOptions in this.queue) { - // eslint-disable-next-line guard-for-in - for (const normalizedOrigin in this.queue[normalizedOptions]) { - const item = this.queue[normalizedOptions][normalizedOrigin]; + const stream = await globalAgent.request(url, proxyOptions, { + ...getAuthorizationHeaders(self), + ...headers, + ':method': 'CONNECT', + ':authority': `${options.host}:${options.port}` + }); - // The entry function can be run only once. - if (!item.completed) { - item.completed = true; + stream.once('error', callback); + stream.once('response', headers => { + const statusCode = headers[':status']; - item(); + if (statusCode !== 200) { + callback(new UnexpectedStatusCodeError(statusCode, '')); + return; } - } - } - } - _isBetterSession(thisStreamCount, thatStreamCount) { - return thisStreamCount > thatStreamCount; - } + const encrypted = self instanceof https.Agent; - _accept(session, listeners, normalizedOrigin, options) { - let index = 0; + if (raw && encrypted) { + options.socket = stream; + const secureStream = tls.connect(options); - while (index < listeners.length && session[kCurrentStreamCount] < session.remoteSettings.maxConcurrentStreams) { - // We assume `resolve(...)` calls `request(...)` *directly*, - // otherwise the session will get overloaded. - listeners[index].resolve(session); + secureStream.once('close', () => { + stream.destroy(); + }); - index++; - } + callback(null, secureStream); + return; + } - listeners.splice(0, index); + const socket = new JSStreamSocket(stream); + socket.encrypted = false; + socket._handle.getpeername = out => { + out.family = undefined; + out.address = undefined; + out.port = undefined; + }; - if (listeners.length > 0) { - this.getSession(normalizedOrigin, options, listeners); - listeners.length = 0; + callback(null, socket); + }); + } catch (error) { + callback(error); } - } + })(); +}; - getSession(origin, options, listeners) { - return new Promise((resolve, reject) => { - if (Array.isArray(listeners) && listeners.length > 0) { - listeners = [...listeners]; +class HttpOverHttp2 extends http.Agent { + constructor(options) { + super(options); - // Resolve the current promise ASAP, we're just moving the listeners. - // They will be executed at a different time. - resolve(); - } else { - listeners = [{resolve, reject}]; - } + initialize(this, options.proxyOptions); + } - try { - // Parse origin - if (typeof origin === 'string') { - origin = new URL(origin); - } else if (!(origin instanceof URL)) { - throw new TypeError('The `origin` argument needs to be a string or an URL object'); - } + createConnection(options, callback) { + createConnection(this, options, callback); + } +} - if (options) { - // Validate servername - const {servername} = options; - const {hostname} = origin; - if (servername && hostname !== servername) { - throw new Error(`Origin ${hostname} differs from servername ${servername}`); - } - } - } catch (error) { - for (let index = 0; index < listeners.length; index++) { - listeners[index].reject(error); - } +class HttpsOverHttp2 extends https.Agent { + constructor(options) { + super(options); - return; - } + initialize(this, options.proxyOptions); + } - const normalizedOptions = this.normalizeOptions(options); - const normalizedOrigin = origin.origin; + createConnection(options, callback) { + createConnection(this, options, callback); + } +} - if (normalizedOptions in this.sessions) { - const sessions = this.sessions[normalizedOptions]; +module.exports = { + HttpOverHttp2, + HttpsOverHttp2 +}; - let maxConcurrentStreams = -1; - let currentStreamsCount = -1; - let optimalSession; - // We could just do this.sessions[normalizedOptions].find(...) but that isn't optimal. - // Additionally, we are looking for session which has biggest current pending streams count. - // - // |------------| |------------| |------------| |------------| - // | Session: A | | Session: B | | Session: C | | Session: D | - // | Pending: 5 |-| Pending: 8 |-| Pending: 9 |-| Pending: 4 | - // | Max: 10 | | Max: 10 | | Max: 9 | | Max: 5 | - // |------------| |------------| |------------| |------------| - // ^ - // | - // pick this one -- - // - for (let index = 0; index < sessions.length; index++) { - const session = sessions[index]; +/***/ }), - const sessionMaxConcurrentStreams = session.remoteSettings.maxConcurrentStreams; +/***/ 278: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (sessionMaxConcurrentStreams < maxConcurrentStreams) { - break; - } - if (!session[kOriginSet].includes(normalizedOrigin)) { - continue; - } +const http = __nccwpck_require__(8611); +const https = __nccwpck_require__(5692); +const Http2OverHttpX = __nccwpck_require__(861); +const getAuthorizationHeaders = __nccwpck_require__(2037); - const sessionCurrentStreamsCount = session[kCurrentStreamCount]; +const getStream = request => new Promise((resolve, reject) => { + const onConnect = (response, socket, head) => { + socket.unshift(head); - if ( - sessionCurrentStreamsCount >= sessionMaxConcurrentStreams - || session[kGracefullyClosing] - // Unfortunately the `close` event isn't called immediately, - // so `session.destroyed` is `true`, but `session.closed` is `false`. - || session.destroyed - ) { - continue; - } + request.off('error', reject); + resolve([socket, response.statusCode, response.statusMessage]); + }; - // We only need set this once. - if (!optimalSession) { - maxConcurrentStreams = sessionMaxConcurrentStreams; - } + request.once('error', reject); + request.once('connect', onConnect); +}); - // Either get the session which has biggest current stream count or the lowest. - if (this._isBetterSession(sessionCurrentStreamsCount, currentStreamsCount)) { - optimalSession = session; - currentStreamsCount = sessionCurrentStreamsCount; - } - } +class Http2OverHttp extends Http2OverHttpX { + async _getProxyStream(authority) { + const {proxyOptions} = this; + const {url, headers} = this.proxyOptions; - if (optimalSession) { - this._accept(optimalSession, listeners, normalizedOrigin, options); - return; - } - } + const network = url.protocol === 'https:' ? https : http; - if (normalizedOptions in this.queue) { - if (normalizedOrigin in this.queue[normalizedOptions]) { - // There's already an item in the queue, just attach ourselves to it. - this.queue[normalizedOptions][normalizedOrigin].listeners.push(...listeners); - return; - } - } else { - this.queue[normalizedOptions] = { - [kLength]: 0 - }; - } + // `new URL('https://localhost/httpbin.org:443')` results in + // a `/httpbin.org:443` path, which has an invalid leading slash. + const request = network.request({ + ...proxyOptions, + hostname: url.hostname, + port: url.port, + path: authority, + headers: { + ...getAuthorizationHeaders(this), + ...headers, + host: authority + }, + method: 'CONNECT' + }).end(); - // The entry must be removed from the queue IMMEDIATELY when: - // 1. the session connects successfully, - // 2. an error occurs. - const removeFromQueue = () => { - // Our entry can be replaced. We cannot remove the new one. - if (normalizedOptions in this.queue && this.queue[normalizedOptions][normalizedOrigin] === entry) { - delete this.queue[normalizedOptions][normalizedOrigin]; + return getStream(request); + } +} - if (--this.queue[normalizedOptions][kLength] === 0) { - delete this.queue[normalizedOptions]; - } - } - }; +module.exports = { + Http2OverHttp, + Http2OverHttps: Http2OverHttp +}; - // The main logic is here - const entry = async () => { - this._sessionCount++; - const name = `${normalizedOrigin}:${normalizedOptions}`; - let receivedSettings = false; - let socket; +/***/ }), - try { - const computedOptions = {...options}; +/***/ 3747: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (computedOptions.settings === undefined) { - computedOptions.settings = this.settings; - } - if (computedOptions.session === undefined) { - computedOptions.session = this.tlsSessionCache.get(name); - } +const {globalAgent} = __nccwpck_require__(685); +const Http2OverHttpX = __nccwpck_require__(861); +const getAuthorizationHeaders = __nccwpck_require__(2037); - const createConnection = computedOptions.createConnection || this.createConnection; +const getStatusCode = stream => new Promise((resolve, reject) => { + stream.once('error', reject); + stream.once('response', headers => { + stream.off('error', reject); + resolve(headers[':status']); + }); +}); - // A hacky workaround to enable async `createConnection` - socket = await createConnection.call(this, origin, computedOptions); - computedOptions.createConnection = () => socket; +class Http2OverHttp2 extends Http2OverHttpX { + async _getProxyStream(authority) { + const {proxyOptions} = this; - const session = http2.connect(origin, computedOptions); - session[kCurrentStreamCount] = 0; - session[kGracefullyClosing] = false; - - // Node.js return https://false:443 instead of https://1.1.1.1:443 - const getOriginSet = () => { - const {socket} = session; + const headers = { + ...getAuthorizationHeaders(this), + ...proxyOptions.headers, + ':method': 'CONNECT', + ':authority': authority + }; - let originSet; - if (socket.servername === false) { - socket.servername = socket.remoteAddress; - originSet = session.originSet; - socket.servername = false; - } else { - originSet = session.originSet; - } + const stream = await globalAgent.request(proxyOptions.url, proxyOptions, headers); + const statusCode = await getStatusCode(stream); - return originSet; - }; + return [stream, statusCode, '']; + } +} - const isFree = () => session[kCurrentStreamCount] < session.remoteSettings.maxConcurrentStreams; +module.exports = Http2OverHttp2; - session.socket.once('session', tlsSession => { - this.tlsSessionCache.set(name, tlsSession); - }); - session.once('error', error => { - // Listeners are empty when the session successfully connected. - for (let index = 0; index < listeners.length; index++) { - listeners[index].reject(error); - } +/***/ }), - // The connection got broken, purge the cache. - this.tlsSessionCache.delete(name); - }); +/***/ 861: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - session.setTimeout(this.timeout, () => { - // Terminates all streams owned by this session. - session.destroy(); - }); - session.once('close', () => { - this._sessionCount--; +const {Agent} = __nccwpck_require__(685); +const JSStreamSocket = __nccwpck_require__(5056); +const UnexpectedStatusCodeError = __nccwpck_require__(5930); +const initialize = __nccwpck_require__(4833); - if (receivedSettings) { - // Assumes session `close` is emitted after request `close` - this._emptySessionCount--; +class Http2OverHttpX extends Agent { + constructor(options) { + super(options); - // This cannot be moved to the stream logic, - // because there may be a session that hadn't made a single request. - const where = this.sessions[normalizedOptions]; + initialize(this, options.proxyOptions); + } - if (where.length === 1) { - delete this.sessions[normalizedOptions]; - } else { - where.splice(where.indexOf(session), 1); - } - } else { - // Broken connection - removeFromQueue(); + async createConnection(origin, options) { + const authority = `${origin.hostname}:${origin.port || 443}`; - const error = new Error('Session closed without receiving a SETTINGS frame'); - error.code = 'HTTP2WRAPPER_NOSETTINGS'; + const [stream, statusCode, statusMessage] = await this._getProxyStream(authority); + if (statusCode !== 200) { + throw new UnexpectedStatusCodeError(statusCode, statusMessage); + } - for (let index = 0; index < listeners.length; index++) { - listeners[index].reject(error); - } - } + if (this.proxyOptions.raw) { + options.socket = stream; + } else { + const socket = new JSStreamSocket(stream); + socket.encrypted = false; + socket._handle.getpeername = out => { + out.family = undefined; + out.address = undefined; + out.port = undefined; + }; - // There may be another session awaiting. - this._processQueue(); - }); + return socket; + } - // Iterates over the queue and processes listeners. - const processListeners = () => { - const queue = this.queue[normalizedOptions]; - if (!queue) { - return; - } + return super.createConnection(origin, options); + } +} - const originSet = session[kOriginSet]; +module.exports = Http2OverHttpX; - for (let index = 0; index < originSet.length; index++) { - const origin = originSet[index]; - if (origin in queue) { - const {listeners, completed} = queue[origin]; +/***/ }), - let index = 0; +/***/ 4833: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Prevents session overloading. - while (index < listeners.length && isFree()) { - // We assume `resolve(...)` calls `request(...)` *directly*, - // otherwise the session will get overloaded. - listeners[index].resolve(session); - index++; - } +// See https://github.com/facebook/jest/issues/2549 +// eslint-disable-next-line node/prefer-global/url +const {URL} = __nccwpck_require__(7016); +const checkType = __nccwpck_require__(891); - queue[origin].listeners.splice(0, index); +module.exports = (self, proxyOptions) => { + checkType('proxyOptions', proxyOptions, ['object']); + checkType('proxyOptions.headers', proxyOptions.headers, ['object', 'undefined']); + checkType('proxyOptions.raw', proxyOptions.raw, ['boolean', 'undefined']); + checkType('proxyOptions.url', proxyOptions.url, [URL, 'string']); - if (queue[origin].listeners.length === 0 && !completed) { - delete queue[origin]; + const url = new URL(proxyOptions.url); - if (--queue[kLength] === 0) { - delete this.queue[normalizedOptions]; - break; - } - } + self.proxyOptions = { + raw: true, + ...proxyOptions, + headers: {...proxyOptions.headers}, + url + }; +}; - // We're no longer free, no point in continuing. - if (!isFree()) { - break; - } - } - } - }; - // The Origin Set cannot shrink. No need to check if it suddenly became covered by another one. - session.on('origin', () => { - session[kOriginSet] = getOriginSet() || []; - session[kGracefullyClosing] = false; - closeSessionIfCovered(this.sessions[normalizedOptions], session); +/***/ }), - if (session[kGracefullyClosing] || !isFree()) { - return; - } +/***/ 5930: +/***/ ((module) => { - processListeners(); - if (!isFree()) { - return; - } - // Close covered sessions (if possible). - closeCoveredSessions(this.sessions[normalizedOptions], session); - }); +class UnexpectedStatusCodeError extends Error { + constructor(statusCode, statusMessage = '') { + super(`The proxy server rejected the request with status code ${statusCode} (${statusMessage || 'empty status message'})`); + this.statusCode = statusCode; + this.statusMessage = statusMessage; + } +} - session.once('remoteSettings', () => { - // The Agent could have been destroyed already. - if (entry.destroyed) { - const error = new Error('Agent has been destroyed'); +module.exports = UnexpectedStatusCodeError; - for (let index = 0; index < listeners.length; index++) { - listeners[index].reject(error); - } - session.destroy(); - return; - } +/***/ }), - // See https://github.com/nodejs/node/issues/38426 - if (session.setLocalWindowSize) { - session.setLocalWindowSize(1024 * 1024 * 4); // 4 MB - } +/***/ 2850: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - session[kOriginSet] = getOriginSet() || []; - if (session.socket.encrypted) { - const mainOrigin = session[kOriginSet][0]; - if (mainOrigin !== normalizedOrigin) { - const error = new Error(`Requested origin ${normalizedOrigin} does not match server ${mainOrigin}`); +const {isIP} = __nccwpck_require__(9278); +const assert = __nccwpck_require__(2613); - for (let index = 0; index < listeners.length; index++) { - listeners[index].reject(error); - } +const getHost = host => { + if (host[0] === '[') { + const idx = host.indexOf(']'); - session.destroy(); - return; - } - } + assert(idx !== -1); + return host.slice(1, idx); + } - removeFromQueue(); + const idx = host.indexOf(':'); + if (idx === -1) { + return host; + } - { - const where = this.sessions; + return host.slice(0, idx); +}; - if (normalizedOptions in where) { - const sessions = where[normalizedOptions]; - sessions.splice(getSortedIndex(sessions, session, compareSessions), 0, session); - } else { - where[normalizedOptions] = [session]; - } - } +module.exports = host => { + const servername = getHost(host); - receivedSettings = true; - this._emptySessionCount++; + if (isIP(servername)) { + return ''; + } - this.emit('session', session); - this._accept(session, listeners, normalizedOrigin, options); + return servername; +}; - if (session[kCurrentStreamCount] === 0 && this._emptySessionCount > this.maxEmptySessions) { - this.closeEmptySessions(this._emptySessionCount - this.maxEmptySessions); - } - // `session.remoteSettings.maxConcurrentStreams` might get increased - session.on('remoteSettings', () => { - if (!isFree()) { - return; - } +/***/ }), - processListeners(); +/***/ 891: +/***/ ((module) => { - if (!isFree()) { - return; - } - // In case the Origin Set changes - closeCoveredSessions(this.sessions[normalizedOptions], session); - }); - }); - // Shim `session.request()` in order to catch all streams - session[kRequest] = session.request; - session.request = (headers, streamOptions) => { - if (session[kGracefullyClosing]) { - throw new Error('The session is gracefully closing. No new streams are allowed.'); - } - - const stream = session[kRequest](headers, streamOptions); - - // The process won't exit until the session is closed or all requests are gone. - session.ref(); +const checkType = (name, value, types) => { + const valid = types.some(type => { + const typeofType = typeof type; + if (typeofType === 'string') { + return typeof value === type; + } - if (session[kCurrentStreamCount]++ === 0) { - this._emptySessionCount--; - } + return value instanceof type; + }); - stream.once('close', () => { - if (--session[kCurrentStreamCount] === 0) { - this._emptySessionCount++; - session.unref(); + if (!valid) { + const names = types.map(type => typeof type === 'string' ? type : type.name); - if (this._emptySessionCount > this.maxEmptySessions || session[kGracefullyClosing]) { - session.close(); - return; - } - } + throw new TypeError(`Expected '${name}' to be a type of ${names.join(' or ')}, got ${typeof value}`); + } +}; - if (session.destroyed || session.closed) { - return; - } +module.exports = checkType; - if (isFree() && !closeSessionIfCovered(this.sessions[normalizedOptions], session)) { - closeCoveredSessions(this.sessions[normalizedOptions], session); - processListeners(); - if (session[kCurrentStreamCount] === 0) { - this._processQueue(); - } - } - }); +/***/ }), - return stream; - }; - } catch (error) { - removeFromQueue(); - this._sessionCount--; +/***/ 811: +/***/ ((module) => { - for (let index = 0; index < listeners.length; index++) { - listeners[index].reject(error); - } - } - }; - entry.listeners = listeners; - entry.completed = false; - entry.destroyed = false; - this.queue[normalizedOptions][normalizedOrigin] = entry; - this.queue[normalizedOptions][kLength]++; - this._processQueue(); - }); +module.exports = stream => { + if (stream.listenerCount('error') !== 0) { + return stream; } - request(origin, options, headers, streamOptions) { - return new Promise((resolve, reject) => { - this.getSession(origin, options, [{ - reject, - resolve: session => { - try { - const stream = session.request(headers, streamOptions); + stream.__destroy = stream._destroy; + stream._destroy = (...args) => { + const callback = args.pop(); - // Do not throw before `request(...)` has been awaited - delayAsyncDestroy(stream); + stream.__destroy(...args, async error => { + await Promise.resolve(); + callback(error); + }); + }; - resolve(stream); - } catch (error) { - reject(error); - } - } - }]); + const onError = error => { + // eslint-disable-next-line promise/prefer-await-to-then + Promise.resolve().then(() => { + stream.emit('error', error); }); - } + }; - async createConnection(origin, options) { - return Agent.connect(origin, options); - } + stream.once('error', onError); - static connect(origin, options) { - options.ALPNProtocols = ['h2']; + // eslint-disable-next-line promise/prefer-await-to-then + Promise.resolve().then(() => { + stream.off('error', onError); + }); - const port = origin.port || 443; - const host = origin.hostname; + return stream; +}; - if (typeof options.servername === 'undefined') { - options.servername = host; - } - const socket = tls.connect(port, host, options); +/***/ }), - if (options.socket) { - socket._peername = { - family: undefined, - address: undefined, - port - }; - } +/***/ 9731: +/***/ ((module) => { - return socket; - } - closeEmptySessions(maxCount = Number.POSITIVE_INFINITY) { - let closedCount = 0; +/* istanbul ignore file: https://github.com/nodejs/node/blob/master/lib/internal/errors.js */ - const {sessions} = this; +const makeError = (Base, key, getMessage) => { + module.exports[key] = class NodeError extends Base { + constructor(...args) { + super(typeof getMessage === 'string' ? getMessage : getMessage(args)); + this.name = `${super.name} [${key}]`; + this.code = key; + } + }; +}; - // eslint-disable-next-line guard-for-in - for (const key in sessions) { - const thisSessions = sessions[key]; +makeError(TypeError, 'ERR_INVALID_ARG_TYPE', args => { + const type = args[0].includes('.') ? 'property' : 'argument'; - for (let index = 0; index < thisSessions.length; index++) { - const session = thisSessions[index]; + let valid = args[1]; + const isManyTypes = Array.isArray(valid); - if (session[kCurrentStreamCount] === 0) { - closedCount++; - session.close(); + if (isManyTypes) { + valid = `${valid.slice(0, -1).join(', ')} or ${valid.slice(-1)}`; + } - if (closedCount >= maxCount) { - return closedCount; - } - } - } - } + return `The "${args[0]}" ${type} must be ${isManyTypes ? 'one of' : 'of'} type ${valid}. Received ${typeof args[2]}`; +}); - return closedCount; - } +makeError(TypeError, 'ERR_INVALID_PROTOCOL', args => + `Protocol "${args[0]}" not supported. Expected "${args[1]}"` +); - destroy(reason) { - const {sessions, queue} = this; +makeError(Error, 'ERR_HTTP_HEADERS_SENT', args => + `Cannot ${args[0]} headers after they are sent to the client` +); - // eslint-disable-next-line guard-for-in - for (const key in sessions) { - const thisSessions = sessions[key]; +makeError(TypeError, 'ERR_INVALID_HTTP_TOKEN', args => + `${args[0]} must be a valid HTTP token [${args[1]}]` +); - for (let index = 0; index < thisSessions.length; index++) { - thisSessions[index].destroy(reason); - } - } +makeError(TypeError, 'ERR_HTTP_INVALID_HEADER_VALUE', args => + `Invalid value "${args[0]} for header "${args[1]}"` +); - // eslint-disable-next-line guard-for-in - for (const normalizedOptions in queue) { - const entries = queue[normalizedOptions]; +makeError(TypeError, 'ERR_INVALID_CHAR', args => + `Invalid character in ${args[0]} [${args[1]}]` +); - // eslint-disable-next-line guard-for-in - for (const normalizedOrigin in entries) { - entries[normalizedOrigin].destroyed = true; - } - } +makeError( + Error, + 'ERR_HTTP2_NO_SOCKET_MANIPULATION', + 'HTTP/2 sockets should not be directly manipulated (e.g. read and written)' +); - // New requests should NOT attach to destroyed sessions - this.queue = {}; - this.tlsSessionCache.clear(); - } - get emptySessionCount() { - return this._emptySessionCount; - } +/***/ }), - get pendingSessionCount() { - return this._sessionCount - this._emptySessionCount; - } +/***/ 6365: +/***/ ((module) => { - get sessionCount() { - return this._sessionCount; - } -} -Agent.kCurrentStreamCount = kCurrentStreamCount; -Agent.kGracefullyClosing = kGracefullyClosing; -module.exports = { - Agent, - globalAgent: new Agent() +module.exports = header => { + switch (header) { + case ':method': + case ':scheme': + case ':authority': + case ':path': + return true; + default: + return false; + } }; /***/ }), -/***/ 7167: +/***/ 5056: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// See https://github.com/facebook/jest/issues/2549 -// eslint-disable-next-line node/prefer-global/url -const {URL, urlToHttpOptions} = __nccwpck_require__(7310); -const http = __nccwpck_require__(3685); -const https = __nccwpck_require__(5687); -const resolveALPN = __nccwpck_require__(6624); -const QuickLRU = __nccwpck_require__(9273); -const {Agent, globalAgent} = __nccwpck_require__(9898); -const Http2ClientRequest = __nccwpck_require__(9632); -const calculateServerName = __nccwpck_require__(1982); -const delayAsyncDestroy = __nccwpck_require__(9237); +const stream = __nccwpck_require__(2203); +const tls = __nccwpck_require__(4756); -const cache = new QuickLRU({maxSize: 100}); -const queue = new Map(); +// Really awesome hack. +const JSStreamSocket = (new tls.TLSSocket(new stream.PassThrough()))._handle._parentWrap.constructor; -const installSocket = (agent, socket, options) => { - socket._httpMessage = {shouldKeepAlive: true}; +module.exports = JSStreamSocket; - const onFree = () => { - agent.emit('free', socket, options); - }; - socket.on('free', onFree); +/***/ }), - const onClose = () => { - agent.removeSocket(socket, options); - }; +/***/ 118: +/***/ ((module) => { - socket.on('close', onClose); - const onTimeout = () => { - const {freeSockets} = agent; - for (const sockets of Object.values(freeSockets)) { - if (sockets.includes(socket)) { - socket.destroy(); - return; - } - } - }; - - socket.on('timeout', onTimeout); - - const onRemove = () => { - agent.removeSocket(socket, options); - socket.off('close', onClose); - socket.off('free', onFree); - socket.off('timeout', onTimeout); - socket.off('agentRemove', onRemove); - }; +module.exports = (from, to, events) => { + for (const event of events) { + from.on(event, (...args) => to.emit(event, ...args)); + } +}; - socket.on('agentRemove', onRemove); - agent.emit('free', socket, options); -}; +/***/ }), -const createResolveProtocol = (cache, queue = new Map(), connect = undefined) => { - return async options => { - const name = `${options.host}:${options.port}:${options.ALPNProtocols.sort()}`; +/***/ 7083: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (!cache.has(name)) { - if (queue.has(name)) { - const result = await queue.get(name); - return {alpnProtocol: result.alpnProtocol}; - } - const {path} = options; - options.path = options.socketPath; +const {ERR_HTTP2_NO_SOCKET_MANIPULATION} = __nccwpck_require__(9731); - const resultPromise = resolveALPN(options, connect); - queue.set(name, resultPromise); +/* istanbul ignore file */ +/* https://github.com/nodejs/node/blob/6eec858f34a40ffa489c1ec54bb24da72a28c781/lib/internal/http2/compat.js#L195-L272 */ - try { - const result = await resultPromise; +const proxySocketHandler = { + has(stream, property) { + // Replaced [kSocket] with .socket + const reference = stream.session === undefined ? stream : stream.session.socket; + return (property in stream) || (property in reference); + }, - cache.set(name, result.alpnProtocol); - queue.delete(name); + get(stream, property) { + switch (property) { + case 'on': + case 'once': + case 'end': + case 'emit': + case 'destroy': + return stream[property].bind(stream); + case 'writable': + case 'destroyed': + return stream[property]; + case 'readable': + if (stream.destroyed) { + return false; + } - options.path = path; + return stream.readable; + case 'setTimeout': { + const {session} = stream; + if (session !== undefined) { + return session.setTimeout.bind(session); + } - return result; - } catch (error) { - queue.delete(name); + return stream.setTimeout.bind(stream); + } - options.path = path; + case 'write': + case 'read': + case 'pause': + case 'resume': + throw new ERR_HTTP2_NO_SOCKET_MANIPULATION(); + default: { + // Replaced [kSocket] with .socket + const reference = stream.session === undefined ? stream : stream.session.socket; + const value = reference[property]; - throw error; + return typeof value === 'function' ? value.bind(reference) : value; } } + }, - return {alpnProtocol: cache.get(name)}; - }; -}; - -const defaultResolveProtocol = createResolveProtocol(cache, queue); + getPrototypeOf(stream) { + if (stream.session !== undefined) { + // Replaced [kSocket] with .socket + return Reflect.getPrototypeOf(stream.session.socket); + } -module.exports = async (input, options, callback) => { - if (typeof input === 'string') { - input = urlToHttpOptions(new URL(input)); - } else if (input instanceof URL) { - input = urlToHttpOptions(input); - } else { - input = {...input}; - } + return Reflect.getPrototypeOf(stream); + }, - if (typeof options === 'function' || options === undefined) { - // (options, callback) - callback = options; - options = input; - } else { - // (input, options, callback) - options = Object.assign(input, options); - } + set(stream, property, value) { + switch (property) { + case 'writable': + case 'readable': + case 'destroyed': + case 'on': + case 'once': + case 'end': + case 'emit': + case 'destroy': + stream[property] = value; + return true; + case 'setTimeout': { + const {session} = stream; + if (session === undefined) { + stream.setTimeout = value; + } else { + session.setTimeout = value; + } - options.ALPNProtocols = options.ALPNProtocols || ['h2', 'http/1.1']; + return true; + } - if (!Array.isArray(options.ALPNProtocols) || options.ALPNProtocols.length === 0) { - throw new Error('The `ALPNProtocols` option must be an Array with at least one entry'); + case 'write': + case 'read': + case 'pause': + case 'resume': + throw new ERR_HTTP2_NO_SOCKET_MANIPULATION(); + default: { + // Replaced [kSocket] with .socket + const reference = stream.session === undefined ? stream : stream.session.socket; + reference[property] = value; + return true; + } + } } +}; - options.protocol = options.protocol || 'https:'; - const isHttps = options.protocol === 'https:'; - - options.host = options.hostname || options.host || 'localhost'; - options.session = options.tlsSession; - options.servername = options.servername || calculateServerName((options.headers && options.headers.host) || options.host); - options.port = options.port || (isHttps ? 443 : 80); - options._defaultAgent = isHttps ? https.globalAgent : http.globalAgent; - - const resolveProtocol = options.resolveProtocol || defaultResolveProtocol; - - // Note: We don't support `h2session` here +module.exports = proxySocketHandler; - let {agent} = options; - if (agent !== undefined && agent !== false && agent.constructor.name !== 'Object') { - throw new Error('The `options.agent` can be only an object `http`, `https` or `http2` properties'); - } - if (isHttps) { - options.resolveSocket = true; +/***/ }), - let {socket, alpnProtocol, timeout} = await resolveProtocol(options); +/***/ 1212: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (timeout) { - if (socket) { - socket.destroy(); - } - const error = new Error(`Timed out resolving ALPN: ${options.timeout} ms`); - error.code = 'ETIMEDOUT'; - error.ms = options.timeout; +const {ERR_INVALID_HTTP_TOKEN} = __nccwpck_require__(9731); +const isRequestPseudoHeader = __nccwpck_require__(6365); - throw error; - } +const isValidHttpToken = /^[\^`\-\w!#$%&*+.|~]+$/; - // We can't accept custom `createConnection` because the API is different for HTTP/2 - if (socket && options.createConnection) { - socket.destroy(); - socket = undefined; - } +module.exports = name => { + if (typeof name !== 'string' || (!isValidHttpToken.test(name) && !isRequestPseudoHeader(name))) { + throw new ERR_INVALID_HTTP_TOKEN('Header name', name); + } +}; - delete options.resolveSocket; - const isHttp2 = alpnProtocol === 'h2'; +/***/ }), - if (agent) { - agent = isHttp2 ? agent.http2 : agent.https; - options.agent = agent; - } +/***/ 6462: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (agent === undefined) { - agent = isHttp2 ? globalAgent : https.globalAgent; - } - if (socket) { - if (agent === false) { - socket.destroy(); - } else { - const defaultCreateConnection = (isHttp2 ? Agent : https.Agent).prototype.createConnection; +const { + ERR_HTTP_INVALID_HEADER_VALUE, + ERR_INVALID_CHAR +} = __nccwpck_require__(9731); - if (agent.createConnection === defaultCreateConnection) { - if (isHttp2) { - options._reuseSocket = socket; - } else { - installSocket(agent, socket, options); - } - } else { - socket.destroy(); - } - } - } +const isInvalidHeaderValue = /[^\t\u0020-\u007E\u0080-\u00FF]/; - if (isHttp2) { - return delayAsyncDestroy(new Http2ClientRequest(options, callback)); - } - } else if (agent) { - options.agent = agent.http; +module.exports = (name, value) => { + if (typeof value === 'undefined') { + throw new ERR_HTTP_INVALID_HEADER_VALUE(value, name); } - return delayAsyncDestroy(http.request(options, callback)); + if (isInvalidHeaderValue.test(value)) { + throw new ERR_INVALID_CHAR('header content', name); + } }; -module.exports.protocolCache = cache; -module.exports.resolveProtocol = defaultResolveProtocol; -module.exports.createResolveProtocol = createResolveProtocol; - /***/ }), -/***/ 9632: +/***/ 9598: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +try { + var util = __nccwpck_require__(9023); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = __nccwpck_require__(6589); +} -// See https://github.com/facebook/jest/issues/2549 -// eslint-disable-next-line node/prefer-global/url -const {URL, urlToHttpOptions} = __nccwpck_require__(7310); -const http2 = __nccwpck_require__(5158); -const {Writable} = __nccwpck_require__(2781); -const {Agent, globalAgent} = __nccwpck_require__(9898); -const IncomingMessage = __nccwpck_require__(2575); -const proxyEvents = __nccwpck_require__(1818); -const { - ERR_INVALID_ARG_TYPE, - ERR_INVALID_PROTOCOL, - ERR_HTTP_HEADERS_SENT -} = __nccwpck_require__(7087); -const validateHeaderName = __nccwpck_require__(4592); -const validateHeaderValue = __nccwpck_require__(3549); -const proxySocketHandler = __nccwpck_require__(9404); -const { - HTTP2_HEADER_STATUS, - HTTP2_HEADER_METHOD, - HTTP2_HEADER_PATH, - HTTP2_HEADER_AUTHORITY, - HTTP2_METHOD_CONNECT -} = http2.constants; +/***/ }), -const kHeaders = Symbol('headers'); -const kOrigin = Symbol('origin'); -const kSession = Symbol('session'); -const kOptions = Symbol('options'); -const kFlushedHeaders = Symbol('flushedHeaders'); -const kJobs = Symbol('jobs'); -const kPendingAgentPromise = Symbol('pendingAgentPromise'); +/***/ 6589: +/***/ ((module) => { -class ClientRequest extends Writable { - constructor(input, options, callback) { - super({ - autoDestroy: false, - emitClose: false - }); +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.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 { + // old school shim for old browsers + module.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 + } + } +} - if (typeof input === 'string') { - input = urlToHttpOptions(new URL(input)); - } else if (input instanceof URL) { - input = urlToHttpOptions(input); - } else { - input = {...input}; - } - if (typeof options === 'function' || options === undefined) { - // (options, callback) - callback = options; - options = input; - } else { - // (input, options, callback) - options = Object.assign(input, options); - } +/***/ }), - if (options.h2session) { - this[kSession] = options.h2session; +/***/ 2513: +/***/ ((module) => { - if (this[kSession].destroyed) { - throw new Error('The session has been closed already'); - } +var toString = {}.toString; - this.protocol = this[kSession].socket.encrypted ? 'https:' : 'http:'; - } else if (options.agent === false) { - this.agent = new Agent({maxEmptySessions: 0}); - } else if (typeof options.agent === 'undefined' || options.agent === null) { - this.agent = globalAgent; - } else if (typeof options.agent.request === 'function') { - this.agent = options.agent; - } else { - throw new ERR_INVALID_ARG_TYPE('options.agent', ['http2wrapper.Agent-like Object', 'undefined', 'false'], options.agent); - } +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; - if (this.agent) { - this.protocol = this.agent.protocol; - } - if (options.protocol && options.protocol !== this.protocol) { - throw new ERR_INVALID_PROTOCOL(options.protocol, this.protocol); - } +/***/ }), - if (!options.port) { - options.port = options.defaultPort || (this.agent && this.agent.defaultPort) || 443; - } +/***/ 5563: +/***/ ((__unused_webpack_module, exports) => { - options.host = options.hostname || options.host || 'localhost'; +//TODO: handle reviver/dehydrate function like normal +//and handle indentation, like normal. +//if anyone needs this... please send pull request. - // Unused - delete options.hostname; +exports.stringify = function stringify (o) { + if('undefined' == typeof o) return o - const {timeout} = options; - options.timeout = undefined; + if(o && Buffer.isBuffer(o)) + return JSON.stringify(':base64:' + o.toString('base64')) - this[kHeaders] = Object.create(null); - this[kJobs] = []; + if(o && o.toJSON) + o = o.toJSON() - this[kPendingAgentPromise] = undefined; + if(o && 'object' === typeof o) { + var s = '' + var array = Array.isArray(o) + s = array ? '[' : '{' + var first = true - this.socket = null; - this.connection = null; + for(var k in o) { + var ignore = 'function' == typeof o[k] || (!array && 'undefined' === typeof o[k]) + if(Object.hasOwnProperty.call(o, k) && !ignore) { + if(!first) + s += ',' + first = false + if (array) { + if(o[k] == undefined) + s += 'null' + else + s += stringify(o[k]) + } else if (o[k] !== void(0)) { + s += stringify(k) + ':' + stringify(o[k]) + } + } + } - this.method = options.method || 'GET'; + s += array ? ']' : '}' - if (!(this.method === 'CONNECT' && (options.path === '/' || options.path === undefined))) { - this.path = options.path; - } + return s + } else if ('string' === typeof o) { + return JSON.stringify(/^:/.test(o) ? ':' + o : o) + } else if ('undefined' === typeof o) { + return 'null'; + } else + return JSON.stringify(o) +} - this.res = null; - this.aborted = false; - this.reusedSocket = false; +exports.parse = function (s) { + return JSON.parse(s, function (key, value) { + if('string' === typeof value) { + if(/^:base64:/.test(value)) + return Buffer.from(value.substring(8), 'base64') + else + return /^:/.test(value) ? value.substring(1) : value + } + return value + }) +} - const {headers} = options; - if (headers) { - // eslint-disable-next-line guard-for-in - for (const header in headers) { - this.setHeader(header, headers[header]); - } - } - if (options.auth && !('authorization' in this[kHeaders])) { - this[kHeaders].authorization = 'Basic ' + Buffer.from(options.auth).toString('base64'); - } +/***/ }), - options.session = options.tlsSession; - options.path = options.socketPath; +/***/ 2064: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - this[kOptions] = options; +let _fs +try { + _fs = __nccwpck_require__(5744) +} catch (_) { + _fs = __nccwpck_require__(9896) +} +const universalify = __nccwpck_require__(5077) +const { stringify, stripBom } = __nccwpck_require__(9449) - // Clients that generate HTTP/2 requests directly SHOULD use the :authority pseudo-header field instead of the Host header field. - this[kOrigin] = new URL(`${this.protocol}//${options.servername || options.host}:${options.port}`); +async function _readFile (file, options = {}) { + if (typeof options === 'string') { + options = { encoding: options } + } - // A socket is being reused - const reuseSocket = options._reuseSocket; - if (reuseSocket) { - options.createConnection = (...args) => { - if (reuseSocket.destroyed) { - return this.agent.createConnection(...args); - } + const fs = options.fs || _fs - return reuseSocket; - }; + const shouldThrow = 'throws' in options ? options.throws : true - // eslint-disable-next-line promise/prefer-await-to-then - this.agent.getSession(this[kOrigin], this[kOptions]).catch(() => {}); - } + let data = await universalify.fromCallback(fs.readFile)(file, options) - if (timeout) { - this.setTimeout(timeout); - } + data = stripBom(data) - if (callback) { - this.once('response', callback); - } + let obj + try { + obj = JSON.parse(data, options ? options.reviver : null) + } catch (err) { + if (shouldThrow) { + err.message = `${file}: ${err.message}` + throw err + } else { + return null + } + } - this[kFlushedHeaders] = false; - } + return obj +} - get method() { - return this[kHeaders][HTTP2_HEADER_METHOD]; - } +const readFile = universalify.fromPromise(_readFile) - set method(value) { - if (value) { - this[kHeaders][HTTP2_HEADER_METHOD] = value.toUpperCase(); - } - } +function readFileSync (file, options = {}) { + if (typeof options === 'string') { + options = { encoding: options } + } - get path() { - const header = this.method === 'CONNECT' ? HTTP2_HEADER_AUTHORITY : HTTP2_HEADER_PATH; + const fs = options.fs || _fs - return this[kHeaders][header]; - } + const shouldThrow = 'throws' in options ? options.throws : true - set path(value) { - if (value) { - const header = this.method === 'CONNECT' ? HTTP2_HEADER_AUTHORITY : HTTP2_HEADER_PATH; + try { + let content = fs.readFileSync(file, options) + content = stripBom(content) + return JSON.parse(content, options.reviver) + } catch (err) { + if (shouldThrow) { + err.message = `${file}: ${err.message}` + throw err + } else { + return null + } + } +} - this[kHeaders][header] = value; - } - } +async function _writeFile (file, obj, options = {}) { + const fs = options.fs || _fs - get host() { - return this[kOrigin].hostname; - } + const str = stringify(obj, options) - set host(_value) { - // Do nothing as this is read only. - } + await universalify.fromCallback(fs.writeFile)(file, str, options) +} - get _mustNotHaveABody() { - return this.method === 'GET' || this.method === 'HEAD' || this.method === 'DELETE'; - } +const writeFile = universalify.fromPromise(_writeFile) - _write(chunk, encoding, callback) { - // https://github.com/nodejs/node/blob/654df09ae0c5e17d1b52a900a545f0664d8c7627/lib/internal/http2/util.js#L148-L156 - if (this._mustNotHaveABody) { - callback(new Error('The GET, HEAD and DELETE methods must NOT have a body')); - /* istanbul ignore next: Node.js 12 throws directly */ - return; - } +function writeFileSync (file, obj, options = {}) { + const fs = options.fs || _fs - this.flushHeaders(); + const str = stringify(obj, options) + // not sure if fs.writeFileSync returns anything, but just in case + return fs.writeFileSync(file, str, options) +} - const callWrite = () => this._request.write(chunk, encoding, callback); - if (this._request) { - callWrite(); - } else { - this[kJobs].push(callWrite); - } - } +const jsonfile = { + readFile, + readFileSync, + writeFile, + writeFileSync +} - _final(callback) { - this.flushHeaders(); +module.exports = jsonfile - const callEnd = () => { - // For GET, HEAD and DELETE and CONNECT - if (this._mustNotHaveABody || this.method === 'CONNECT') { - callback(); - return; - } - this._request.end(callback); - }; +/***/ }), - if (this._request) { - callEnd(); - } else { - this[kJobs].push(callEnd); - } - } +/***/ 9449: +/***/ ((module) => { - abort() { - if (this.res && this.res.complete) { - return; - } +function stringify (obj, { EOL = '\n', finalEOL = true, replacer = null, spaces } = {}) { + const EOF = finalEOL ? EOL : '' + const str = JSON.stringify(obj, replacer, spaces) - if (!this.aborted) { - process.nextTick(() => this.emit('abort')); - } + return str.replace(/\n/g, EOL) + EOF +} - this.aborted = true; +function stripBom (content) { + // we do this because JSON.parse would convert it to a utf8 string if encoding wasn't specified + if (Buffer.isBuffer(content)) content = content.toString('utf8') + return content.replace(/^\uFEFF/, '') +} - this.destroy(); - } +module.exports = { stringify, stripBom } - async _destroy(error, callback) { - if (this.res) { - this.res._dump(); - } - if (this._request) { - this._request.destroy(); - } else { - process.nextTick(() => { - this.emit('close'); - }); - } +/***/ }), - try { - await this[kPendingAgentPromise]; - } catch (internalError) { - if (this.aborted) { - error = internalError; - } - } +/***/ 6018: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - callback(error); + + +const EventEmitter = __nccwpck_require__(4434); +const JSONB = __nccwpck_require__(5563); + +const loadStore = options => { + const adapters = { + redis: '@keyv/redis', + rediss: '@keyv/redis', + mongodb: '@keyv/mongo', + mongo: '@keyv/mongo', + sqlite: '@keyv/sqlite', + postgresql: '@keyv/postgres', + postgres: '@keyv/postgres', + mysql: '@keyv/mysql', + etcd: '@keyv/etcd', + offline: '@keyv/offline', + tiered: '@keyv/tiered', + }; + if (options.adapter || options.uri) { + const adapter = options.adapter || /^[^:+]*/.exec(options.uri)[0]; + return new (__WEBPACK_EXTERNAL_createRequire(import.meta.url)(adapters[adapter]))(options); } - async flushHeaders() { - if (this[kFlushedHeaders] || this.destroyed) { - return; - } + return new Map(); +}; - this[kFlushedHeaders] = true; +const iterableAdapters = [ + 'sqlite', + 'postgres', + 'mysql', + 'mongo', + 'redis', + 'tiered', +]; - const isConnectMethod = this.method === HTTP2_METHOD_CONNECT; +class Keyv extends EventEmitter { + constructor(uri, {emitErrors = true, ...options} = {}) { + super(); + this.opts = { + namespace: 'keyv', + serialize: JSONB.stringify, + deserialize: JSONB.parse, + ...((typeof uri === 'string') ? {uri} : uri), + ...options, + }; - // The real magic is here - const onStream = stream => { - this._request = stream; + if (!this.opts.store) { + const adapterOptions = {...this.opts}; + this.opts.store = loadStore(adapterOptions); + } - if (this.destroyed) { - stream.destroy(); - return; - } + if (this.opts.compression) { + const compression = this.opts.compression; + this.opts.serialize = compression.serialize.bind(compression); + this.opts.deserialize = compression.deserialize.bind(compression); + } - // Forwards `timeout`, `continue`, `close` and `error` events to this instance. - if (!isConnectMethod) { - // TODO: Should we proxy `close` here? - proxyEvents(stream, this, ['timeout', 'continue']); - } + if (typeof this.opts.store.on === 'function' && emitErrors) { + this.opts.store.on('error', error => this.emit('error', error)); + } - stream.once('error', error => { - this.destroy(error); - }); + this.opts.store.namespace = this.opts.namespace; - stream.once('aborted', () => { - const {res} = this; - if (res) { - res.aborted = true; - res.emit('aborted'); - res.destroy(); - } else { - this.destroy(new Error('The server aborted the HTTP/2 stream')); + const generateIterator = iterator => async function * () { + for await (const [key, raw] of typeof iterator === 'function' + ? iterator(this.opts.store.namespace) + : iterator) { + const data = await this.opts.deserialize(raw); + if (this.opts.store.namespace && !key.includes(this.opts.store.namespace)) { + continue; } - }); - const onResponse = (headers, flags, rawHeaders) => { - // If we were to emit raw request stream, it would be as fast as the native approach. - // Note that wrapping the raw stream in a Proxy instance won't improve the performance (already tested it). - const response = new IncomingMessage(this.socket, stream.readableHighWaterMark); - this.res = response; + if (typeof data.expires === 'number' && Date.now() > data.expires) { + this.delete(key); + continue; + } - // Undocumented, but it is used by `cacheable-request` - response.url = `${this[kOrigin].origin}${this.path}`; + yield [this._getKeyUnprefix(key), data.value]; + } + }; - response.req = this; - response.statusCode = headers[HTTP2_HEADER_STATUS]; - response.headers = headers; - response.rawHeaders = rawHeaders; + // Attach iterators + if (typeof this.opts.store[Symbol.iterator] === 'function' && this.opts.store instanceof Map) { + this.iterator = generateIterator(this.opts.store); + } else if (typeof this.opts.store.iterator === 'function' && this.opts.store.opts + && this._checkIterableAdaptar()) { + this.iterator = generateIterator(this.opts.store.iterator.bind(this.opts.store)); + } + } - response.once('end', () => { - response.complete = true; + _checkIterableAdaptar() { + return iterableAdapters.includes(this.opts.store.opts.dialect) + || iterableAdapters.findIndex(element => this.opts.store.opts.url.includes(element)) >= 0; + } - // Has no effect, just be consistent with the Node.js behavior - response.socket = null; - response.connection = null; - }); + _getKeyPrefix(key) { + return `${this.opts.namespace}:${key}`; + } - if (isConnectMethod) { - response.upgrade = true; + _getKeyPrefixArray(keys) { + return keys.map(key => `${this.opts.namespace}:${key}`); + } - // The HTTP1 API says the socket is detached here, - // but we can't do that so we pass the original HTTP2 request. - if (this.emit('connect', response, stream, Buffer.alloc(0))) { - this.emit('close'); - } else { - // No listeners attached, destroy the original request. - stream.destroy(); - } - } else { - // Forwards data - stream.on('data', chunk => { - if (!response._dumped && !response.push(chunk)) { - stream.pause(); + _getKeyUnprefix(key) { + return key + .split(':') + .splice(1) + .join(':'); + } + + get(key, options) { + const {store} = this.opts; + const isArray = Array.isArray(key); + const keyPrefixed = isArray ? this._getKeyPrefixArray(key) : this._getKeyPrefix(key); + if (isArray && store.getMany === undefined) { + const promises = []; + for (const key of keyPrefixed) { + promises.push(Promise.resolve() + .then(() => store.get(key)) + .then(data => (typeof data === 'string') ? this.opts.deserialize(data) : (this.opts.compression ? this.opts.deserialize(data) : data)) + .then(data => { + if (data === undefined || data === null) { + return undefined; } - }); - stream.once('end', () => { - if (!this.aborted) { - response.push(null); + if (typeof data.expires === 'number' && Date.now() > data.expires) { + return this.delete(key).then(() => undefined); } - }); - if (!this.emit('response', response)) { - // No listeners attached, dump the response. - response._dump(); + return (options && options.raw) ? data : data.value; + }), + ); + } + + return Promise.allSettled(promises) + .then(values => { + const data = []; + for (const value of values) { + data.push(value.value); } - } - }; - // This event tells we are ready to listen for the data. - stream.once('response', onResponse); + return data; + }); + } - // Emits `information` event - stream.once('headers', headers => this.emit('information', {statusCode: headers[HTTP2_HEADER_STATUS]})); + return Promise.resolve() + .then(() => isArray ? store.getMany(keyPrefixed) : store.get(keyPrefixed)) + .then(data => (typeof data === 'string') ? this.opts.deserialize(data) : (this.opts.compression ? this.opts.deserialize(data) : data)) + .then(data => { + if (data === undefined || data === null) { + return undefined; + } - stream.once('trailers', (trailers, flags, rawTrailers) => { - const {res} = this; - - // https://github.com/nodejs/node/issues/41251 - if (res === null) { - onResponse(trailers, flags, rawTrailers); - return; - } - - // Assigns trailers to the response object. - res.trailers = trailers; - res.rawTrailers = rawTrailers; - }); - - stream.once('close', () => { - const {aborted, res} = this; - if (res) { - if (aborted) { - res.aborted = true; - res.emit('aborted'); - res.destroy(); - } - - const finish = () => { - res.emit('close'); + if (isArray) { + return data.map((row, index) => { + if ((typeof row === 'string')) { + row = this.opts.deserialize(row); + } - this.destroy(); - this.emit('close'); - }; + if (row === undefined || row === null) { + return undefined; + } - if (res.readable) { - res.once('end', finish); - } else { - finish(); - } + if (typeof row.expires === 'number' && Date.now() > row.expires) { + this.delete(key[index]).then(() => undefined); + return undefined; + } - return; + return (options && options.raw) ? row : row.value; + }); } - if (!this.destroyed) { - this.destroy(new Error('The HTTP/2 stream has been early terminated')); - this.emit('close'); - return; + if (typeof data.expires === 'number' && Date.now() > data.expires) { + return this.delete(key).then(() => undefined); } - this.destroy(); - this.emit('close'); + return (options && options.raw) ? data : data.value; }); + } - this.socket = new Proxy(stream, proxySocketHandler); - - for (const job of this[kJobs]) { - job(); - } - - this[kJobs].length = 0; - - this.emit('socket', this.socket); - }; + set(key, value, ttl) { + const keyPrefixed = this._getKeyPrefix(key); + if (typeof ttl === 'undefined') { + ttl = this.opts.ttl; + } - if (!(HTTP2_HEADER_AUTHORITY in this[kHeaders]) && !isConnectMethod) { - this[kHeaders][HTTP2_HEADER_AUTHORITY] = this[kOrigin].host; + if (ttl === 0) { + ttl = undefined; } - // Makes a HTTP2 request - if (this[kSession]) { - try { - onStream(this[kSession].request(this[kHeaders])); - } catch (error) { - this.destroy(error); - } - } else { - this.reusedSocket = true; + const {store} = this.opts; - try { - const promise = this.agent.request(this[kOrigin], this[kOptions], this[kHeaders]); - this[kPendingAgentPromise] = promise; + return Promise.resolve() + .then(() => { + const expires = (typeof ttl === 'number') ? (Date.now() + ttl) : null; + if (typeof value === 'symbol') { + this.emit('error', 'symbol cannot be serialized'); + } - onStream(await promise); + value = {value, expires}; + return this.opts.serialize(value); + }) + .then(value => store.set(keyPrefixed, value, ttl)) + .then(() => true); + } - this[kPendingAgentPromise] = false; - } catch (error) { - this[kPendingAgentPromise] = false; + delete(key) { + const {store} = this.opts; + if (Array.isArray(key)) { + const keyPrefixed = this._getKeyPrefixArray(key); + if (store.deleteMany === undefined) { + const promises = []; + for (const key of keyPrefixed) { + promises.push(store.delete(key)); + } - this.destroy(error); + return Promise.allSettled(promises) + .then(values => values.every(x => x.value === true)); } + + return Promise.resolve() + .then(() => store.deleteMany(keyPrefixed)); } - } - get connection() { - return this.socket; + const keyPrefixed = this._getKeyPrefix(key); + return Promise.resolve() + .then(() => store.delete(keyPrefixed)); } - set connection(value) { - this.socket = value; + clear() { + const {store} = this.opts; + return Promise.resolve() + .then(() => store.clear()); } - getHeaderNames() { - return Object.keys(this[kHeaders]); + has(key) { + const keyPrefixed = this._getKeyPrefix(key); + const {store} = this.opts; + return Promise.resolve() + .then(async () => { + if (typeof store.has === 'function') { + return store.has(keyPrefixed); + } + + const value = await store.get(keyPrefixed); + return value !== undefined; + }); } - hasHeader(name) { - if (typeof name !== 'string') { - throw new ERR_INVALID_ARG_TYPE('name', 'string', name); + disconnect() { + const {store} = this.opts; + if (typeof store.disconnect === 'function') { + return store.disconnect(); } - - return Boolean(this[kHeaders][name.toLowerCase()]); } +} - getHeader(name) { - if (typeof name !== 'string') { - throw new ERR_INVALID_ARG_TYPE('name', 'string', name); - } +module.exports = Keyv; - return this[kHeaders][name.toLowerCase()]; - } - get headersSent() { - return this[kFlushedHeaders]; - } +/***/ }), - removeHeader(name) { - if (typeof name !== 'string') { - throw new ERR_INVALID_ARG_TYPE('name', 'string', name); - } +/***/ 8789: +/***/ ((module) => { - if (this.headersSent) { - throw new ERR_HTTP_HEADERS_SENT('remove'); - } +// Int64.js +// +// Copyright (c) 2012 Robert Kieffer +// MIT License - http://opensource.org/licenses/mit-license.php - delete this[kHeaders][name.toLowerCase()]; - } +/** + * Support for handling 64-bit int numbers in Javascript (node.js) + * + * JS Numbers are IEEE-754 binary double-precision floats, which limits the + * range of values that can be represented with integer precision to: + * + * 2^^53 <= N <= 2^53 + * + * Int64 objects wrap a node Buffer that holds the 8-bytes of int64 data. These + * objects operate directly on the buffer which means that if they are created + * using an existing buffer then setting the value will modify the Buffer, and + * vice-versa. + * + * Internal Representation + * + * The internal buffer format is Big Endian. I.e. the most-significant byte is + * at buffer[0], the least-significant at buffer[7]. For the purposes of + * converting to/from JS native numbers, the value is assumed to be a signed + * integer stored in 2's complement form. + * + * For details about IEEE-754 see: + * http://en.wikipedia.org/wiki/Double_precision_floating-point_format + */ - setHeader(name, value) { - if (this.headersSent) { - throw new ERR_HTTP_HEADERS_SENT('set'); - } +// Useful masks and values for bit twiddling +var MASK31 = 0x7fffffff, VAL31 = 0x80000000; +var MASK32 = 0xffffffff, VAL32 = 0x100000000; - validateHeaderName(name); - validateHeaderValue(name, value); +// Map for converting hex octets to strings +var _HEX = []; +for (var i = 0; i < 256; i++) { + _HEX[i] = (i > 0xF ? '' : '0') + i.toString(16); +} - const lowercased = name.toLowerCase(); +// +// Int64 +// - if (lowercased === 'connection') { - if (value.toLowerCase() === 'keep-alive') { - return; - } +/** + * Constructor accepts any of the following argument types: + * + * new Int64(buffer[, offset=0]) - Existing Buffer with byte offset + * new Int64(Uint8Array[, offset=0]) - Existing Uint8Array with a byte offset + * new Int64(string) - Hex string (throws if n is outside int64 range) + * new Int64(number) - Number (throws if n is outside int64 range) + * new Int64(hi, lo) - Raw bits as two 32-bit values + */ +var Int64 = module.exports = function(a1, a2) { + if (a1 instanceof Buffer) { + this.buffer = a1; + this.offset = a2 || 0; + } else if (Object.prototype.toString.call(a1) == '[object Uint8Array]') { + // Under Browserify, Buffers can extend Uint8Arrays rather than an + // instance of Buffer. We could assume the passed in Uint8Array is actually + // a buffer but that won't handle the case where a raw Uint8Array is passed + // in. We construct a new Buffer just in case. + this.buffer = new Buffer(a1); + this.offset = a2 || 0; + } else { + this.buffer = this.buffer || new Buffer(8); + this.offset = 0; + this.setValue.apply(this, arguments); + } +}; - throw new Error(`Invalid 'connection' header: ${value}`); - } - if (lowercased === 'host' && this.method === 'CONNECT') { - this[kHeaders][HTTP2_HEADER_AUTHORITY] = value; - } else { - this[kHeaders][lowercased] = value; - } - } +// Max integer value that JS can accurately represent +Int64.MAX_INT = Math.pow(2, 53); - setNoDelay() { - // HTTP2 sockets cannot be malformed, do nothing. - } +// Min integer value that JS can accurately represent +Int64.MIN_INT = -Math.pow(2, 53); - setSocketKeepAlive() { - // HTTP2 sockets cannot be malformed, do nothing. - } +Int64.prototype = { - setTimeout(ms, callback) { - const applyTimeout = () => this._request.setTimeout(ms, callback); + constructor: Int64, - if (this._request) { - applyTimeout(); - } else { - this[kJobs].push(applyTimeout); - } + /** + * Do in-place 2's compliment. See + * http://en.wikipedia.org/wiki/Two's_complement + */ + _2scomp: function() { + var b = this.buffer, o = this.offset, carry = 1; + for (var i = o + 7; i >= o; i--) { + var v = (b[i] ^ 0xff) + carry; + b[i] = v & 0xff; + carry = v >> 8; + } + }, - return this; - } + /** + * Set the value. Takes any of the following arguments: + * + * setValue(string) - A hexidecimal string + * setValue(number) - Number (throws if n is outside int64 range) + * setValue(hi, lo) - Raw bits as two 32-bit values + */ + setValue: function(hi, lo) { + var negate = false; + if (arguments.length == 1) { + if (typeof(hi) == 'number') { + // Simplify bitfield retrieval by using abs() value. We restore sign + // later + negate = hi < 0; + hi = Math.abs(hi); + lo = hi % VAL32; + hi = hi / VAL32; + if (hi > VAL32) throw new RangeError(hi + ' is outside Int64 range'); + hi = hi | 0; + } else if (typeof(hi) == 'string') { + hi = (hi + '').replace(/^0x/, ''); + lo = hi.substr(-8); + hi = hi.length > 8 ? hi.substr(0, hi.length - 8) : ''; + hi = parseInt(hi, 16); + lo = parseInt(lo, 16); + } else { + throw new Error(hi + ' must be a Number or String'); + } + } - get maxHeadersCount() { - if (!this.destroyed && this._request) { - return this._request.session.localSettings.maxHeaderListSize; - } + // Technically we should throw if hi or lo is outside int32 range here, but + // it's not worth the effort. Anything past the 32'nd bit is ignored. - return undefined; - } + // Copy bytes to buffer + var b = this.buffer, o = this.offset; + for (var i = 7; i >= 0; i--) { + b[o+i] = lo & 0xff; + lo = i == 4 ? hi : lo >>> 8; + } - set maxHeadersCount(_value) { - // Updating HTTP2 settings would affect all requests, do nothing. - } -} + // Restore sign of passed argument + if (negate) this._2scomp(); + }, -module.exports = ClientRequest; + /** + * Convert to a native JS number. + * + * WARNING: Do not expect this value to be accurate to integer precision for + * large (positive or negative) numbers! + * + * @param allowImprecise If true, no check is performed to verify the + * returned value is accurate to integer precision. If false, imprecise + * numbers (very large positive or negative numbers) will be forced to +/- + * Infinity. + */ + toNumber: function(allowImprecise) { + var b = this.buffer, o = this.offset; + + // Running sum of octets, doing a 2's complement + var negate = b[o] & 0x80, x = 0, carry = 1; + for (var i = 7, m = 1; i >= 0; i--, m *= 256) { + var v = b[o+i]; + + // 2's complement for negative numbers + if (negate) { + v = (v ^ 0xff) + carry; + carry = v >> 8; + v = v & 0xff; + } + x += v * m; + } -/***/ }), + // Return Infinity if we've lost integer precision + if (!allowImprecise && x >= Int64.MAX_INT) { + return negate ? -Infinity : Infinity; + } -/***/ 2575: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return negate ? -x : x; + }, + /** + * Convert to a JS Number. Returns +/-Infinity for values that can't be + * represented to integer precision. + */ + valueOf: function() { + return this.toNumber(false); + }, -const {Readable} = __nccwpck_require__(2781); + /** + * Return string value + * + * @param radix Just like Number#toString()'s radix + */ + toString: function(radix) { + return this.valueOf().toString(radix || 10); + }, -class IncomingMessage extends Readable { - constructor(socket, highWaterMark) { - super({ - emitClose: false, - autoDestroy: true, - highWaterMark - }); + /** + * Return a string showing the buffer octets, with MSB on the left. + * + * @param sep separator string. default is '' (empty string) + */ + toOctetString: function(sep) { + var out = new Array(8); + var b = this.buffer, o = this.offset; + for (var i = 0; i < 8; i++) { + out[i] = _HEX[b[o+i]]; + } + return out.join(sep || ''); + }, - this.statusCode = null; - this.statusMessage = ''; - this.httpVersion = '2.0'; - this.httpVersionMajor = 2; - this.httpVersionMinor = 0; - this.headers = {}; - this.trailers = {}; - this.req = null; + /** + * Returns the int64's 8 bytes in a buffer. + * + * @param {bool} [rawBuffer=false] If no offset and this is true, return the internal buffer. Should only be used if + * you're discarding the Int64 afterwards, as it breaks encapsulation. + */ + toBuffer: function(rawBuffer) { + if (rawBuffer && this.offset === 0) return this.buffer; + + var out = new Buffer(8); + this.buffer.copy(out, 0, this.offset, this.offset + 8); + return out; + }, - this.aborted = false; - this.complete = false; - this.upgrade = null; + /** + * Copy 8 bytes of int64 into target buffer at target offset. + * + * @param {Buffer} targetBuffer Buffer to copy into. + * @param {number} [targetOffset=0] Offset into target buffer. + */ + copy: function(targetBuffer, targetOffset) { + this.buffer.copy(targetBuffer, targetOffset || 0, this.offset, this.offset + 8); + }, - this.rawHeaders = []; - this.rawTrailers = []; + /** + * Returns a number indicating whether this comes before or after or is the + * same as the other in sort order. + * + * @param {Int64} other Other Int64 to compare. + */ + compare: function(other) { - this.socket = socket; + // If sign bits differ ... + if ((this.buffer[this.offset] & 0x80) != (other.buffer[other.offset] & 0x80)) { + return other.buffer[other.offset] - this.buffer[this.offset]; + } - this._dumped = false; - } + // otherwise, compare bytes lexicographically + for (var i = 0; i < 8; i++) { + if (this.buffer[this.offset+i] !== other.buffer[other.offset+i]) { + return this.buffer[this.offset+i] - other.buffer[other.offset+i]; + } + } + return 0; + }, - get connection() { - return this.socket; - } + /** + * Returns a boolean indicating if this integer is equal to other. + * + * @param {Int64} other Other Int64 to compare. + */ + equals: function(other) { + return this.compare(other) === 0; + }, - set connection(value) { - this.socket = value; - } + /** + * Pretty output in console.log + */ + inspect: function() { + return '[Int64 value:' + this + ' octets:' + this.toOctetString(' ') + ']'; + } +}; - _destroy(error, callback) { - if (!this.readableEnded) { - this.aborted = true; - } - // See https://github.com/nodejs/node/issues/35303 - callback(); +/***/ }), - this.req._request.destroy(error); - } +/***/ 1564: +/***/ ((module) => { - setTimeout(ms, callback) { - this.req.setTimeout(ms, callback); - return this; - } - _dump() { - if (!this._dumped) { - this._dumped = true; - this.removeAllListeners('data'); - this.resume(); - } - } +if (typeof process === 'undefined' || + !process.version || + process.version.indexOf('v0.') === 0 || + process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { + module.exports = { nextTick: nextTick }; +} else { + module.exports = process +} - _read() { - if (this.req) { - this.req._request.resume(); - } - } +function nextTick(fn, arg1, arg2, arg3) { + if (typeof fn !== 'function') { + throw new TypeError('"callback" argument must be a function'); + } + var len = arguments.length; + var args, i; + switch (len) { + case 0: + case 1: + return process.nextTick(fn); + case 2: + return process.nextTick(function afterTickOne() { + fn.call(null, arg1); + }); + case 3: + return process.nextTick(function afterTickTwo() { + fn.call(null, arg1, arg2); + }); + case 4: + return process.nextTick(function afterTickThree() { + fn.call(null, arg1, arg2, arg3); + }); + default: + args = new Array(len - 1); + i = 0; + while (i < args.length) { + args[i++] = arguments[i]; + } + return process.nextTick(function afterTick() { + fn.apply(null, args); + }); + } } -module.exports = IncomingMessage; /***/ }), -/***/ 4645: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -const http2 = __nccwpck_require__(5158); -const { - Agent, - globalAgent -} = __nccwpck_require__(9898); -const ClientRequest = __nccwpck_require__(9632); -const IncomingMessage = __nccwpck_require__(2575); -const auto = __nccwpck_require__(7167); -const { - HttpOverHttp2, - HttpsOverHttp2 -} = __nccwpck_require__(8795); -const Http2OverHttp2 = __nccwpck_require__(8553); -const { - Http2OverHttp, - Http2OverHttps -} = __nccwpck_require__(9794); -const validateHeaderName = __nccwpck_require__(4592); -const validateHeaderValue = __nccwpck_require__(3549); +/***/ 5475: +/***/ ((module) => { -const request = (url, options, callback) => new ClientRequest(url, options, callback); -const get = (url, options, callback) => { - // eslint-disable-next-line unicorn/prevent-abbreviations - const req = new ClientRequest(url, options, callback); - req.end(); - return req; -}; +class QuickLRU { + constructor(options = {}) { + if (!(options.maxSize && options.maxSize > 0)) { + throw new TypeError('`maxSize` must be a number greater than 0'); + } -module.exports = { - ...http2, - ClientRequest, - IncomingMessage, - Agent, - globalAgent, - request, - get, - auto, - proxies: { - HttpOverHttp2, - HttpsOverHttp2, - Http2OverHttp2, - Http2OverHttp, - Http2OverHttps - }, - validateHeaderName, - validateHeaderValue -}; + this.maxSize = options.maxSize; + this.onEviction = options.onEviction; + this.cache = new Map(); + this.oldCache = new Map(); + this._size = 0; + } + _set(key, value) { + this.cache.set(key, value); + this._size++; -/***/ }), + if (this._size >= this.maxSize) { + this._size = 0; -/***/ 7885: -/***/ ((module) => { + if (typeof this.onEviction === 'function') { + for (const [key, value] of this.oldCache.entries()) { + this.onEviction(key, value); + } + } + this.oldCache = this.cache; + this.cache = new Map(); + } + } + get(key) { + if (this.cache.has(key)) { + return this.cache.get(key); + } -module.exports = self => { - const {username, password} = self.proxyOptions.url; + if (this.oldCache.has(key)) { + const value = this.oldCache.get(key); + this.oldCache.delete(key); + this._set(key, value); + return value; + } + } - if (username || password) { - const data = `${username}:${password}`; - const authorization = `Basic ${Buffer.from(data).toString('base64')}`; + set(key, value) { + if (this.cache.has(key)) { + this.cache.set(key, value); + } else { + this._set(key, value); + } - return { - 'proxy-authorization': authorization, - authorization - }; + return this; } - return {}; -}; + has(key) { + return this.cache.has(key) || this.oldCache.has(key); + } + peek(key) { + if (this.cache.has(key)) { + return this.cache.get(key); + } -/***/ }), + if (this.oldCache.has(key)) { + return this.oldCache.get(key); + } + } -/***/ 8795: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + delete(key) { + const deleted = this.cache.delete(key); + if (deleted) { + this._size--; + } + return this.oldCache.delete(key) || deleted; + } -const tls = __nccwpck_require__(4404); -const http = __nccwpck_require__(3685); -const https = __nccwpck_require__(5687); -const JSStreamSocket = __nccwpck_require__(1564); -const {globalAgent} = __nccwpck_require__(9898); -const UnexpectedStatusCodeError = __nccwpck_require__(4065); -const initialize = __nccwpck_require__(1089); -const getAuthorizationHeaders = __nccwpck_require__(7885); + clear() { + this.cache.clear(); + this.oldCache.clear(); + this._size = 0; + } -const createConnection = (self, options, callback) => { - (async () => { - try { - const {proxyOptions} = self; - const {url, headers, raw} = proxyOptions; + * keys() { + for (const [key] of this) { + yield key; + } + } - const stream = await globalAgent.request(url, proxyOptions, { - ...getAuthorizationHeaders(self), - ...headers, - ':method': 'CONNECT', - ':authority': `${options.host}:${options.port}` - }); + * values() { + for (const [, value] of this) { + yield value; + } + } - stream.once('error', callback); - stream.once('response', headers => { - const statusCode = headers[':status']; + * [Symbol.iterator]() { + for (const item of this.cache) { + yield item; + } - if (statusCode !== 200) { - callback(new UnexpectedStatusCodeError(statusCode, '')); - return; - } - - const encrypted = self instanceof https.Agent; - - if (raw && encrypted) { - options.socket = stream; - const secureStream = tls.connect(options); - - secureStream.once('close', () => { - stream.destroy(); - }); - - callback(null, secureStream); - return; - } - - const socket = new JSStreamSocket(stream); - socket.encrypted = false; - socket._handle.getpeername = out => { - out.family = undefined; - out.address = undefined; - out.port = undefined; - }; - - callback(null, socket); - }); - } catch (error) { - callback(error); + for (const item of this.oldCache) { + const [key] = item; + if (!this.cache.has(key)) { + yield item; + } } - })(); -}; - -class HttpOverHttp2 extends http.Agent { - constructor(options) { - super(options); - - initialize(this, options.proxyOptions); } - createConnection(options, callback) { - createConnection(this, options, callback); - } -} - -class HttpsOverHttp2 extends https.Agent { - constructor(options) { - super(options); - - initialize(this, options.proxyOptions); - } + get size() { + let oldCacheSize = 0; + for (const key of this.oldCache.keys()) { + if (!this.cache.has(key)) { + oldCacheSize++; + } + } - createConnection(options, callback) { - createConnection(this, options, callback); + return Math.min(this._size + oldCacheSize, this.maxSize); } } -module.exports = { - HttpOverHttp2, - HttpsOverHttp2 -}; +module.exports = QuickLRU; /***/ }), -/***/ 9794: +/***/ 2063: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. -const http = __nccwpck_require__(3685); -const https = __nccwpck_require__(5687); -const Http2OverHttpX = __nccwpck_require__(1857); -const getAuthorizationHeaders = __nccwpck_require__(7885); +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. -const getStream = request => new Promise((resolve, reject) => { - const onConnect = (response, socket, head) => { - socket.unshift(head); - request.off('error', reject); - resolve([socket, response.statusCode, response.statusMessage]); - }; - request.once('error', reject); - request.once('connect', onConnect); -}); +/**/ -class Http2OverHttp extends Http2OverHttpX { - async _getProxyStream(authority) { - const {proxyOptions} = this; - const {url, headers} = this.proxyOptions; +var pna = __nccwpck_require__(1564); +/**/ - const network = url.protocol === 'https:' ? https : http; +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; +}; +/**/ - // `new URL('https://localhost/httpbin.org:443')` results in - // a `/httpbin.org:443` path, which has an invalid leading slash. - const request = network.request({ - ...proxyOptions, - hostname: url.hostname, - port: url.port, - path: authority, - headers: { - ...getAuthorizationHeaders(this), - ...headers, - host: authority - }, - method: 'CONNECT' - }).end(); +module.exports = Duplex; - return getStream(request); - } +/**/ +var util = Object.create(__nccwpck_require__(5481)); +util.inherits = __nccwpck_require__(9598); +/**/ + +var Readable = __nccwpck_require__(6893); +var Writable = __nccwpck_require__(8797); + +util.inherits(Duplex, Readable); + +{ + // avoid scope creep, the keys array can then be collected + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } } -module.exports = { - Http2OverHttp, - Http2OverHttps: Http2OverHttp -}; +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + Readable.call(this, options); + Writable.call(this, options); -/***/ }), + if (options && options.readable === false) this.readable = false; -/***/ 8553: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (options && options.writable === false) this.writable = false; + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; -const {globalAgent} = __nccwpck_require__(9898); -const Http2OverHttpX = __nccwpck_require__(1857); -const getAuthorizationHeaders = __nccwpck_require__(7885); + this.once('end', onend); +} -const getStatusCode = stream => new Promise((resolve, reject) => { - stream.once('error', reject); - stream.once('response', headers => { - stream.off('error', reject); - resolve(headers[':status']); - }); +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 () { + return this._writableState.highWaterMark; + } }); -class Http2OverHttp2 extends Http2OverHttpX { - async _getProxyStream(authority) { - const {proxyOptions} = this; - - const headers = { - ...getAuthorizationHeaders(this), - ...proxyOptions.headers, - ':method': 'CONNECT', - ':authority': authority - }; +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; - const stream = await globalAgent.request(proxyOptions.url, proxyOptions, headers); - const statusCode = await getStatusCode(stream); + // no more data can be written. + // But allow more writes to happen in this tick. + pna.nextTick(onEndNT, this); +} - return [stream, statusCode, '']; - } +function onEndNT(self) { + self.end(); } -module.exports = Http2OverHttp2; +Object.defineProperty(Duplex.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); + +Duplex.prototype._destroy = function (err, cb) { + this.push(null); + this.end(); + pna.nextTick(cb, err); +}; /***/ }), -/***/ 1857: +/***/ 5283: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. -const {Agent} = __nccwpck_require__(9898); -const JSStreamSocket = __nccwpck_require__(1564); -const UnexpectedStatusCodeError = __nccwpck_require__(4065); -const initialize = __nccwpck_require__(1089); +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. -class Http2OverHttpX extends Agent { - constructor(options) { - super(options); - initialize(this, options.proxyOptions); - } - async createConnection(origin, options) { - const authority = `${origin.hostname}:${origin.port || 443}`; +module.exports = PassThrough; - const [stream, statusCode, statusMessage] = await this._getProxyStream(authority); - if (statusCode !== 200) { - throw new UnexpectedStatusCodeError(statusCode, statusMessage); - } +var Transform = __nccwpck_require__(2337); - if (this.proxyOptions.raw) { - options.socket = stream; - } else { - const socket = new JSStreamSocket(stream); - socket.encrypted = false; - socket._handle.getpeername = out => { - out.family = undefined; - out.address = undefined; - out.port = undefined; - }; +/**/ +var util = Object.create(__nccwpck_require__(5481)); +util.inherits = __nccwpck_require__(9598); +/**/ - return socket; - } +util.inherits(PassThrough, Transform); - return super.createConnection(origin, options); - } -} +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); -module.exports = Http2OverHttpX; + Transform.call(this, options); +} +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; /***/ }), -/***/ 1089: +/***/ 6893: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. -// See https://github.com/facebook/jest/issues/2549 -// eslint-disable-next-line node/prefer-global/url -const {URL} = __nccwpck_require__(7310); -const checkType = __nccwpck_require__(3453); -module.exports = (self, proxyOptions) => { - checkType('proxyOptions', proxyOptions, ['object']); - checkType('proxyOptions.headers', proxyOptions.headers, ['object', 'undefined']); - checkType('proxyOptions.raw', proxyOptions.raw, ['boolean', 'undefined']); - checkType('proxyOptions.url', proxyOptions.url, [URL, 'string']); - const url = new URL(proxyOptions.url); +/**/ - self.proxyOptions = { - raw: true, - ...proxyOptions, - headers: {...proxyOptions.headers}, - url - }; -}; +var pna = __nccwpck_require__(1564); +/**/ +module.exports = Readable; -/***/ }), +/**/ +var isArray = __nccwpck_require__(2513); +/**/ -/***/ 4065: -/***/ ((module) => { +/**/ +var Duplex; +/**/ +Readable.ReadableState = ReadableState; +/**/ +var EE = (__nccwpck_require__(4434).EventEmitter); -class UnexpectedStatusCodeError extends Error { - constructor(statusCode, statusMessage = '') { - super(`The proxy server rejected the request with status code ${statusCode} (${statusMessage || 'empty status message'})`); - this.statusCode = statusCode; - this.statusMessage = statusMessage; - } -} +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; +}; +/**/ -module.exports = UnexpectedStatusCodeError; +/**/ +var Stream = __nccwpck_require__(3283); +/**/ +/**/ -/***/ }), +var Buffer = (__nccwpck_require__(3058).Buffer); +var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} -/***/ 1982: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/**/ +/**/ +var util = Object.create(__nccwpck_require__(5481)); +util.inherits = __nccwpck_require__(9598); +/**/ -const {isIP} = __nccwpck_require__(1808); -const assert = __nccwpck_require__(9491); +/**/ +var debugUtil = __nccwpck_require__(9023); +var debug = void 0; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function () {}; +} +/**/ -const getHost = host => { - if (host[0] === '[') { - const idx = host.indexOf(']'); +var BufferList = __nccwpck_require__(9381); +var destroyImpl = __nccwpck_require__(5089); +var StringDecoder; - assert(idx !== -1); - return host.slice(1, idx); - } +util.inherits(Readable, Stream); - const idx = host.indexOf(':'); - if (idx === -1) { - return host; - } +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - return host.slice(0, idx); -}; +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); -module.exports = host => { - const servername = getHost(host); + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} - if (isIP(servername)) { - return ''; - } +function ReadableState(options, stream) { + Duplex = Duplex || __nccwpck_require__(2063); - return servername; -}; + options = options || {}; + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; -/***/ }), + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; -/***/ 3453: -/***/ ((module) => { + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var readableHwm = options.readableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; -const checkType = (name, value, types) => { - const valid = types.some(type => { - const typeofType = typeof type; - if (typeofType === 'string') { - return typeof value === type; - } + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); - return value instanceof type; - }); + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + 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; - if (!valid) { - const names = types.map(type => typeof type === 'string' ? type : type.name); + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; - throw new TypeError(`Expected '${name}' to be a type of ${names.join(' or ')}, got ${typeof value}`); - } -}; + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; -module.exports = checkType; + // has it been destroyed + this.destroyed = false; + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; -/***/ }), + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; -/***/ 9237: -/***/ ((module) => { + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = (__nccwpck_require__(634)/* .StringDecoder */ .I); + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} +function Readable(options) { + Duplex = Duplex || __nccwpck_require__(2063); -module.exports = stream => { - if (stream.listenerCount('error') !== 0) { - return stream; - } + if (!(this instanceof Readable)) return new Readable(options); - stream.__destroy = stream._destroy; - stream._destroy = (...args) => { - const callback = args.pop(); + this._readableState = new ReadableState(options, this); - stream.__destroy(...args, async error => { - await Promise.resolve(); - callback(error); - }); - }; + // legacy + this.readable = true; - const onError = error => { - // eslint-disable-next-line promise/prefer-await-to-then - Promise.resolve().then(() => { - stream.emit('error', error); - }); - }; + if (options) { + if (typeof options.read === 'function') this._read = options.read; - stream.once('error', onError); + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } - // eslint-disable-next-line promise/prefer-await-to-then - Promise.resolve().then(() => { - stream.off('error', onError); - }); - - return stream; -}; - - -/***/ }), - -/***/ 7087: -/***/ ((module) => { + Stream.call(this); +} +Object.defineProperty(Readable.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } -/* istanbul ignore file: https://github.com/nodejs/node/blob/master/lib/internal/errors.js */ + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); -const makeError = (Base, key, getMessage) => { - module.exports[key] = class NodeError extends Base { - constructor(...args) { - super(typeof getMessage === 'string' ? getMessage : getMessage(args)); - this.name = `${super.name} [${key}]`; - this.code = key; - } - }; +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + this.push(null); + cb(err); }; -makeError(TypeError, 'ERR_INVALID_ARG_TYPE', args => { - const type = args[0].includes('.') ? 'property' : 'argument'; - - let valid = args[1]; - const isManyTypes = Array.isArray(valid); - - if (isManyTypes) { - valid = `${valid.slice(0, -1).join(', ')} or ${valid.slice(-1)}`; - } - - return `The "${args[0]}" ${type} must be ${isManyTypes ? 'one of' : 'of'} type ${valid}. Received ${typeof args[2]}`; -}); - -makeError(TypeError, 'ERR_INVALID_PROTOCOL', args => - `Protocol "${args[0]}" not supported. Expected "${args[1]}"` -); +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; -makeError(Error, 'ERR_HTTP_HEADERS_SENT', args => - `Cannot ${args[0]} headers after they are sent to the client` -); + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } -makeError(TypeError, 'ERR_INVALID_HTTP_TOKEN', args => - `${args[0]} must be a valid HTTP token [${args[1]}]` -); + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; -makeError(TypeError, 'ERR_HTTP_INVALID_HEADER_VALUE', args => - `Invalid value "${args[0]} for header "${args[1]}"` -); +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; -makeError(TypeError, 'ERR_INVALID_CHAR', args => - `Invalid character in ${args[0]} [${args[1]}]` -); +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } -makeError( - Error, - 'ERR_HTTP2_NO_SOCKET_MANIPULATION', - 'HTTP/2 sockets should not be directly manipulated (e.g. read and written)' -); + if (addToFront) { + if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); + } else if (state.ended) { + stream.emit('error', new Error('stream.push() after EOF')); + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + } + } + return needMoreData(state); +} -/***/ }), +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); -/***/ 1199: -/***/ ((module) => { + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); +} +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} -module.exports = header => { - switch (header) { - case ':method': - case ':scheme': - case ':authority': - case ':path': - return true; - default: - return false; - } +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; }; +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = (__nccwpck_require__(634)/* .StringDecoder */ .I); + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; -/***/ }), - -/***/ 1564: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -const stream = __nccwpck_require__(2781); -const tls = __nccwpck_require__(4404); - -// Really awesome hack. -const JSStreamSocket = (new tls.TLSSocket(new stream.PassThrough()))._handle._parentWrap.constructor; +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} -module.exports = JSStreamSocket; +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; -/***/ }), + if (n !== 0) state.emittedReadable = false; -/***/ 1818: -/***/ ((module) => { + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + n = howMuchToRead(n, state); + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } -module.exports = (from, to, events) => { - for (const event of events) { - from.on(event, (...args) => to.emit(event, ...args)); - } -}; - + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. -/***/ }), + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); -/***/ 9404: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } -const {ERR_HTTP2_NO_SOCKET_MANIPULATION} = __nccwpck_require__(7087); + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; -/* istanbul ignore file */ -/* https://github.com/nodejs/node/blob/6eec858f34a40ffa489c1ec54bb24da72a28c781/lib/internal/http2/compat.js#L195-L272 */ + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } -const proxySocketHandler = { - has(stream, property) { - // Replaced [kSocket] with .socket - const reference = stream.session === undefined ? stream : stream.session.socket; - return (property in stream) || (property in reference); - }, + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; - get(stream, property) { - switch (property) { - case 'on': - case 'once': - case 'end': - case 'emit': - case 'destroy': - return stream[property].bind(stream); - case 'writable': - case 'destroyed': - return stream[property]; - case 'readable': - if (stream.destroyed) { - return false; - } + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } - return stream.readable; - case 'setTimeout': { - const {session} = stream; - if (session !== undefined) { - return session.setTimeout.bind(session); - } + if (ret !== null) this.emit('data', ret); - return stream.setTimeout.bind(stream); - } + return ret; +}; - case 'write': - case 'read': - case 'pause': - case 'resume': - throw new ERR_HTTP2_NO_SOCKET_MANIPULATION(); - default: { - // Replaced [kSocket] with .socket - const reference = stream.session === undefined ? stream : stream.session.socket; - const value = reference[property]; +function onEofChunk(stream, state) { + 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; - return typeof value === 'function' ? value.bind(reference) : value; - } - } - }, + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} - getPrototypeOf(stream) { - if (stream.session !== undefined) { - // Replaced [kSocket] with .socket - return Reflect.getPrototypeOf(stream.session.socket); - } +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); + } +} - return Reflect.getPrototypeOf(stream); - }, +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} - set(stream, property, value) { - switch (property) { - case 'writable': - case 'readable': - case 'destroyed': - case 'on': - case 'once': - case 'end': - case 'emit': - case 'destroy': - stream[property] = value; - return true; - case 'setTimeout': { - const {session} = stream; - if (session === undefined) { - stream.setTimeout = value; - } else { - session.setTimeout = value; - } +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + pna.nextTick(maybeReadMore_, stream, state); + } +} - return true; - } +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} - case 'write': - case 'read': - case 'pause': - case 'resume': - throw new ERR_HTTP2_NO_SOCKET_MANIPULATION(); - default: { - // Replaced [kSocket] with .socket - const reference = stream.session === undefined ? stream : stream.session.socket; - reference[property] = value; - return true; - } - } - } +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('_read() is not implemented')); }; -module.exports = proxySocketHandler; +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); -/***/ }), + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; -/***/ 4592: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } -const {ERR_INVALID_HTTP_TOKEN} = __nccwpck_require__(7087); -const isRequestPseudoHeader = __nccwpck_require__(1199); + function onend() { + debug('onend'); + dest.end(); + } -const isValidHttpToken = /^[\^`\-\w!#$%&*+.|~]+$/; + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); -module.exports = name => { - if (typeof name !== 'string' || (!isValidHttpToken.test(name) && !isRequestPseudoHeader(name))) { - throw new ERR_INVALID_HTTP_TOKEN('Header name', name); - } -}; - - -/***/ }), - -/***/ 3549: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -const { - ERR_HTTP_INVALID_HEADER_VALUE, - ERR_INVALID_CHAR -} = __nccwpck_require__(7087); + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + 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); -const isInvalidHeaderValue = /[^\t\u0020-\u007E\u0080-\u00FF]/; + cleanedUp = true; -module.exports = (name, value) => { - if (typeof value === 'undefined') { - throw new ERR_HTTP_INVALID_HEADER_VALUE(value, name); - } + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } - if (isInvalidHeaderValue.test(value)) { - throw new ERR_INVALID_CHAR('header content', name); - } -}; + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', state.awaitDrain); + state.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + } -/***/ }), + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); -/***/ 2492: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); -var wrappy = __nccwpck_require__(2940) -var reqs = Object.create(null) -var once = __nccwpck_require__(1223) + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } -module.exports = wrappy(inflight) + // tell the dest that it's being piped to + dest.emit('pipe', src); -function inflight (key, cb) { - if (reqs[key]) { - reqs[key].push(cb) - return null - } else { - reqs[key] = [cb] - return makeres(key) + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); } -} -function makeres (key) { - return once(function RES () { - var cbs = reqs[key] - var len = cbs.length - var args = slice(arguments) + return dest; +}; - // XXX It's somewhat ambiguous whether a new callback added in this - // pass should be queued for later execution if something in the - // list of callbacks throws, or if it should just be discarded. - // However, it's such an edge case that it hardly matters, and either - // choice is likely as surprising as the other. - // As it happens, we do go ahead and schedule it for later execution. - try { - for (var i = 0; i < len; i++) { - cbs[i].apply(null, args) - } - } finally { - if (cbs.length > len) { - // added more in the interim. - // de-zalgo, just in case, but don't call again. - cbs.splice(0, len) - process.nextTick(function () { - RES.apply(null, args) - }) - } else { - delete reqs[key] - } +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); } - }) -} - -function slice (args) { - var length = args.length - var array = [] - - for (var i = 0; i < length; i++) array[i] = args[i] - return array + }; } +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { hasUnpiped: false }; -/***/ }), + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; -/***/ 4124: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; -try { - var util = __nccwpck_require__(3837); - /* istanbul ignore next */ - if (typeof util.inherits !== 'function') throw ''; - module.exports = util.inherits; -} catch (e) { - /* istanbul ignore next */ - module.exports = __nccwpck_require__(8544); -} + if (!dest) dest = state.pipes; + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } -/***/ }), + // slow case. multiple pipe destinations. -/***/ 8544: -/***/ ((module) => { + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.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 { - // old school shim for old browsers - module.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 - } + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, { hasUnpiped: false }); + }return this; } -} + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; -/***/ }), - -/***/ 893: -/***/ ((module) => { + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; -var toString = {}.toString; + dest.emit('unpipe', this, unpipeInfo); -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; + return this; }; +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); -/***/ }), + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + pna.nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } -/***/ 2820: -/***/ ((__unused_webpack_module, exports) => { + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; -//TODO: handle reviver/dehydrate function like normal -//and handle indentation, like normal. -//if anyone needs this... please send pull request. +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} -exports.stringify = function stringify (o) { - if('undefined' == typeof o) return o +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; - if(o && Buffer.isBuffer(o)) - return JSON.stringify(':base64:' + o.toString('base64')) +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + pna.nextTick(resume_, stream, state); + } +} - if(o && o.toJSON) - o = o.toJSON() - - if(o && 'object' === typeof o) { - var s = '' - var array = Array.isArray(o) - s = array ? '[' : '{' - var first = true +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } - for(var k in o) { - var ignore = 'function' == typeof o[k] || (!array && 'undefined' === typeof o[k]) - if(Object.hasOwnProperty.call(o, k) && !ignore) { - if(!first) - s += ',' - first = false - if (array) { - if(o[k] == undefined) - s += 'null' - else - s += stringify(o[k]) - } else if (o[k] !== void(0)) { - s += stringify(k) + ':' + stringify(o[k]) - } - } - } + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} - s += array ? ']' : '}' +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; - return s - } else if ('string' === typeof o) { - return JSON.stringify(/^:/.test(o) ? ':' + o : o) - } else if ('undefined' === typeof o) { - return 'null'; - } else - return JSON.stringify(o) +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} } -exports.parse = function (s) { - return JSON.parse(s, function (key, value) { - if('string' === typeof value) { - if(/^:base64:/.test(value)) - return Buffer.from(value.substring(8), 'base64') - else - return /^:/.test(value) ? value.substring(1) : value +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var _this = this; + + var state = this._readableState; + var paused = false; + + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); } - return value - }) -} + _this.push(null); + }); -/***/ }), + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); -/***/ 1531: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } -const EventEmitter = __nccwpck_require__(2361); -const JSONB = __nccwpck_require__(2820); + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } -const loadStore = options => { - const adapters = { - redis: '@keyv/redis', - rediss: '@keyv/redis', - mongodb: '@keyv/mongo', - mongo: '@keyv/mongo', - sqlite: '@keyv/sqlite', - postgresql: '@keyv/postgres', - postgres: '@keyv/postgres', - mysql: '@keyv/mysql', - etcd: '@keyv/etcd', - offline: '@keyv/offline', - tiered: '@keyv/tiered', - }; - if (options.adapter || options.uri) { - const adapter = options.adapter || /^[^:+]*/.exec(options.uri)[0]; - return new (require(adapters[adapter]))(options); - } + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; - return new Map(); + return this; }; -const iterableAdapters = [ - 'sqlite', - 'postgres', - 'mysql', - 'mongo', - 'redis', - 'tiered', -]; +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._readableState.highWaterMark; + } +}); -class Keyv extends EventEmitter { - constructor(uri, {emitErrors = true, ...options} = {}) { - super(); - this.opts = { - namespace: 'keyv', - serialize: JSONB.stringify, - deserialize: JSONB.parse, - ...((typeof uri === 'string') ? {uri} : uri), - ...options, - }; +// exposed for testing purposes only. +Readable._fromList = fromList; - if (!this.opts.store) { - const adapterOptions = {...this.opts}; - this.opts.store = loadStore(adapterOptions); - } +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; - if (this.opts.compression) { - const compression = this.opts.compression; - this.opts.serialize = compression.serialize.bind(compression); - this.opts.deserialize = compression.deserialize.bind(compression); - } + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } - if (typeof this.opts.store.on === 'function' && emitErrors) { - this.opts.store.on('error', error => this.emit('error', error)); - } + return ret; +} - this.opts.store.namespace = this.opts.namespace; +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; +} - const generateIterator = iterator => async function * () { - for await (const [key, raw] of typeof iterator === 'function' - ? iterator(this.opts.store.namespace) - : iterator) { - const data = this.opts.deserialize(raw); - if (this.opts.store.namespace && !key.includes(this.opts.store.namespace)) { - continue; - } +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.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) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} - if (typeof data.expires === 'number' && Date.now() > data.expires) { - this.delete(key); - continue; - } - - yield [this._getKeyUnprefix(key), data.value]; - } - }; +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.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) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} - // Attach iterators - if (typeof this.opts.store[Symbol.iterator] === 'function' && this.opts.store instanceof Map) { - this.iterator = generateIterator(this.opts.store); - } else if (typeof this.opts.store.iterator === 'function' && this.opts.store.opts - && this._checkIterableAdaptar()) { - this.iterator = generateIterator(this.opts.store.iterator.bind(this.opts.store)); - } - } +function endReadable(stream) { + var state = stream._readableState; - _checkIterableAdaptar() { - return iterableAdapters.includes(this.opts.store.opts.dialect) - || iterableAdapters.findIndex(element => this.opts.store.opts.url.includes(element)) >= 0; - } + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); - _getKeyPrefix(key) { - return `${this.opts.namespace}:${key}`; - } + if (!state.endEmitted) { + state.ended = true; + pna.nextTick(endReadableNT, state, stream); + } +} - _getKeyPrefixArray(keys) { - return keys.map(key => `${this.opts.namespace}:${key}`); - } +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} - _getKeyUnprefix(key) { - return key - .split(':') - .splice(1) - .join(':'); - } +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} - get(key, options) { - const {store} = this.opts; - const isArray = Array.isArray(key); - const keyPrefixed = isArray ? this._getKeyPrefixArray(key) : this._getKeyPrefix(key); - if (isArray && store.getMany === undefined) { - const promises = []; - for (const key of keyPrefixed) { - promises.push(Promise.resolve() - .then(() => store.get(key)) - .then(data => (typeof data === 'string') ? this.opts.deserialize(data) : (this.opts.compression ? this.opts.deserialize(data) : data)) - .then(data => { - if (data === undefined || data === null) { - return undefined; - } +/***/ }), - if (typeof data.expires === 'number' && Date.now() > data.expires) { - return this.delete(key).then(() => undefined); - } +/***/ 2337: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return (options && options.raw) ? data : data.value; - }), - ); - } +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - return Promise.allSettled(promises) - .then(values => { - const data = []; - for (const value of values) { - data.push(value.value); - } +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. - return data; - }); - } - return Promise.resolve() - .then(() => isArray ? store.getMany(keyPrefixed) : store.get(keyPrefixed)) - .then(data => (typeof data === 'string') ? this.opts.deserialize(data) : (this.opts.compression ? this.opts.deserialize(data) : data)) - .then(data => { - if (data === undefined || data === null) { - return undefined; - } - if (isArray) { - const result = []; +module.exports = Transform; - for (let row of data) { - if ((typeof row === 'string')) { - row = this.opts.deserialize(row); - } +var Duplex = __nccwpck_require__(2063); - if (row === undefined || row === null) { - result.push(undefined); - continue; - } +/**/ +var util = Object.create(__nccwpck_require__(5481)); +util.inherits = __nccwpck_require__(9598); +/**/ - if (typeof row.expires === 'number' && Date.now() > row.expires) { - this.delete(key).then(() => undefined); - result.push(undefined); - } else { - result.push((options && options.raw) ? row : row.value); - } - } +util.inherits(Transform, Duplex); - return result; - } +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; - if (typeof data.expires === 'number' && Date.now() > data.expires) { - return this.delete(key).then(() => undefined); - } + var cb = ts.writecb; - return (options && options.raw) ? data : data.value; - }); - } + if (!cb) { + return this.emit('error', new Error('write callback called multiple times')); + } - set(key, value, ttl) { - const keyPrefixed = this._getKeyPrefix(key); - if (typeof ttl === 'undefined') { - ttl = this.opts.ttl; - } + ts.writechunk = null; + ts.writecb = null; - if (ttl === 0) { - ttl = undefined; - } + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); - const {store} = this.opts; + cb(er); - return Promise.resolve() - .then(() => { - const expires = (typeof ttl === 'number') ? (Date.now() + ttl) : null; - if (typeof value === 'symbol') { - this.emit('error', 'symbol cannot be serialized'); - } + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } +} - value = {value, expires}; - return this.opts.serialize(value); - }) - .then(value => store.set(keyPrefixed, value, ttl)) - .then(() => true); - } +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); - delete(key) { - const {store} = this.opts; - if (Array.isArray(key)) { - const keyPrefixed = this._getKeyPrefixArray(key); - if (store.deleteMany === undefined) { - const promises = []; - for (const key of keyPrefixed) { - promises.push(store.delete(key)); - } + Duplex.call(this, options); - return Promise.allSettled(promises) - .then(values => values.every(x => x.value === true)); - } - - return Promise.resolve() - .then(() => store.deleteMany(keyPrefixed)); - } + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; - const keyPrefixed = this._getKeyPrefix(key); - return Promise.resolve() - .then(() => store.delete(keyPrefixed)); - } + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; - clear() { - const {store} = this.opts; - return Promise.resolve() - .then(() => store.clear()); - } + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; - has(key) { - const keyPrefixed = this._getKeyPrefix(key); - const {store} = this.opts; - return Promise.resolve() - .then(async () => { - if (typeof store.has === 'function') { - return store.has(keyPrefixed); - } + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; - const value = await store.get(keyPrefixed); - return value !== undefined; - }); - } + if (typeof options.flush === 'function') this._flush = options.flush; + } - disconnect() { - const {store} = this.opts; - if (typeof store.disconnect === 'function') { - return store.disconnect(); - } - } + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); } -module.exports = Keyv; +function prefinish() { + var _this = this; + if (typeof this._flush === 'function') { + 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); +}; -/***/ 1360: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('_transform() is not implemented'); +}; +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); + } +}; +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; -var listenerCount = (__nccwpck_require__(2361).listenerCount) -// listenerCount isn't in node 0.10, so here's a basic polyfill -listenerCount = listenerCount || function (ee, event) { - var listeners = ee && ee._events && ee._events[event] - if (Array.isArray(listeners)) { - return listeners.length - } else if (typeof listeners === 'function') { - return 1 + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); } else { - return 0 + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; } -} - -module.exports = listenerCount +}; +Transform.prototype._destroy = function (err, cb) { + var _this2 = this; -/***/ }), + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + _this2.emit('close'); + }); +}; -/***/ 3973: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function done(stream, er, data) { + if (er) return stream.emit('error', er); -module.exports = minimatch -minimatch.Minimatch = Minimatch + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); -var path = (function () { try { return __nccwpck_require__(1017) } catch (e) {}}()) || { - sep: '/' -} -minimatch.sep = path.sep + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); -var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} -var expand = __nccwpck_require__(3717) + if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); -var plTypes = { - '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, - '?': { open: '(?:', close: ')?' }, - '+': { open: '(?:', close: ')+' }, - '*': { open: '(?:', close: ')*' }, - '@': { open: '(?:', close: ')' } + return stream.push(null); } -// any single thing other than / -// don't need to escape / when using new RegExp() -var qmark = '[^/]' +/***/ }), + +/***/ 8797: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// * => any number of characters -var star = qmark + '*?' +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. -// ** when dots are allowed. Anything goes, except .. and . -// not (^ or / followed by one or two dots followed by $ or /), -// followed by anything, any number of times. -var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. -// not a ^ or / followed by a dot, -// followed by anything, any number of times. -var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' -// characters that need to be escaped in RegExp. -var reSpecials = charSet('().*{}+?[]^$\\!') -// "abc" -> { a:true, b:true, c:true } -function charSet (s) { - return s.split('').reduce(function (set, c) { - set[c] = true - return set - }, {}) -} +/**/ -// normalizes slashes. -var slashSplit = /\/+/ +var pna = __nccwpck_require__(1564); +/**/ -minimatch.filter = filter -function filter (pattern, options) { - options = options || {} - return function (p, i, list) { - return minimatch(p, pattern, options) - } -} +module.exports = Writable; -function ext (a, b) { - b = b || {} - var t = {} - Object.keys(a).forEach(function (k) { - t[k] = a[k] - }) - Object.keys(b).forEach(function (k) { - t[k] = b[k] - }) - return t +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; } -minimatch.defaults = function (def) { - if (!def || typeof def !== 'object' || !Object.keys(def).length) { - return minimatch - } +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; - var orig = minimatch + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ - var m = function minimatch (p, pattern, options) { - return orig(p, pattern, ext(def, options)) - } +/**/ +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; +/**/ - m.Minimatch = function Minimatch (pattern, options) { - return new orig.Minimatch(pattern, ext(def, options)) - } - m.Minimatch.defaults = function defaults (options) { - return orig.defaults(ext(def, options)).Minimatch - } +/**/ +var Duplex; +/**/ - m.filter = function filter (pattern, options) { - return orig.filter(pattern, ext(def, options)) - } +Writable.WritableState = WritableState; - m.defaults = function defaults (options) { - return orig.defaults(ext(def, options)) - } +/**/ +var util = Object.create(__nccwpck_require__(5481)); +util.inherits = __nccwpck_require__(9598); +/**/ - m.makeRe = function makeRe (pattern, options) { - return orig.makeRe(pattern, ext(def, options)) - } +/**/ +var internalUtil = { + deprecate: __nccwpck_require__(4488) +}; +/**/ - m.braceExpand = function braceExpand (pattern, options) { - return orig.braceExpand(pattern, ext(def, options)) - } +/**/ +var Stream = __nccwpck_require__(3283); +/**/ - m.match = function (list, pattern, options) { - return orig.match(list, pattern, ext(def, options)) - } +/**/ - return m +var Buffer = (__nccwpck_require__(3058).Buffer); +var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); } - -Minimatch.defaults = function (def) { - return minimatch.defaults(def).Minimatch +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } -function minimatch (p, pattern, options) { - assertValidPattern(pattern) - - if (!options) options = {} - - // shortcut: comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - return false - } +/**/ - return new Minimatch(pattern, options).match(p) -} +var destroyImpl = __nccwpck_require__(5089); -function Minimatch (pattern, options) { - if (!(this instanceof Minimatch)) { - return new Minimatch(pattern, options) - } +util.inherits(Writable, Stream); - assertValidPattern(pattern) +function nop() {} - if (!options) options = {} +function WritableState(options, stream) { + Duplex = Duplex || __nccwpck_require__(2063); - pattern = pattern.trim() + options = options || {}; - // windows support: need to use /, not \ - if (!options.allowWindowsEscape && path.sep !== '/') { - pattern = pattern.split(path.sep).join('/') - } + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; - this.options = options - this.set = [] - this.pattern = pattern - this.regexp = null - this.negate = false - this.comment = false - this.empty = false - this.partial = !!options.partial + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; - // make the set of regexps etc. - this.make() -} + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; -Minimatch.prototype.debug = function () {} + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var writableHwm = options.writableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; -Minimatch.prototype.make = make -function make () { - var pattern = this.pattern - var options = this.options + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; - // empty patterns and comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - this.comment = true - return - } - if (!pattern) { - this.empty = true - return - } + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); - // step 1: figure out negation, etc. - this.parseNegate() + // if _final has been called + this.finalCalled = false; - // step 2: expand braces - var set = this.globSet = this.braceExpand() + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; - if (options.debug) this.debug = function debug() { console.error.apply(console, arguments) } + // has it been destroyed + this.destroyed = false; - this.debug(this.pattern, set) - - // step 3: now we have a set, so turn each one into a series of path-portion - // matching patterns. - // These will be regexps, except in the case of "**", which is - // set to the GLOBSTAR object for globstar behavior, - // and will not contain any / characters - set = this.globParts = set.map(function (s) { - return s.split(slashSplit) - }) - - this.debug(this.pattern, set) - - // glob --> regexps - set = set.map(function (s, si, set) { - return s.map(this.parse, this) - }, this) + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; - this.debug(this.pattern, set) + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; - // filter out everything that didn't compile properly. - set = set.filter(function (s) { - return s.indexOf(false) === -1 - }) + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; - this.debug(this.pattern, set) + // a flag to see when we're in the middle of a write. + this.writing = false; - this.set = set -} + // when true all writes will be buffered until .uncork() call + this.corked = 0; -Minimatch.prototype.parseNegate = parseNegate -function parseNegate () { - var pattern = this.pattern - var negate = false - var options = this.options - var negateOffset = 0 + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; - if (options.nonegate) return + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; - for (var i = 0, l = pattern.length - ; i < l && pattern.charAt(i) === '!' - ; i++) { - negate = !negate - negateOffset++ - } + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; - if (negateOffset) this.pattern = pattern.substr(negateOffset) - this.negate = negate -} + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; -// Brace expansion: -// a{b,c}d -> abd acd -// a{b,}c -> abc ac -// a{0..3}d -> a0d a1d a2d a3d -// a{b,c{d,e}f}g -> abg acdfg acefg -// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg -// -// Invalid sets are not expanded. -// a{2..}b -> a{2..}b -// a{b}c -> a{b}c -minimatch.braceExpand = function (pattern, options) { - return braceExpand(pattern, options) -} + // the amount that is being written when _write is called. + this.writelen = 0; -Minimatch.prototype.braceExpand = braceExpand + this.bufferedRequest = null; + this.lastBufferedRequest = null; -function braceExpand (pattern, options) { - if (!options) { - if (this instanceof Minimatch) { - options = this.options - } else { - options = {} - } - } + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; - pattern = typeof pattern === 'undefined' - ? this.pattern : pattern + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; - assertValidPattern(pattern) + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; - // Thanks to Yeting Li for - // improving this regexp to avoid a ReDOS vulnerability. - if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { - // shortcut. no need to expand. - return [pattern] - } + // count buffered requests + this.bufferedRequestCount = 0; - return expand(pattern) + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); } -var MAX_PATTERN_LENGTH = 1024 * 64 -var assertValidPattern = function (pattern) { - if (typeof pattern !== 'string') { - throw new TypeError('invalid pattern') - } - - if (pattern.length > MAX_PATTERN_LENGTH) { - throw new TypeError('pattern is too long') +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; } -} + return out; +}; -// parse a component of the expanded set. -// At this point, no pattern may contain "/" in it -// so we're going to return a 2d array, where each entry is the full -// pattern, split on '/', and then turned into a regular expression. -// A regexp is made at the end which joins each array with an -// escaped /, and another full one which joins each regexp with |. -// -// Following the lead of Bash 4.1, note that "**" only has special meaning -// when it is the *only* thing in a path portion. Otherwise, any series -// of * is equivalent to a single *. Globstar behavior is enabled by -// default, and can be disabled by setting options.noglobstar. -Minimatch.prototype.parse = parse -var SUBPARSE = {} -function parse (pattern, isSub) { - assertValidPattern(pattern) - - var options = this.options - - // shortcuts - if (pattern === '**') { - if (!options.noglobstar) - return GLOBSTAR - else - pattern = '*' - } - if (pattern === '') return '' - - var re = '' - var hasMagic = !!options.nocase - var escaping = false - // ? => one single character - var patternListStack = [] - var negativeLists = [] - var stateChar - var inClass = false - var reClassStart = -1 - var classStart = -1 - // . and .. never match anything that doesn't start with ., - // even when options.dot is set. - var patternStart = pattern.charAt(0) === '.' ? '' // anything - // not (start or / followed by . or .. followed by / or end) - : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' - : '(?!\\.)' - var self = this - - function clearStateChar () { - if (stateChar) { - // we had some state-tracking character - // that wasn't consumed by this pass. - switch (stateChar) { - case '*': - re += star - hasMagic = true - break - case '?': - re += qmark - hasMagic = true - break - default: - re += '\\' + stateChar - break - } - self.debug('clearStateChar %j %j', stateChar, re) - stateChar = false - } - } +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); - for (var i = 0, len = pattern.length, c - ; (i < len) && (c = pattern.charAt(i)) - ; i++) { - this.debug('%s\t%s %s %j', pattern, i, re, c) +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function (object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; - // skip over any that are escaped. - if (escaping && reSpecials[c]) { - re += '\\' + c - escaping = false - continue + return object && object._writableState instanceof WritableState; } + }); +} else { + realHasInstance = function (object) { + return object instanceof this; + }; +} - switch (c) { - /* istanbul ignore next */ - case '/': { - // completely not allowed, even escaped. - // Should already be path-split by now. - return false - } - - case '\\': - clearStateChar() - escaping = true - continue - - // the various stateChar values - // for the "extglob" stuff. - case '?': - case '*': - case '+': - case '@': - case '!': - this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) - - // all of those are literals inside a class, except that - // the glob [!a] means [^a] in regexp - if (inClass) { - this.debug(' in class') - if (c === '!' && i === classStart + 1) c = '^' - re += c - continue - } - - // if we already have a stateChar, then it means - // that there was something like ** or +? in there. - // Handle the stateChar, then proceed with this one. - self.debug('call clearStateChar %j', stateChar) - clearStateChar() - stateChar = c - // if extglob is disabled, then +(asdf|foo) isn't a thing. - // just clear the statechar *now*, rather than even diving into - // the patternList stuff. - if (options.noext) clearStateChar() - continue - - case '(': - if (inClass) { - re += '(' - continue - } - - if (!stateChar) { - re += '\\(' - continue - } - - patternListStack.push({ - type: stateChar, - start: i - 1, - reStart: re.length, - open: plTypes[stateChar].open, - close: plTypes[stateChar].close - }) - // negation is (?:(?!js)[^/]*) - re += stateChar === '!' ? '(?:(?!(?:' : '(?:' - this.debug('plType %j %j', stateChar, re) - stateChar = false - continue - - case ')': - if (inClass || !patternListStack.length) { - re += '\\)' - continue - } +function Writable(options) { + Duplex = Duplex || __nccwpck_require__(2063); - clearStateChar() - hasMagic = true - var pl = patternListStack.pop() - // negation is (?:(?!js)[^/]*) - // The others are (?:) - re += pl.close - if (pl.type === '!') { - negativeLists.push(pl) - } - pl.reEnd = re.length - continue + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. - case '|': - if (inClass || !patternListStack.length || escaping) { - re += '\\|' - escaping = false - continue - } + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { + return new Writable(options); + } - clearStateChar() - re += '|' - continue + this._writableState = new WritableState(options, this); - // these are mostly the same in regexp and glob - case '[': - // swallow any state-tracking char before the [ - clearStateChar() + // legacy. + this.writable = true; - if (inClass) { - re += '\\' + c - continue - } + if (options) { + if (typeof options.write === 'function') this._write = options.write; - inClass = true - classStart = i - reClassStart = re.length - re += c - continue + if (typeof options.writev === 'function') this._writev = options.writev; - case ']': - // a right bracket shall lose its special - // meaning and represent itself in - // a bracket expression if it occurs - // first in the list. -- POSIX.2 2.8.3.2 - if (i === classStart + 1 || !inClass) { - re += '\\' + c - escaping = false - continue - } + if (typeof options.destroy === 'function') this._destroy = options.destroy; - // handle the case where we left a class open. - // "[z-a]" is valid, equivalent to "\[z-a\]" - // split where the last [ was, make sure we don't have - // an invalid re. if so, re-walk the contents of the - // would-be class to re-translate any characters that - // were passed through as-is - // TODO: It would probably be faster to determine this - // without a try/catch and a new RegExp, but it's tricky - // to do safely. For now, this is safe and works. - var cs = pattern.substring(classStart + 1, i) - try { - RegExp('[' + cs + ']') - } catch (er) { - // not a valid class! - var sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' - hasMagic = hasMagic || sp[1] - inClass = false - continue - } + if (typeof options.final === 'function') this._final = options.final; + } - // finish up the class. - hasMagic = true - inClass = false - re += c - continue + Stream.call(this); +} - default: - // swallow any state char that wasn't consumed - clearStateChar() - - if (escaping) { - // no need - escaping = false - } else if (reSpecials[c] - && !(c === '^' && inClass)) { - re += '\\' - } - - re += c - - } // switch - } // for - - // handle the case where we left a class open. - // "[abc" is valid, equivalent to "\[abc" - if (inClass) { - // split where the last [ was, and escape it - // this is a huge pita. We now have to re-walk - // the contents of the would-be class to re-translate - // any characters that were passed through as-is - cs = pattern.substr(classStart + 1) - sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] - hasMagic = hasMagic || sp[1] - } - - // handle the case where we had a +( thing at the *end* - // of the pattern. - // each pattern list stack adds 3 chars, and we need to go through - // and escape any | chars that were passed through as-is for the regexp. - // Go through and escape them, taking care not to double-escape any - // | chars that were already escaped. - for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { - var tail = re.slice(pl.reStart + pl.open.length) - this.debug('setting tail', re, pl) - // maybe some even number of \, then maybe 1 \, followed by a | - tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { - if (!$2) { - // the | isn't already escaped, so escape it. - $2 = '\\' - } - - // need to escape all those slashes *again*, without escaping the - // one that we need for escaping the | character. As it works out, - // escaping an even number of slashes can be done by simply repeating - // it exactly after itself. That's why this trick works. - // - // I am sorry that you have to see this. - return $1 + $1 + $2 + '|' - }) +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; - this.debug('tail=%j\n %s', tail, tail, pl, re) - var t = pl.type === '*' ? star - : pl.type === '?' ? qmark - : '\\' + pl.type +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + pna.nextTick(cb, er); +} - hasMagic = true - re = re.slice(0, pl.reStart) + t + '\\(' + tail - } +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; - // handle trailing things that only matter at the very end. - clearStateChar() - if (escaping) { - // trailing \\ - re += '\\\\' + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); } - - // only need to apply the nodot start if the re starts with - // something that could conceivably capture a dot - var addPatternStart = false - switch (re.charAt(0)) { - case '[': case '.': case '(': addPatternStart = true + if (er) { + stream.emit('error', er); + pna.nextTick(cb, er); + valid = false; } + return valid; +} - // Hack to work around lack of negative lookbehind in JS - // A pattern like: *.!(x).!(y|z) needs to ensure that a name - // like 'a.xyz.yz' doesn't match. So, the first negative - // lookahead, has to look ALL the way ahead, to the end of - // the pattern. - for (var n = negativeLists.length - 1; n > -1; n--) { - var nl = negativeLists[n] - - var nlBefore = re.slice(0, nl.reStart) - var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) - var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) - var nlAfter = re.slice(nl.reEnd) - - nlLast += nlAfter - - // Handle nested stuff like *(*.js|!(*.json)), where open parens - // mean that we should *not* include the ) in the bit that is considered - // "after" the negated section. - var openParensBefore = nlBefore.split('(').length - 1 - var cleanAfter = nlAfter - for (i = 0; i < openParensBefore; i++) { - cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') - } - nlAfter = cleanAfter - - var dollar = '' - if (nlAfter === '' && isSub !== SUBPARSE) { - dollar = '$' - } - var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast - re = newRe - } +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); - // if the re is not "" at this point, then we need to make sure - // it doesn't match against an empty path part. - // Otherwise a/* will match a/, which it should not. - if (re !== '' && hasMagic) { - re = '(?=.)' + re + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); } - if (addPatternStart) { - re = patternStart + re + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; } - // parsing just a piece of a larger pattern. - if (isSub === SUBPARSE) { - return [re, hasMagic] - } + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - // skip the regexp for non-magical patterns - // unescape anything in it, though, so that it'll be - // an exact match against a file etc. - if (!hasMagic) { - return globUnescape(pattern) - } + if (typeof cb !== 'function') cb = nop; - var flags = options.nocase ? 'i' : '' - try { - var regExp = new RegExp('^' + re + '$', flags) - } catch (er) /* istanbul ignore next - should be impossible */ { - // If it was an invalid regular expression, then it can't match - // anything. This trick looks for a character after the end of - // the string, which is of course impossible, except in multi-line - // mode, but it's not a /m regex. - return new RegExp('$.') + if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); } - regExp._glob = pattern - regExp._src = re + return ret; +}; - return regExp -} +Writable.prototype.cork = function () { + var state = this._writableState; -minimatch.makeRe = function (pattern, options) { - return new Minimatch(pattern, options || {}).makeRe() -} + state.corked++; +}; -Minimatch.prototype.makeRe = makeRe -function makeRe () { - if (this.regexp || this.regexp === false) return this.regexp +Writable.prototype.uncork = function () { + var state = this._writableState; - // at this point, this.set is a 2d array of partial - // pattern strings, or "**". - // - // It's better to use .match(). This function shouldn't - // be used, really, but it's pretty convenient sometimes, - // when you just want to work with a regex. - var set = this.set + if (state.corked) { + state.corked--; - if (!set.length) { - this.regexp = false - return this.regexp + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); } - var options = this.options - - var twoStar = options.noglobstar ? star - : options.dot ? twoStarDot - : twoStarNoDot - var flags = options.nocase ? 'i' : '' - - var re = set.map(function (pattern) { - return pattern.map(function (p) { - return (p === GLOBSTAR) ? twoStar - : (typeof p === 'string') ? regExpEscape(p) - : p._src - }).join('\\\/') - }).join('|') - - // must match entire pattern - // ending in a * or ** will make it less strict. - re = '^(?:' + re + ')$' - - // can match anything, as long as it's not this. - if (this.negate) re = '^(?!' + re + ').*$' +}; - try { - this.regexp = new RegExp(re, flags) - } catch (ex) /* istanbul ignore next - should be impossible */ { - this.regexp = false - } - return this.regexp -} +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + 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 TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; -minimatch.match = function (list, pattern, options) { - options = options || {} - var mm = new Minimatch(pattern, options) - list = list.filter(function (f) { - return mm.match(f) - }) - if (mm.options.nonull && !list.length) { - list.push(pattern) +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); } - return list + return chunk; } -Minimatch.prototype.match = function match (f, partial) { - if (typeof partial === 'undefined') partial = this.partial - this.debug('match', f, this.pattern) - // short-circuit in the case of busted things. - // comments, etc. - if (this.comment) return false - if (this.empty) return f === '' - - if (f === '/' && partial) return true - - var options = this.options - - // windows: need to use /, not \ - if (path.sep !== '/') { - f = f.split(path.sep).join('/') - } - - // treat the test path as a set of pathparts. - f = f.split(slashSplit) - this.debug(this.pattern, 'split', f) - - // just ONE of the pattern sets in this.set needs to match - // in order for it to be valid. If negating, then just one - // match means that we have failed. - // Either way, return on the first hit. - - var set = this.set - this.debug(this.pattern, 'set', set) - - // Find the basename of the path by looking for the last non-empty segment - var filename - var i - for (i = f.length - 1; i >= 0; i--) { - filename = f[i] - if (filename) break - } - - for (i = 0; i < set.length; i++) { - var pattern = set[i] - var file = f - if (options.matchBase && pattern.length === 1) { - file = [filename] - } - var hit = this.matchOne(file, pattern, partial) - if (hit) { - if (options.flipNegate) return true - return !this.negate - } - } - - // didn't get any hits. this is success if it's a negative - // pattern, failure otherwise. - if (options.flipNegate) return false - return this.negate -} - -// set partial to true to test if, for example, -// "/a/b" matches the start of "/*/b/*/d" -// Partial means, if you run out of file before you run -// out of pattern, then that's fine, as long as all -// the parts match. -Minimatch.prototype.matchOne = function (file, pattern, partial) { - var options = this.options - - this.debug('matchOne', - { 'this': this, file: file, pattern: pattern }) - - this.debug('matchOne', file.length, pattern.length) - - for (var fi = 0, - pi = 0, - fl = file.length, - pl = pattern.length - ; (fi < fl) && (pi < pl) - ; fi++, pi++) { - this.debug('matchOne loop') - var p = pattern[pi] - var f = file[fi] - - this.debug(pattern, p, f) - - // should be impossible. - // some invalid regexp stuff in the set. - /* istanbul ignore if */ - if (p === false) return false - - if (p === GLOBSTAR) { - this.debug('GLOBSTAR', [pattern, p, f]) - - // "**" - // a/**/b/**/c would match the following: - // a/b/x/y/z/c - // a/x/y/z/b/c - // a/b/x/b/x/c - // a/b/c - // To do this, take the rest of the pattern after - // the **, and see if it would match the file remainder. - // If so, return success. - // If not, the ** "swallows" a segment, and try again. - // This is recursively awful. - // - // a/**/b/**/c matching a/b/x/y/z/c - // - a matches a - // - doublestar - // - matchOne(b/x/y/z/c, b/**/c) - // - b matches b - // - doublestar - // - matchOne(x/y/z/c, c) -> no - // - matchOne(y/z/c, c) -> no - // - matchOne(z/c, c) -> no - // - matchOne(c, c) yes, hit - var fr = fi - var pr = pi + 1 - if (pr === pl) { - this.debug('** at the end') - // a ** at the end will just swallow the rest. - // We have found a match. - // however, it will not swallow /.x, unless - // options.dot is set. - // . and .. are *never* matched by **, for explosively - // exponential reasons. - for (; fi < fl; fi++) { - if (file[fi] === '.' || file[fi] === '..' || - (!options.dot && file[fi].charAt(0) === '.')) return false - } - return true - } - - // ok, let's see if we can swallow whatever we can. - while (fr < fl) { - var swallowee = file[fr] - - this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); - // XXX remove this slice. Just pass the start index. - if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { - this.debug('globstar found match!', fr, fl, swallowee) - // found a match. - return true - } else { - // can't swallow "." or ".." ever. - // can only swallow ".foo" when explicitly asked. - if (swallowee === '.' || swallowee === '..' || - (!options.dot && swallowee.charAt(0) === '.')) { - this.debug('dot detected!', file, fr, pattern, pr) - break - } +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, 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; - // ** swallows a segment, and continue. - this.debug('globstar swallow a segment, and continue') - fr++ - } - } + state.length += len; - // no match was found. - // However, in partial mode, we can't say this is necessarily over. - // If there's more *pattern* left, then - /* istanbul ignore if */ - if (partial) { - // ran out of file - this.debug('\n>>> no match, partial?', file, fr, pattern, pr) - if (fr === fl) return true - } - return false - } + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; - // something other than ** - // non-magic patterns just have to match exactly - // patterns with magic have been turned into regexps. - var hit - if (typeof p === 'string') { - hit = f === p - this.debug('string match', p, f, hit) + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; } else { - hit = f.match(p) - this.debug('pattern match', p, f, hit) + state.bufferedRequest = state.lastBufferedRequest; } - - if (!hit) return false + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); } - // Note: ending in / means that we'll get a final "" - // at the end of the pattern. This can only match a - // corresponding "" at the end of the file. - // If the file ends in /, then it can only match a - // a pattern that ends in /, unless the pattern just - // doesn't have any more for it. But, a/b/ should *not* - // match "a/b/*", even though "" matches against the - // [^/]*? pattern, except in partial mode, where it might - // simply not be reached yet. - // However, a/b/ should still satisfy a/* - - // now either we fell off the end of the pattern, or we're done. - if (fi === fl && pi === pl) { - // ran out of pattern and filename at the same time. - // an exact hit! - return true - } else if (fi === fl) { - // ran out of file, but still had pattern left. - // this is ok if we're doing the match as part of - // a glob fs traversal. - return partial - } else /* istanbul ignore else */ if (pi === pl) { - // ran out of pattern, still have file left. - // this is only acceptable if we're on the very last - // empty segment of a file with a trailing slash. - // a/* should match a/b/ - return (fi === fl - 1) && (file[fi] === '') - } - - // should be unreachable. - /* istanbul ignore next */ - throw new Error('wtf?') -} - -// replace stuff like \* with * -function globUnescape (s) { - return s.replace(/\\(.)/g, '$1') + return ret; } -function regExpEscape (s) { - return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; } +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; -/***/ }), - -/***/ 6186: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var path = __nccwpck_require__(1017); -var fs = __nccwpck_require__(7147); -var _0777 = parseInt('0777', 8); - -module.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 || fs; - - if (mode === undefined) { - mode = _0777 - } - if (!made) made = null; - - var cb = f || /* istanbul ignore next */ 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': - /* istanbul ignore if */ - if (path.dirname(p) === p) return cb(er); - mkdirP(path.dirname(p), opts, function (er, made) { - /* istanbul ignore if */ - if (er) cb(er, made); - else mkdirP(p, opts, cb, made); - }); - break; + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + pna.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + pna.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } +} - // 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 the stat fails, then that's super weird. - // let the original error be the failure reason. - if (er2 || !stat.isDirectory()) cb(er, made) - else cb(null, made); - }); - break; - } - }); +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; } -mkdirP.sync = function sync (p, opts, made) { - if (!opts || typeof opts !== 'object') { - opts = { mode: opts }; - } - - var mode = opts.mode; - var xfs = opts.fs || fs; - - if (mode === undefined) { - mode = _0777 - } - if (!made) made = null; +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; - p = path.resolve(p); + onwriteStateUpdate(state); - 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; + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); - // 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) /* istanbul ignore next */ { - throw err0; - } - /* istanbul ignore if */ - if (!stat.isDirectory()) throw err0; - break; - } + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); } - return made; -}; - - -/***/ }), - -/***/ 1223: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var wrappy = __nccwpck_require__(2940) -module.exports = wrappy(once) -module.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) + if (sync) { + /**/ + asyncWrite(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } } - 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) +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); } - var name = fn.name || 'Function wrapped with `once`' - f.onceError = name + " shouldn't be called more than once" - f.called = false - return f } +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; -/***/ }), + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; -/***/ 8714: -/***/ ((module) => { + 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(stream, state, true, state.length, buffer, '', holder.finish); + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + 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 { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; -function posix(path) { - return path.charAt(0) === '/'; -} + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } -function win32(path) { - // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 - var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; - var result = splitDeviceRe.exec(path); - var device = result[1] || ''; - var isUnc = Boolean(device && device.charAt(1) !== ':'); + if (entry === null) state.lastBufferedRequest = null; + } - // UNC paths are always absolute - return Boolean(result[2] || isUnc); + state.bufferedRequest = entry; + state.bufferProcessing = false; } -module.exports = process.platform === 'win32' ? win32 : posix; -module.exports.posix = posix; -module.exports.win32 = win32; +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('_write() is not implemented')); +}; +Writable.prototype._writev = null; -/***/ }), +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; -/***/ 7810: -/***/ ((module) => { + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } -if (typeof process === 'undefined' || - !process.version || - process.version.indexOf('v0.') === 0 || - process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { - module.exports = { nextTick: nextTick }; -} else { - module.exports = process -} + // ignore unnecessary end() calls. + if (!state.ending) endWritable(this, state, cb); +}; -function nextTick(fn, arg1, arg2, arg3) { - if (typeof fn !== 'function') { - throw new TypeError('"callback" argument must be a function'); +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + stream.emit('error', err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function') { + state.pendingcb++; + state.finalCalled = true; + pna.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } } - var len = arguments.length; - var args, i; - switch (len) { - case 0: - case 1: - return process.nextTick(fn); - case 2: - return process.nextTick(function afterTickOne() { - fn.call(null, arg1); - }); - case 3: - return process.nextTick(function afterTickTwo() { - fn.call(null, arg1, arg2); - }); - case 4: - return process.nextTick(function afterTickThree() { - fn.call(null, arg1, arg2, arg3); - }); - default: - args = new Array(len - 1); - i = 0; - while (i < args.length) { - args[i++] = arguments[i]; +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); } - return process.nextTick(function afterTick() { - fn.apply(null, args); - }); } + return need; } +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.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; + } -/***/ }), + // reuse the free corkReq. + state.corkedRequestsFree.next = corkReq; +} -/***/ 9273: -/***/ ((module) => { +Object.defineProperty(Writable.prototype, 'destroyed', { + get: function () { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + this.end(); + cb(err); +}; -class QuickLRU { - constructor(options = {}) { - if (!(options.maxSize && options.maxSize > 0)) { - throw new TypeError('`maxSize` must be a number greater than 0'); - } +/***/ }), - this.maxSize = options.maxSize; - this.onEviction = options.onEviction; - this.cache = new Map(); - this.oldCache = new Map(); - this._size = 0; - } +/***/ 9381: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _set(key, value) { - this.cache.set(key, value); - this._size++; - if (this._size >= this.maxSize) { - this._size = 0; - if (typeof this.onEviction === 'function') { - for (const [key, value] of this.oldCache.entries()) { - this.onEviction(key, value); - } - } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - this.oldCache = this.cache; - this.cache = new Map(); - } - } +var Buffer = (__nccwpck_require__(3058).Buffer); +var util = __nccwpck_require__(9023); - get(key) { - if (this.cache.has(key)) { - return this.cache.get(key); - } +function copyBuffer(src, target, offset) { + src.copy(target, offset); +} - if (this.oldCache.has(key)) { - const value = this.oldCache.get(key); - this.oldCache.delete(key); - this._set(key, value); - return value; - } - } +module.exports = function () { + function BufferList() { + _classCallCheck(this, BufferList); - set(key, value) { - if (this.cache.has(key)) { - this.cache.set(key, value); - } else { - this._set(key, value); - } + this.head = null; + this.tail = null; + this.length = 0; + } - return this; - } + BufferList.prototype.push = 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; + }; - has(key) { - return this.cache.has(key) || this.oldCache.has(key); - } + BufferList.prototype.unshift = function unshift(v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; - peek(key) { - if (this.cache.has(key)) { - return this.cache.get(key); - } + BufferList.prototype.shift = function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; - if (this.oldCache.has(key)) { - return this.oldCache.get(key); - } - } + BufferList.prototype.clear = function clear() { + this.head = this.tail = null; + this.length = 0; + }; - delete(key) { - const deleted = this.cache.delete(key); - if (deleted) { - this._size--; - } + BufferList.prototype.join = 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; + }; - return this.oldCache.delete(key) || deleted; - } + BufferList.prototype.concat = function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + var ret = Buffer.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; + }; - clear() { - this.cache.clear(); - this.oldCache.clear(); - this._size = 0; - } + return BufferList; +}(); - * keys() { - for (const [key] of this) { - yield key; - } - } +if (util && util.inspect && util.inspect.custom) { + module.exports.prototype[util.inspect.custom] = function () { + var obj = util.inspect({ length: this.length }); + return this.constructor.name + ' ' + obj; + }; +} - * values() { - for (const [, value] of this) { - yield value; - } - } +/***/ }), - * [Symbol.iterator]() { - for (const item of this.cache) { - yield item; - } - - for (const item of this.oldCache) { - const [key] = item; - if (!this.cache.has(key)) { - yield item; - } - } - } - - get size() { - let oldCacheSize = 0; - for (const key of this.oldCache.keys()) { - if (!this.cache.has(key)) { - oldCacheSize++; - } - } - - return Math.min(this._size + oldCacheSize, this.maxSize); - } -} - -module.exports = QuickLRU; - - -/***/ }), - -/***/ 1359: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. +/***/ 5089: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /**/ -var pna = __nccwpck_require__(7810); -/**/ - -/**/ -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - keys.push(key); - }return keys; -}; +var pna = __nccwpck_require__(1564); /**/ -module.exports = Duplex; - -/**/ -var util = Object.create(__nccwpck_require__(5898)); -util.inherits = __nccwpck_require__(4124); -/**/ +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; -var Readable = __nccwpck_require__(1433); -var Writable = __nccwpck_require__(6993); + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; -util.inherits(Duplex, Readable); + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + pna.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + pna.nextTick(emitErrorNT, this, err); + } + } -{ - // avoid scope creep, the keys array can then be collected - var keys = objectKeys(Writable.prototype); - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + return this; } -} - -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable.call(this, options); - Writable.call(this, options); + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks - if (options && options.readable === false) this.readable = false; + if (this._readableState) { + this._readableState.destroyed = true; + } - if (options && options.writable === false) this.writable = false; + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + pna.nextTick(emitErrorNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + pna.nextTick(emitErrorNT, _this, err); + } + } else if (cb) { + cb(err); + } + }); - this.once('end', onend); + return this; } -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 () { - return this._writableState.highWaterMark; +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; } -}); -// the no-half-open enforcer -function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) return; - - // no more data can be written. - // But allow more writes to happen in this tick. - pna.nextTick(onEndNT, this); + 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 onEndNT(self) { - self.end(); +function emitErrorNT(self, err) { + self.emit('error', err); } -Object.defineProperty(Duplex.prototype, 'destroyed', { - get: function () { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } - - // backward compatibility, the user is explicitly - // managing destroyed - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } -}); - -Duplex.prototype._destroy = function (err, cb) { - this.push(null); - this.end(); - - pna.nextTick(cb, err); +module.exports = { + destroy: destroy, + undestroy: undestroy }; /***/ }), -/***/ 1542: +/***/ 3283: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. +module.exports = __nccwpck_require__(2203); -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. +/***/ }), +/***/ 6131: +/***/ ((module, exports, __nccwpck_require__) => { -module.exports = PassThrough; +var Stream = __nccwpck_require__(2203); +if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream; + exports = module.exports = Stream.Readable; + exports.Readable = Stream.Readable; + exports.Writable = Stream.Writable; + exports.Duplex = Stream.Duplex; + exports.Transform = Stream.Transform; + exports.PassThrough = Stream.PassThrough; + exports.Stream = Stream; +} else { + exports = module.exports = __nccwpck_require__(6893); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = __nccwpck_require__(8797); + exports.Duplex = __nccwpck_require__(2063); + exports.Transform = __nccwpck_require__(2337); + exports.PassThrough = __nccwpck_require__(5283); +} -var Transform = __nccwpck_require__(4415); -/**/ -var util = Object.create(__nccwpck_require__(5898)); -util.inherits = __nccwpck_require__(4124); -/**/ +/***/ }), -util.inherits(PassThrough, Transform); +/***/ 8824: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform.call(this, options); -} +const tls = __nccwpck_require__(4756); -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; +module.exports = (options = {}, connect = tls.connect) => new Promise((resolve, reject) => { + let timeout = false; -/***/ }), + let socket; -/***/ 1433: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + const callback = async () => { + await socketPromise; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - -/**/ + socket.off('timeout', onTimeout); + socket.off('error', reject); -var pna = __nccwpck_require__(7810); -/**/ + if (options.resolveSocket) { + resolve({alpnProtocol: socket.alpnProtocol, socket, timeout}); -module.exports = Readable; + if (timeout) { + await Promise.resolve(); + socket.emit('timeout'); + } + } else { + socket.destroy(); + resolve({alpnProtocol: socket.alpnProtocol, timeout}); + } + }; -/**/ -var isArray = __nccwpck_require__(893); -/**/ + const onTimeout = async () => { + timeout = true; + callback(); + }; -/**/ -var Duplex; -/**/ + const socketPromise = (async () => { + try { + socket = await connect(options, callback); -Readable.ReadableState = ReadableState; + socket.on('error', reject); + socket.once('timeout', onTimeout); + } catch (error) { + reject(error); + } + })(); +}); -/**/ -var EE = (__nccwpck_require__(2361).EventEmitter); -var EElistenerCount = function (emitter, type) { - return emitter.listeners(type).length; -}; -/**/ +/***/ }), -/**/ -var Stream = __nccwpck_require__(2387); -/**/ +/***/ 3058: +/***/ ((module, exports, __nccwpck_require__) => { -/**/ +/* eslint-disable node/no-deprecated-api */ +var buffer = __nccwpck_require__(181) +var Buffer = buffer.Buffer -var Buffer = (__nccwpck_require__(1867).Buffer); -var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } } - -/**/ - -/**/ -var util = Object.create(__nccwpck_require__(5898)); -util.inherits = __nccwpck_require__(4124); -/**/ - -/**/ -var debugUtil = __nccwpck_require__(3837); -var debug = void 0; -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer } else { - debug = function () {}; + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer } -/**/ -var BufferList = __nccwpck_require__(7053); -var destroyImpl = __nccwpck_require__(7049); -var StringDecoder; - -util.inherits(Readable, Stream); +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf } -function ReadableState(options, stream) { - Duplex = Duplex || __nccwpck_require__(1359); +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} - options = options || {}; +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} - // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - var isDuplex = stream instanceof Duplex; - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; +/***/ }), - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; +/***/ 634: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - var readableHwm = options.readableHighWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; - // cast to ints. - this.highWaterMark = Math.floor(this.highWaterMark); - // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - 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; +/**/ - // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - this.sync = true; +var Buffer = (__nccwpck_require__(3058).Buffer); +/**/ - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; +var isEncoding = Buffer.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; + } +}; - // has it been destroyed - this.destroyed = 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; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; - - // if true, a maybeReadMore has been scheduled - this.readingMore = false; - - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) StringDecoder = (__nccwpck_require__(4841)/* .StringDecoder */ .s); - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.I = 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 = Buffer.allocUnsafe(nb); } -function Readable(options) { - Duplex = Duplex || __nccwpck_require__(1359); - - if (!(this instanceof Readable)) return new Readable(options); - - this._readableState = new ReadableState(options, this); +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) 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 || ''; +}; - // legacy - this.readable = true; +StringDecoder.prototype.end = utf8End; - if (options) { - if (typeof options.read === 'function') this._read = options.read; +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; - if (typeof options.destroy === 'function') this._destroy = options.destroy; +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +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; +}; - Stream.call(this); +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; } -Object.defineProperty(Readable.prototype, 'destroyed', { - get: function () { - if (this._readableState === undefined) { - return false; - } - return this._readableState.destroyed; - }, - set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.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 self.lastNeed = nb - 3; } - - // backward compatibility, the user is explicitly - // managing destroyed - this._readableState.destroyed = value; + return nb; } -}); - -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; -Readable.prototype._destroy = function (err, cb) { - this.push(null); - cb(err); -}; - -// Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; + return 0; +} - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; } - skipChunkCheck = true; } - } else { - skipChunkCheck = true; } +} - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) 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; +} -// Unshift should *always* be something directly out of read() -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +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 readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - var state = stream._readableState; - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} - if (addToFront) { - if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); - } else if (state.ended) { - stream.emit('error', new Error('stream.push() after EOF')); - } else { - state.reading = false; - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +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 >= 0xD800 && c <= 0xDBFF) { + 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); } - } else if (!addToFront) { - state.reading = false; } + return r; } - - return needMoreData(state); + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); } -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - stream.emit('data', chunk); - stream.read(0); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - - if (state.needReadable) emitReadable(stream); +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +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); } - maybeReadMore(stream, state); + return r; } -function chunkInvalid(state, chunk) { - var er; - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); +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 er; + return buf.toString('base64', i, buf.length - n); } -// if it's past the high water mark, we can push in some more. -// Also, if we have no data yet, we can stand some -// more bytes. This is to work around cases where hwm=0, -// such as the repl. Also, if the push() triggered a -// readable event, and the user called read(largeNumber) such that -// needReadable was set, then we ought to push more, so that another -// 'readable' event will be triggered. -function needMoreData(state) { - return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +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; } -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; - -// backwards compatibility. -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = (__nccwpck_require__(4841)/* .StringDecoder */ .s); - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; - return this; -}; - -// Don't raise the hwm > 8MB -var MAX_HWM = 0x800000; -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - return n; +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); } -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } - // If we're asking for more than the current hwm, then raise the hwm. - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; - // Don't have enough - if (!state.ended) { - state.needReadable = true; - return 0; - } - return state.length; +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; } -// you can override either this method, or the async _read(n) below. -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - - if (n !== 0) state.emittedReadable = false; - - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); - - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } +/***/ }), - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. +/***/ 770: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug('need readable', doRead); +module.exports = __nccwpck_require__(218); - // if we currently have less than the highWaterMark, then also read some - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead(nOrig, state); - } +/***/ }), - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; +/***/ 218: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (ret === null) { - state.needReadable = true; - n = 0; - } else { - state.length -= n; - } - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable(this); - } +var net = __nccwpck_require__(9278); +var tls = __nccwpck_require__(4756); +var http = __nccwpck_require__(8611); +var https = __nccwpck_require__(5692); +var events = __nccwpck_require__(4434); +var assert = __nccwpck_require__(2613); +var util = __nccwpck_require__(9023); - if (ret !== null) this.emit('data', ret); - return ret; -}; +exports.httpOverHttp = httpOverHttp; +exports.httpsOverHttp = httpsOverHttp; +exports.httpOverHttps = httpOverHttps; +exports.httpsOverHttps = httpsOverHttps; -function onEofChunk(stream, state) { - 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; - // emit 'readable' now to make sure it gets picked up. - emitReadable(stream); +function httpOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http.request; + return agent; } -// Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. -function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); - } +function httpsOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http.request; + agent.createSocket = createSecureSocket; + agent.defaultPort = 443; + return agent; } -function emitReadable_(stream) { - debug('emit readable'); - stream.emit('readable'); - flow(stream); +function httpOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https.request; + return agent; } -// at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - pna.nextTick(maybeReadMore_, stream, state); - } +function httpsOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https.request; + agent.createSocket = createSecureSocket; + agent.defaultPort = 443; + return agent; } -function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break;else len = state.length; - } - state.readingMore = false; -} - -// abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. -Readable.prototype._read = function (n) { - this.emit('error', new Error('_read() is not implemented')); -}; - -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); +function TunnelingAgent(options) { + var self = this; + self.options = options || {}; + self.proxyOptions = self.options.proxy || {}; + self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; + self.requests = []; + self.sockets = []; - dest.on('unpipe', onunpipe); - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); + self.on('free', function onFree(socket, host, port, localAddress) { + var options = toOptions(host, port, localAddress); + for (var i = 0, len = self.requests.length; i < len; ++i) { + var pending = self.requests[i]; + if (pending.host === options.host && pending.port === options.port) { + // Detect the request to connect same origin server, + // reuse the connection. + self.requests.splice(i, 1); + pending.request.onSocket(socket); + return; } } - } + socket.destroy(); + self.removeSocket(socket); + }); +} +util.inherits(TunnelingAgent, events.EventEmitter); - function onend() { - debug('onend'); - dest.end(); +TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { + var self = this; + var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); + + if (self.sockets.length >= this.maxSockets) { + // We are over limit so we'll add it to the queue. + self.requests.push(options); + return; } - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); + // If we are under maxSockets create a new one. + self.createSocket(options, function(socket) { + socket.on('free', onFree); + socket.on('close', onCloseOrRemove); + socket.on('agentRemove', onCloseOrRemove); + req.onSocket(socket); - var cleanedUp = false; - function cleanup() { - debug('cleanup'); - // cleanup event handlers once the pipe is broken - 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); + function onFree() { + self.emit('free', socket, options); + } - cleanedUp = true; + function onCloseOrRemove(err) { + self.removeSocket(socket); + socket.removeListener('free', onFree); + socket.removeListener('close', onCloseOrRemove); + socket.removeListener('agentRemove', onCloseOrRemove); + } + }); +}; - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } +TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { + var self = this; + var placeholder = {}; + self.sockets.push(placeholder); - // If the user pushes more data while we're writing to dest then we'll end up - // in ondata again. However, we only want to increase awaitDrain once because - // dest will only emit one 'drain' event for the multiple writes. - // => Introduce a guard on increasing awaitDrain. - var increasedAwaitDrain = false; - src.on('data', ondata); - function ondata(chunk) { - debug('ondata'); - increasedAwaitDrain = false; - var ret = dest.write(chunk); - if (false === ret && !increasedAwaitDrain) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', state.awaitDrain); - state.awaitDrain++; - increasedAwaitDrain = true; - } - src.pause(); + var connectOptions = mergeOptions({}, self.proxyOptions, { + method: 'CONNECT', + path: options.host + ':' + options.port, + agent: false, + headers: { + host: options.host + ':' + options.port } + }); + if (options.localAddress) { + connectOptions.localAddress = options.localAddress; } - - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + if (connectOptions.proxyAuth) { + connectOptions.headers = connectOptions.headers || {}; + connectOptions.headers['Proxy-Authorization'] = 'Basic ' + + new Buffer(connectOptions.proxyAuth).toString('base64'); } - // Make sure our error handler is attached before userland ones. - prependListener(dest, 'error', onerror); + debug('making CONNECT request'); + var connectReq = self.request(connectOptions); + connectReq.useChunkedEncodingByDefault = false; // for v0.6 + connectReq.once('response', onResponse); // for v0.6 + connectReq.once('upgrade', onUpgrade); // for v0.6 + connectReq.once('connect', onConnect); // for v0.7 or later + connectReq.once('error', onError); + connectReq.end(); - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); + function onResponse(res) { + // Very hacky. This is necessary to avoid http-parser leaks. + res.upgrade = true; } - dest.once('finish', onfinish); - function unpipe() { - debug('unpipe'); - src.unpipe(dest); + function onUpgrade(res, socket, head) { + // Hacky. + process.nextTick(function() { + onConnect(res, socket, head); + }); } - // tell the dest that it's being piped to - dest.emit('pipe', src); + function onConnect(res, socket, head) { + connectReq.removeAllListeners(); + socket.removeAllListeners(); - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug('pipe resume'); - src.resume(); + if (res.statusCode !== 200) { + debug('tunneling socket could not be established, statusCode=%d', + res.statusCode); + socket.destroy(); + var error = new Error('tunneling socket could not be established, ' + + 'statusCode=' + res.statusCode); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + return; + } + if (head.length > 0) { + debug('got illegal response body from proxy'); + socket.destroy(); + var error = new Error('got illegal response body from proxy'); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + return; + } + debug('tunneling connection has established'); + self.sockets[self.sockets.indexOf(placeholder)] = socket; + return cb(socket); } - return dest; -}; + function onError(cause) { + connectReq.removeAllListeners(); -function pipeOnDrain(src) { - return function () { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} + debug('tunneling socket could not be established, cause=%s\n', + cause.message, cause.stack); + var error = new Error('tunneling socket could not be established, ' + + 'cause=' + cause.message); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + } +}; -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { hasUnpiped: false }; - - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) return this; - - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - - if (!dest) dest = state.pipes; - - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; +TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { + var pos = this.sockets.indexOf(socket) + if (pos === -1) { + return; } + this.sockets.splice(pos, 1); - // slow case. multiple pipe destinations. - - if (!dest) { - // remove all. - 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 pending = this.requests.shift(); + if (pending) { + // If we have pending requests and a socket gets closed a new one + // needs to be created to take over in the pool for the one that closed. + this.createSocket(pending, function(socket) { + pending.request.onSocket(socket); + }); } +}; - // try to find the right one. - 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]; +function createSecureSocket(options, cb) { + var self = this; + TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { + var hostHeader = options.request.getHeader('host'); + var tlsOptions = mergeOptions({}, self.options, { + socket: socket, + servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host + }); - dest.emit('unpipe', this, unpipeInfo); + // 0 is dummy port for v0.6 + var secureSocket = tls.connect(0, tlsOptions); + self.sockets[self.sockets.indexOf(socket)] = secureSocket; + cb(secureSocket); + }); +} - return this; -}; -// set up data events if they are asked for -// Ensure readable listeners eventually get something -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); +function toOptions(host, port, localAddress) { + if (typeof host === 'string') { // since v0.10 + return { + host: host, + port: port, + localAddress: localAddress + }; + } + return host; // for v0.11 or later +} - if (ev === 'data') { - // Start flowing on next tick if stream isn't explicitly paused - if (this._readableState.flowing !== false) this.resume(); - } else if (ev === 'readable') { - var state = this._readableState; - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.emittedReadable = false; - if (!state.reading) { - pna.nextTick(nReadingNextTick, this); - } else if (state.length) { - emitReadable(this); +function mergeOptions(target) { + for (var i = 1, len = arguments.length; i < len; ++i) { + var overrides = arguments[i]; + if (typeof overrides === 'object') { + var keys = Object.keys(overrides); + for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { + var k = keys[j]; + if (overrides[k] !== undefined) { + target[k] = overrides[k]; + } } } } - - return res; -}; -Readable.prototype.addListener = Readable.prototype.on; - -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); + return target; } -// pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. -Readable.prototype.resume = function () { - var state = this._readableState; - if (!state.flowing) { - debug('resume'); - state.flowing = true; - resume(this, state); - } - return this; -}; -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - pna.nextTick(resume_, stream, state); +var debug; +if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { + debug = function() { + var args = Array.prototype.slice.call(arguments); + if (typeof args[0] === 'string') { + args[0] = 'TUNNEL: ' + args[0]; + } else { + args.unshift('TUNNEL:'); + } + console.error.apply(console, args); } +} else { + debug = function() {}; } +exports.debug = debug; // for test -function resume_(stream, state) { - if (!state.reading) { - debug('resume read 0'); - stream.read(0); - } - state.resumeScheduled = false; - state.awaitDrain = 0; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} +/***/ }), -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - if (false !== this._readableState.flowing) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - return this; -}; +/***/ 6752: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - while (state.flowing && stream.read() !== null) {} + + +const Client = __nccwpck_require__(6197) +const Dispatcher = __nccwpck_require__(992) +const errors = __nccwpck_require__(8707) +const Pool = __nccwpck_require__(5076) +const BalancedPool = __nccwpck_require__(1093) +const Agent = __nccwpck_require__(9965) +const util = __nccwpck_require__(3440) +const { InvalidArgumentError } = errors +const api = __nccwpck_require__(6615) +const buildConnector = __nccwpck_require__(9136) +const MockClient = __nccwpck_require__(7365) +const MockAgent = __nccwpck_require__(7501) +const MockPool = __nccwpck_require__(4004) +const mockErrors = __nccwpck_require__(2429) +const ProxyAgent = __nccwpck_require__(2720) +const RetryHandler = __nccwpck_require__(3573) +const { getGlobalDispatcher, setGlobalDispatcher } = __nccwpck_require__(2581) +const DecoratorHandler = __nccwpck_require__(8840) +const RedirectHandler = __nccwpck_require__(8299) +const createRedirectInterceptor = __nccwpck_require__(4415) + +let hasCrypto +try { + __nccwpck_require__(6982) + hasCrypto = true +} catch { + hasCrypto = false } -// wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. -Readable.prototype.wrap = function (stream) { - var _this = this; +Object.assign(Dispatcher.prototype, api) - var state = this._readableState; - var paused = false; +module.exports.Dispatcher = Dispatcher +module.exports.Client = Client +module.exports.Pool = Pool +module.exports.BalancedPool = BalancedPool +module.exports.Agent = Agent +module.exports.ProxyAgent = ProxyAgent +module.exports.RetryHandler = RetryHandler - stream.on('end', function () { - debug('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); +module.exports.DecoratorHandler = DecoratorHandler +module.exports.RedirectHandler = RedirectHandler +module.exports.createRedirectInterceptor = createRedirectInterceptor + +module.exports.buildConnector = buildConnector +module.exports.errors = errors + +function makeDispatcher (fn) { + return (url, opts, handler) => { + if (typeof opts === 'function') { + handler = opts + opts = null } - _this.push(null); - }); + if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) { + throw new InvalidArgumentError('invalid url') + } - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); + if (opts != null && typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } - // don't skip over falsy values in objectMode - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + if (opts && opts.path != null) { + if (typeof opts.path !== 'string') { + throw new InvalidArgumentError('invalid opts.path') + } - var ret = _this.push(chunk); - if (!ret) { - paused = true; - stream.pause(); + 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) } - }); - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function (method) { - return function () { - return stream[method].apply(stream, arguments); - }; - }(i); + const { agent, dispatcher = getGlobalDispatcher() } = opts + + if (agent) { + throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?') } - } - // proxy certain important events. - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + 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) } +} - // when we try to consume some more bytes, simply unpause the - // underlying stream. - this._read = function (n) { - debug('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); +module.exports.setGlobalDispatcher = setGlobalDispatcher +module.exports.getGlobalDispatcher = getGlobalDispatcher + +if (util.nodeMajor > 16 || (util.nodeMajor === 16 && util.nodeMinor >= 8)) { + let fetchImpl = null + module.exports.fetch = async function fetch (resource) { + if (!fetchImpl) { + fetchImpl = (__nccwpck_require__(2315).fetch) } - }; - return this; -}; + try { + return await fetchImpl(...arguments) + } catch (err) { + if (typeof err === 'object') { + Error.captureStackTrace(err, this) + } -Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function () { - return this._readableState.highWaterMark; + throw err + } } -}); + module.exports.Headers = __nccwpck_require__(6349).Headers + module.exports.Response = __nccwpck_require__(8676).Response + module.exports.Request = __nccwpck_require__(5194).Request + module.exports.FormData = __nccwpck_require__(3073).FormData + module.exports.File = __nccwpck_require__(3041).File + module.exports.FileReader = __nccwpck_require__(2160).FileReader -// exposed for testing purposes only. -Readable._fromList = fromList; + const { setGlobalOrigin, getGlobalOrigin } = __nccwpck_require__(5628) -// Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; + module.exports.setGlobalOrigin = setGlobalOrigin + module.exports.getGlobalOrigin = getGlobalOrigin - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = fromListPartial(n, state.buffer, state.decoder); - } + const { CacheStorage } = __nccwpck_require__(4738) + const { kConstruct } = __nccwpck_require__(296) - return ret; + // Cache & CacheStorage are tightly coupled with fetch. Even if it may run + // in an older version of Node, it doesn't have any use without fetch. + module.exports.caches = new CacheStorage(kConstruct) } -// Extracts only enough buffered data to satisfy the amount requested. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromListPartial(n, list, hasStrings) { - var ret; - if (n < list.head.data.length) { - // slice is the same for buffers and strings - ret = list.head.data.slice(0, n); - list.head.data = list.head.data.slice(n); - } else if (n === list.head.data.length) { - // first chunk is a perfect match - ret = list.shift(); - } else { - // result spans more than one buffer - ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); - } - return ret; -} +if (util.nodeMajor >= 16) { + const { deleteCookie, getCookies, getSetCookies, setCookie } = __nccwpck_require__(3168) -// Copies a specified amount of characters from the list of buffered data -// chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBufferString(n, list) { - var p = list.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) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = str.slice(nb); - } - break; - } - ++c; - } - list.length -= c; - return ret; -} + module.exports.deleteCookie = deleteCookie + module.exports.getCookies = getCookies + module.exports.getSetCookies = getSetCookies + module.exports.setCookie = setCookie -// Copies a specified amount of bytes from the list of buffered data chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBuffer(n, list) { - var ret = Buffer.allocUnsafe(n); - var p = list.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) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = buf.slice(nb); - } - break; - } - ++c; - } - list.length -= c; - return ret; -} + const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(4322) -function endReadable(stream) { - var state = stream._readableState; + module.exports.parseMIMEType = parseMIMEType + module.exports.serializeAMimeType = serializeAMimeType +} - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); +if (util.nodeMajor >= 18 && hasCrypto) { + const { WebSocket } = __nccwpck_require__(5171) - if (!state.endEmitted) { - state.ended = true; - pna.nextTick(endReadableNT, state, stream); - } + module.exports.WebSocket = WebSocket } -function endReadableNT(state, stream) { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } -} +module.exports.request = makeDispatcher(api.request) +module.exports.stream = makeDispatcher(api.stream) +module.exports.pipeline = makeDispatcher(api.pipeline) +module.exports.connect = makeDispatcher(api.connect) +module.exports.upgrade = makeDispatcher(api.upgrade) + +module.exports.MockClient = MockClient +module.exports.MockPool = MockPool +module.exports.MockAgent = MockAgent +module.exports.mockErrors = mockErrors -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; -} /***/ }), -/***/ 4415: +/***/ 9965: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. +const { InvalidArgumentError } = __nccwpck_require__(8707) +const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = __nccwpck_require__(6443) +const DispatcherBase = __nccwpck_require__(1) +const Pool = __nccwpck_require__(5076) +const Client = __nccwpck_require__(6197) +const util = __nccwpck_require__(3440) +const createRedirectInterceptor = __nccwpck_require__(4415) +const { WeakRef, FinalizationRegistry } = __nccwpck_require__(3194)() +const kOnConnect = Symbol('onConnect') +const kOnDisconnect = Symbol('onDisconnect') +const kOnConnectionError = Symbol('onConnectionError') +const kMaxRedirections = Symbol('maxRedirections') +const kOnDrain = Symbol('onDrain') +const kFactory = Symbol('factory') +const kFinalizer = Symbol('finalizer') +const kOptions = Symbol('options') -module.exports = Transform; +function defaultFactory (origin, opts) { + return opts && opts.connections === 1 + ? new Client(origin, opts) + : new Pool(origin, opts) +} -var Duplex = __nccwpck_require__(1359); +class Agent extends DispatcherBase { + constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super() -/**/ -var util = Object.create(__nccwpck_require__(5898)); -util.inherits = __nccwpck_require__(4124); -/**/ + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } -util.inherits(Transform, Duplex); + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } -function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; + if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } - var cb = ts.writecb; + if (connect && typeof connect !== 'function') { + connect = { ...connect } + } - if (!cb) { - return this.emit('error', new Error('write callback called multiple times')); - } + this[kInterceptors] = options.interceptors && options.interceptors.Agent && Array.isArray(options.interceptors.Agent) + ? options.interceptors.Agent + : [createRedirectInterceptor({ maxRedirections })] - ts.writechunk = null; - ts.writecb = null; + this[kOptions] = { ...util.deepClone(options), connect } + this[kOptions].interceptors = options.interceptors + ? { ...options.interceptors } + : undefined + this[kMaxRedirections] = maxRedirections + this[kFactory] = factory + this[kClients] = new Map() + this[kFinalizer] = new FinalizationRegistry(/* istanbul ignore next: gc is undeterministic */ key => { + const ref = this[kClients].get(key) + if (ref !== undefined && ref.deref() === undefined) { + this[kClients].delete(key) + } + }) - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); + const agent = this - cb(er); + this[kOnDrain] = (origin, targets) => { + agent.emit('drain', origin, [agent, ...targets]) + } - var rs = this._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); + this[kOnConnect] = (origin, targets) => { + agent.emit('connect', origin, [agent, ...targets]) + } + + this[kOnDisconnect] = (origin, targets, err) => { + agent.emit('disconnect', origin, [agent, ...targets], err) + } + + this[kOnConnectionError] = (origin, targets, err) => { + agent.emit('connectionError', origin, [agent, ...targets], err) + } } -} -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); + get [kRunning] () { + let ret = 0 + for (const ref of this[kClients].values()) { + const client = ref.deref() + /* istanbul ignore next: gc is undeterministic */ + if (client) { + ret += client[kRunning] + } + } + return ret + } - Duplex.call(this, options); + [kDispatch] (opts, handler) { + let key + if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) { + key = String(opts.origin) + } else { + throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.') + } - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; + const ref = this[kClients].get(key) - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; + let dispatcher = ref ? ref.deref() : null + if (!dispatcher) { + dispatcher = this[kFactory](opts.origin, this[kOptions]) + .on('drain', this[kOnDrain]) + .on('connect', this[kOnConnect]) + .on('disconnect', this[kOnDisconnect]) + .on('connectionError', this[kOnConnectionError]) - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; + this[kClients].set(key, new WeakRef(dispatcher)) + this[kFinalizer].register(dispatcher, key) + } - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; + return dispatcher.dispatch(opts, handler) + } - if (typeof options.flush === 'function') this._flush = options.flush; + async [kClose] () { + const closePromises = [] + for (const ref of this[kClients].values()) { + const client = ref.deref() + /* istanbul ignore else: gc is undeterministic */ + if (client) { + closePromises.push(client.close()) + } + } + + await Promise.all(closePromises) } - // When the writable side finishes, then flush out anything remaining. - this.on('prefinish', prefinish); + async [kDestroy] (err) { + const destroyPromises = [] + for (const ref of this[kClients].values()) { + const client = ref.deref() + /* istanbul ignore else: gc is undeterministic */ + if (client) { + destroyPromises.push(client.destroy(err)) + } + } + + await Promise.all(destroyPromises) + } } -function prefinish() { - var _this = this; +module.exports = Agent - if (typeof this._flush === 'function') { - this._flush(function (er, data) { - done(_this, er, data); - }); + +/***/ }), + +/***/ 158: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const { addAbortListener } = __nccwpck_require__(3440) +const { RequestAbortedError } = __nccwpck_require__(8707) + +const kListener = Symbol('kListener') +const kSignal = Symbol('kSignal') + +function abort (self) { + if (self.abort) { + self.abort() } else { - done(this, null, null); + self.onError(new RequestAbortedError()) } } -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; - -// This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. -Transform.prototype._transform = function (chunk, encoding, cb) { - throw new Error('_transform() is not implemented'); -}; +function addSignal (self, signal) { + self[kSignal] = null + self[kListener] = null -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); + if (!signal) { + return } -}; - -// Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. -Transform.prototype._read = function (n) { - var ts = this._transformState; - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; + if (signal.aborted) { + abort(self) + return } -}; - -Transform.prototype._destroy = function (err, cb) { - var _this2 = this; - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - _this2.emit('close'); - }); -}; + self[kSignal] = signal + self[kListener] = () => { + abort(self) + } -function done(stream, er, data) { - if (er) return stream.emit('error', er); + addAbortListener(self[kSignal], self[kListener]) +} - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); +function removeSignal (self) { + if (!self[kSignal]) { + return + } - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); + if ('removeEventListener' in self[kSignal]) { + self[kSignal].removeEventListener('abort', self[kListener]) + } else { + self[kSignal].removeListener('abort', self[kListener]) + } - if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); + self[kSignal] = null + self[kListener] = null +} - return stream.push(null); +module.exports = { + addSignal, + removeSignal } + /***/ }), -/***/ 6993: +/***/ 4660: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. +const { AsyncResource } = __nccwpck_require__(290) +const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(8707) +const util = __nccwpck_require__(3440) +const { addSignal, removeSignal } = __nccwpck_require__(158) +class ConnectHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } -/**/ + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } -var pna = __nccwpck_require__(7810); -/**/ + const { signal, opaque, responseHeaders } = opts -module.exports = Writable; + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } -/* */ -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} + super('UNDICI_CONNECT') -// It seems a linked list but it is not -// there will be only 2 of these for each stream -function CorkedRequest(state) { - var _this = this; + this.opaque = opaque || null + this.responseHeaders = responseHeaders || null + this.callback = callback + this.abort = null - this.next = null; - this.entry = null; - this.finish = function () { - onCorkedFinish(_this, state); - }; -} -/* */ + addSignal(this, signal) + } -/**/ -var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; -/**/ + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } -/**/ -var Duplex; -/**/ + this.abort = abort + this.context = context + } -Writable.WritableState = WritableState; + onHeaders () { + throw new SocketError('bad connect', null) + } -/**/ -var util = Object.create(__nccwpck_require__(5898)); -util.inherits = __nccwpck_require__(4124); -/**/ + onUpgrade (statusCode, rawHeaders, socket) { + const { callback, opaque, context } = this -/**/ -var internalUtil = { - deprecate: __nccwpck_require__(7127) -}; -/**/ + removeSignal(this) -/**/ -var Stream = __nccwpck_require__(2387); -/**/ + this.callback = null -/**/ + let headers = rawHeaders + // Indicates is an HTTP2Session + if (headers != null) { + headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + } -var Buffer = (__nccwpck_require__(1867).Buffer); -var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); + this.runInAsyncScope(callback, null, null, { + statusCode, + headers, + socket, + opaque, + context + }) + } + + onError (err) { + const { callback, opaque } = this + + removeSignal(this) + + if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } + } } -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; + +function connect (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + connect.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + const connectHandler = new ConnectHandler(opts, callback) + this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts && opts.opaque + queueMicrotask(() => callback(err, { opaque })) + } } -/**/ +module.exports = connect -var destroyImpl = __nccwpck_require__(7049); -util.inherits(Writable, Stream); +/***/ }), -function nop() {} +/***/ 6862: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function WritableState(options, stream) { - Duplex = Duplex || __nccwpck_require__(1359); - options = options || {}; - // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - var isDuplex = stream instanceof Duplex; +const { + Readable, + Duplex, + PassThrough +} = __nccwpck_require__(2203) +const { + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError +} = __nccwpck_require__(8707) +const util = __nccwpck_require__(3440) +const { AsyncResource } = __nccwpck_require__(290) +const { addSignal, removeSignal } = __nccwpck_require__(158) +const assert = __nccwpck_require__(2613) - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; +const kResume = Symbol('resume') - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; +class PipelineRequest extends Readable { + constructor () { + super({ autoDestroy: true }) - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - var writableHwm = options.writableHighWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this[kResume] = null + } - if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; + _read () { + const { [kResume]: resume } = this - // cast to ints. - this.highWaterMark = Math.floor(this.highWaterMark); + if (resume) { + this[kResume] = null + resume() + } + } - // if _final has been called - this.finalCalled = false; + _destroy (err, callback) { + this._read() - // drain event flag. - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; + callback(err) + } +} - // has it been destroyed - this.destroyed = false; +class PipelineResponse extends Readable { + constructor (resume) { + super({ autoDestroy: true }) + this[kResume] = resume + } - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; + _read () { + this[kResume]() + } - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; + _destroy (err, callback) { + if (!err && !this._readableState.endEmitted) { + err = new RequestAbortedError() + } - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; + callback(err) + } +} - // a flag to see when we're in the middle of a write. - this.writing = false; +class PipelineHandler extends AsyncResource { + constructor (opts, handler) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } - // when true all writes will be buffered until .uncork() call - this.corked = 0; + if (typeof handler !== 'function') { + throw new InvalidArgumentError('invalid handler') + } - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; + const { signal, method, opaque, onInfo, responseHeaders } = opts - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } - // the callback that's passed to _write(chunk,cb) - this.onwrite = function (er) { - onwrite(stream, er); - }; + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } - // the amount that is being written when _write is called. - this.writelen = 0; + super('UNDICI_PIPELINE') - this.bufferedRequest = null; - this.lastBufferedRequest = null; + this.opaque = opaque || null + this.responseHeaders = responseHeaders || null + this.handler = handler + this.abort = null + this.context = null + this.onInfo = onInfo || null - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; + this.req = new PipelineRequest().on('error', util.nop) - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; + this.ret = new Duplex({ + readableObjectMode: opts.objectMode, + autoDestroy: true, + read: () => { + const { body } = this - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; + if (body && body.resume) { + body.resume() + } + }, + write: (chunk, encoding, callback) => { + const { req } = this - // count buffered requests - this.bufferedRequestCount = 0; + if (req.push(chunk, encoding) || req._readableState.destroyed) { + callback() + } else { + req[kResume] = callback + } + }, + destroy: (err, callback) => { + const { body, req, res, ret, abort } = this - // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - this.corkedRequestsFree = new CorkedRequest(this); -} + if (!err && !ret._readableState.endEmitted) { + err = new RequestAbortedError() + } -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; - } - return out; -}; + if (abort && err) { + abort() + } -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function () { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} -})(); + util.destroy(body, err) + util.destroy(req, err) + util.destroy(res, err) -// Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. -var realHasInstance; -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function (object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable) return false; + removeSignal(this) - return object && object._writableState instanceof WritableState; - } - }); -} else { - realHasInstance = function (object) { - return object instanceof this; - }; -} + callback(err) + } + }).on('prefinish', () => { + const { req } = this -function Writable(options) { - Duplex = Duplex || __nccwpck_require__(1359); + // Node < 15 does not call _final in same tick. + req.push(null) + }) - // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. + this.res = null - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { - return new Writable(options); + addSignal(this, signal) } - this._writableState = new WritableState(options, this); + onConnect (abort, context) { + const { ret, res } = this - // legacy. - this.writable = true; + assert(!res, 'pipeline cannot be retried') - if (options) { - if (typeof options.write === 'function') this._write = options.write; + if (ret.destroyed) { + throw new RequestAbortedError() + } - if (typeof options.writev === 'function') this._writev = options.writev; + this.abort = abort + this.context = context + } - if (typeof options.destroy === 'function') this._destroy = options.destroy; + onHeaders (statusCode, rawHeaders, resume) { + const { opaque, handler, context } = this - if (typeof options.final === 'function') this._final = options.final; - } + if (statusCode < 200) { + if (this.onInfo) { + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + this.onInfo({ statusCode, headers }) + } + return + } - Stream.call(this); -} + this.res = new PipelineResponse(resume) -// Otherwise people can pipe Writable streams, which is just wrong. -Writable.prototype.pipe = function () { - this.emit('error', new Error('Cannot pipe, not readable')); -}; + let body + try { + this.handler = null + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + body = this.runInAsyncScope(handler, null, { + statusCode, + headers, + opaque, + body: this.res, + context + }) + } catch (err) { + this.res.on('error', util.nop) + throw err + } -function writeAfterEnd(stream, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - pna.nextTick(cb, er); -} + if (!body || typeof body.on !== 'function') { + throw new InvalidReturnValueError('expected Readable') + } -// Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. -function validChunk(stream, state, chunk, cb) { - var valid = true; - var er = false; + body + .on('data', (chunk) => { + const { ret, body } = this - if (chunk === null) { - er = new TypeError('May not write null values to stream'); - } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); + if (!ret.push(chunk) && body.pause) { + body.pause() + } + }) + .on('error', (err) => { + const { ret } = this + + util.destroy(ret, err) + }) + .on('end', () => { + const { ret } = this + + ret.push(null) + }) + .on('close', () => { + const { ret } = this + + if (!ret._readableState.ended) { + util.destroy(ret, new RequestAbortedError()) + } + }) + + this.body = body } - if (er) { - stream.emit('error', er); - pna.nextTick(cb, er); - valid = false; + + onData (chunk) { + const { res } = this + return res.push(chunk) } - return valid; -} -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - var isBuf = !state.objectMode && _isUint8Array(chunk); + onComplete (trailers) { + const { res } = this + res.push(null) + } - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); + onError (err) { + const { ret } = this + this.handler = null + util.destroy(ret, err) } +} - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; +function pipeline (opts, handler) { + try { + const pipelineHandler = new PipelineHandler(opts, handler) + this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler) + return pipelineHandler.ret + } catch (err) { + return new PassThrough().destroy(err) } +} - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; +module.exports = pipeline - if (typeof cb !== 'function') cb = nop; - if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } +/***/ }), - return ret; -}; +/***/ 4043: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Writable.prototype.cork = function () { - var state = this._writableState; - state.corked++; -}; -Writable.prototype.uncork = function () { - var state = this._writableState; +const Readable = __nccwpck_require__(9927) +const { + InvalidArgumentError, + RequestAbortedError +} = __nccwpck_require__(8707) +const util = __nccwpck_require__(3440) +const { getResolveErrorBodyCallback } = __nccwpck_require__(7655) +const { AsyncResource } = __nccwpck_require__(290) +const { addSignal, removeSignal } = __nccwpck_require__(158) + +class RequestHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } - if (state.corked) { - state.corked--; + const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - 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 TypeError('Unknown encoding: ' + encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; + if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) { + throw new InvalidArgumentError('invalid highWaterMark') + } -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } - return chunk; -} + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } -Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function () { - return this._writableState.highWaterMark; + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } + + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } + + super('UNDICI_REQUEST') + } catch (err) { + if (util.isStream(body)) { + util.destroy(body.on('error', util.nop), err) + } + throw err + } + + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.callback = callback + this.res = null + this.abort = null + this.body = body + this.trailers = {} + this.context = null + this.onInfo = onInfo || null + this.throwOnError = throwOnError + this.highWaterMark = highWaterMark + + if (util.isStream(body)) { + body.on('error', (err) => { + this.onError(err) + }) + } + + addSignal(this, signal) } -}); -// if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() } + + this.abort = abort + this.context = context } - var len = state.objectMode ? 1 : chunk.length; - state.length += len; + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) state.needDrain = true; + const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; + if (statusCode < 200) { + if (this.onInfo) { + this.onInfo({ statusCode, headers }) + } + return + } + + const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers + const contentType = parsedHeaders['content-type'] + const body = new Readable({ resume, abort, contentType, highWaterMark }) + + this.callback = null + this.res = body + if (callback !== null) { + if (this.throwOnError && statusCode >= 400) { + this.runInAsyncScope(getResolveErrorBodyCallback, null, + { callback, body, contentType, statusCode, statusMessage, headers } + ) + } else { + this.runInAsyncScope(callback, null, null, { + statusCode, + headers, + trailers: this.trailers, + opaque, + body, + context + }) + } } - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); } - return ret; -} + onData (chunk) { + const { res } = this + return res.push(chunk) + } -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} + onComplete (trailers) { + const { res } = this -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; + removeSignal(this) - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - pna.nextTick(cb, er); - // this can emit finish, and it will always happen - // after error - pna.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - stream.emit('error', er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - stream.emit('error', er); - // this can emit finish, but finish must - // always follow error - finishMaybe(stream, state); - } -} + util.parseHeaders(trailers, this.trailers) -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} + res.push(null) + } -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; + onError (err) { + const { res, callback, body, opaque } = this - onwriteStateUpdate(state); + removeSignal(this) - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state); + if (callback) { + // TODO: Does this need queueMicrotask? + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); + if (res) { + this.res = null + // Ensure all queued handlers are invoked before destroying res. + queueMicrotask(() => { + util.destroy(res, err) + }) } - if (sync) { - /**/ - asyncWrite(afterWrite, stream, state, finished, cb); - /**/ - } else { - afterWrite(stream, state, finished, cb); + if (body) { + this.body = null + util.destroy(body, err) } } } -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} +function request (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + request.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } -// Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); + try { + this.dispatch(opts, new RequestHandler(opts, callback)) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts && opts.opaque + queueMicrotask(() => callback(err, { opaque })) } } -// if there's something in the buffer waiting, then process it -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; +module.exports = request +module.exports.RequestHandler = RequestHandler - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - 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(stream, state, true, state.length, buffer, '', holder.finish); +/***/ 3560: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - state.pendingcb++; - state.lastBufferedRequest = null; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); + + +const { finished, PassThrough } = __nccwpck_require__(2203) +const { + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError +} = __nccwpck_require__(8707) +const util = __nccwpck_require__(3440) +const { getResolveErrorBodyCallback } = __nccwpck_require__(7655) +const { AsyncResource } = __nccwpck_require__(290) +const { addSignal, removeSignal } = __nccwpck_require__(158) + +class StreamHandler extends AsyncResource { + constructor (opts, factory, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') } - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - break; + const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts + + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') } - } - if (entry === null) state.lastBufferedRequest = null; - } + if (typeof factory !== 'function') { + throw new InvalidArgumentError('invalid factory') + } - state.bufferedRequest = entry; - state.bufferProcessing = false; -} + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new Error('_write() is not implemented')); -}; + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } -Writable.prototype._writev = null; + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; + super('UNDICI_STREAM') + } catch (err) { + if (util.isStream(body)) { + util.destroy(body.on('error', util.nop), err) + } + throw err + } + + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.factory = factory + this.callback = callback + this.res = null + this.abort = null + this.context = null + this.trailers = null + this.body = body + this.onInfo = onInfo || null + this.throwOnError = throwOnError || false + + if (util.isStream(body)) { + body.on('error', (err) => { + this.onError(err) + }) + } - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; + addSignal(this, signal) } - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); + this.abort = abort + this.context = context } - // ignore unnecessary end() calls. - if (!state.ending) endWritable(this, state, cb); -}; + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const { factory, opaque, context, callback, responseHeaders } = this -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} -function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - if (err) { - stream.emit('error', err); + const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + + if (statusCode < 200) { + if (this.onInfo) { + this.onInfo({ statusCode, headers }) + } + return } - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); -} -function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function') { - state.pendingcb++; - state.finalCalled = true; - pna.nextTick(callFinal, stream, state); + + this.factory = null + + let res + + if (this.throwOnError && statusCode >= 400) { + const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers + const contentType = parsedHeaders['content-type'] + res = new PassThrough() + + this.callback = null + this.runInAsyncScope(getResolveErrorBodyCallback, null, + { callback, body: res, contentType, statusCode, statusMessage, headers } + ) } else { - state.prefinished = true; - stream.emit('prefinish'); - } - } -} + if (factory === null) { + return + } -function finishMaybe(stream, state) { - var need = needFinish(state); - if (need) { - prefinish(stream, state); - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); + res = this.runInAsyncScope(factory, null, { + statusCode, + headers, + opaque, + context + }) + + if ( + !res || + typeof res.write !== 'function' || + typeof res.end !== 'function' || + typeof res.on !== 'function' + ) { + throw new InvalidReturnValueError('expected Writable') + } + + // TODO: Avoid finished. It registers an unnecessary amount of listeners. + finished(res, { readable: false }, (err) => { + const { callback, res, opaque, trailers, abort } = this + + this.res = null + if (err || !res.readable) { + util.destroy(res, err) + } + + this.callback = null + this.runInAsyncScope(callback, null, err || null, { opaque, trailers }) + + if (err) { + abort() + } + }) } + + res.on('drain', resume) + + this.res = res + + const needDrain = res.writableNeedDrain !== undefined + ? res.writableNeedDrain + : res._writableState && res._writableState.needDrain + + return needDrain !== true } - return need; -} -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); + onData (chunk) { + const { res } = this + + return res ? res.write(chunk) : true } - state.ended = true; - stream.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; + onComplete (trailers) { + const { res } = this + + removeSignal(this) + + if (!res) { + return + } + + this.trailers = util.parseHeaders(trailers) + + res.end() } - // reuse the free corkReq. - state.corkedRequestsFree.next = corkReq; -} + onError (err) { + const { res, callback, opaque, body } = this -Object.defineProperty(Writable.prototype, 'destroyed', { - get: function () { - if (this._writableState === undefined) { - return false; + removeSignal(this) + + this.factory = null + + if (res) { + this.res = null + util.destroy(res, err) + } else if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) } - return this._writableState.destroyed; - }, - set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; + + if (body) { + this.body = null + util.destroy(body, err) } + } +} - // backward compatibility, the user is explicitly - // managing destroyed - this._writableState.destroyed = value; +function stream (opts, factory, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + stream.call(this, opts, factory, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) } -}); -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; -Writable.prototype._destroy = function (err, cb) { - this.end(); - cb(err); -}; + try { + this.dispatch(opts, new StreamHandler(opts, factory, callback)) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts && opts.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} + +module.exports = stream + /***/ }), -/***/ 7053: +/***/ 1882: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var Buffer = (__nccwpck_require__(1867).Buffer); -var util = __nccwpck_require__(3837); - -function copyBuffer(src, target, offset) { - src.copy(target, offset); -} - -module.exports = function () { - function BufferList() { - _classCallCheck(this, BufferList); - - this.head = null; - this.tail = null; - this.length = 0; - } - - BufferList.prototype.push = 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; - }; - - BufferList.prototype.unshift = function unshift(v) { - var entry = { data: v, next: this.head }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - }; - - BufferList.prototype.shift = 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; - }; - - BufferList.prototype.clear = function clear() { - this.head = this.tail = null; - this.length = 0; - }; +const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(8707) +const { AsyncResource } = __nccwpck_require__(290) +const util = __nccwpck_require__(3440) +const { addSignal, removeSignal } = __nccwpck_require__(158) +const assert = __nccwpck_require__(2613) - BufferList.prototype.join = 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; - }; +class UpgradeHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } - BufferList.prototype.concat = function concat(n) { - if (this.length === 0) return Buffer.alloc(0); - var ret = Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') } - return ret; - }; - return BufferList; -}(); + const { signal, opaque, responseHeaders } = opts -if (util && util.inspect && util.inspect.custom) { - module.exports.prototype[util.inspect.custom] = function () { - var obj = util.inspect({ length: this.length }); - return this.constructor.name + ' ' + obj; - }; -} + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } -/***/ }), + super('UNDICI_UPGRADE') -/***/ 7049: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.callback = callback + this.abort = null + this.context = null + addSignal(this, signal) + } + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } -/**/ + this.abort = abort + this.context = null + } -var pna = __nccwpck_require__(7810); -/**/ + onHeaders () { + throw new SocketError('bad upgrade', null) + } -// undocumented cb() API, needed for core, not for public API -function destroy(err, cb) { - var _this = this; + onUpgrade (statusCode, rawHeaders, socket) { + const { callback, opaque, context } = this - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; + assert.strictEqual(statusCode, 101) - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - pna.nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - pna.nextTick(emitErrorNT, this, err); - } - } + removeSignal(this) - return this; + this.callback = null + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + this.runInAsyncScope(callback, null, null, { + headers, + socket, + opaque, + context + }) } - // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - if (this._readableState) { - this._readableState.destroyed = true; - } + onError (err) { + const { callback, opaque } = this - // if this is a duplex stream mark the writable part as destroyed as well - if (this._writableState) { - this._writableState.destroyed = true; - } + removeSignal(this) - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - pna.nextTick(emitErrorNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - pna.nextTick(emitErrorNT, _this, err); - } - } else if (cb) { - cb(err); + if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) } - }); - - return this; + } } -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; +function upgrade (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + upgrade.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) } - 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; + try { + const upgradeHandler = new UpgradeHandler(opts, callback) + this.dispatch({ + ...opts, + method: opts.method || 'GET', + upgrade: opts.protocol || 'Websocket' + }, upgradeHandler) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts && opts.opaque + queueMicrotask(() => callback(err, { opaque })) } } -function emitErrorNT(self, err) { - self.emit('error', err); -} +module.exports = upgrade -module.exports = { - destroy: destroy, - undestroy: undestroy -}; /***/ }), -/***/ 2387: +/***/ 6615: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -module.exports = __nccwpck_require__(2781); -/***/ }), - -/***/ 1642: -/***/ ((module, exports, __nccwpck_require__) => { - -var Stream = __nccwpck_require__(2781); -if (process.env.READABLE_STREAM === 'disable' && Stream) { - module.exports = Stream; - exports = module.exports = Stream.Readable; - exports.Readable = Stream.Readable; - exports.Writable = Stream.Writable; - exports.Duplex = Stream.Duplex; - exports.Transform = Stream.Transform; - exports.PassThrough = Stream.PassThrough; - exports.Stream = Stream; -} else { - exports = module.exports = __nccwpck_require__(1433); - exports.Stream = Stream || exports; - exports.Readable = exports; - exports.Writable = __nccwpck_require__(6993); - exports.Duplex = __nccwpck_require__(1359); - exports.Transform = __nccwpck_require__(4415); - exports.PassThrough = __nccwpck_require__(1542); -} +module.exports.request = __nccwpck_require__(4043) +module.exports.stream = __nccwpck_require__(3560) +module.exports.pipeline = __nccwpck_require__(6862) +module.exports.upgrade = __nccwpck_require__(1882) +module.exports.connect = __nccwpck_require__(4660) /***/ }), -/***/ 6624: +/***/ 9927: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// Ported from https://github.com/nodejs/undici/pull/907 -const tls = __nccwpck_require__(4404); -module.exports = (options = {}, connect = tls.connect) => new Promise((resolve, reject) => { - let timeout = false; - let socket; +const assert = __nccwpck_require__(2613) +const { Readable } = __nccwpck_require__(2203) +const { RequestAbortedError, NotSupportedError, InvalidArgumentError } = __nccwpck_require__(8707) +const util = __nccwpck_require__(3440) +const { ReadableStreamFrom, toUSVString } = __nccwpck_require__(3440) - const callback = async () => { - await socketPromise; +let Blob - socket.off('timeout', onTimeout); - socket.off('error', reject); +const kConsume = Symbol('kConsume') +const kReading = Symbol('kReading') +const kBody = Symbol('kBody') +const kAbort = Symbol('abort') +const kContentType = Symbol('kContentType') - if (options.resolveSocket) { - resolve({alpnProtocol: socket.alpnProtocol, socket, timeout}); +const noop = () => {} - if (timeout) { - await Promise.resolve(); - socket.emit('timeout'); - } - } else { - socket.destroy(); - resolve({alpnProtocol: socket.alpnProtocol, timeout}); - } - }; +module.exports = class BodyReadable extends Readable { + constructor ({ + resume, + abort, + contentType = '', + highWaterMark = 64 * 1024 // Same as nodejs fs streams. + }) { + super({ + autoDestroy: true, + read: resume, + highWaterMark + }) - const onTimeout = async () => { - timeout = true; - callback(); - }; + this._readableState.dataEmitted = false - const socketPromise = (async () => { - try { - socket = await connect(options, callback); + this[kAbort] = abort + this[kConsume] = null + this[kBody] = null + this[kContentType] = contentType - socket.on('error', reject); - socket.once('timeout', onTimeout); - } catch (error) { - reject(error); - } - })(); -}); + // Is stream being consumed through Readable API? + // This is an optimization so that we avoid checking + // for 'data' and 'readable' listeners in the hot path + // inside push(). + this[kReading] = false + } + destroy (err) { + if (this.destroyed) { + // Node < 16 + return this + } -/***/ }), + if (!err && !this._readableState.endEmitted) { + err = new RequestAbortedError() + } -/***/ 4959: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (err) { + this[kAbort]() + } -module.exports = rimraf -rimraf.sync = rimrafSync + return super.destroy(err) + } -var assert = __nccwpck_require__(9491) -var path = __nccwpck_require__(1017) -var fs = __nccwpck_require__(7147) -var glob = undefined -try { - glob = __nccwpck_require__(1957) -} catch (_err) { - // treat glob as optional. -} -var _0666 = parseInt('666', 8) + emit (ev, ...args) { + if (ev === 'data') { + // Node < 16.7 + this._readableState.dataEmitted = true + } else if (ev === 'error') { + // Node < 16 + this._readableState.errorEmitted = true + } + return super.emit(ev, ...args) + } -var defaultGlobOpts = { - nosort: true, - silent: true -} + on (ev, ...args) { + if (ev === 'data' || ev === 'readable') { + this[kReading] = true + } + return super.on(ev, ...args) + } -// for EMFILE handling -var timeout = 0 + addListener (ev, ...args) { + return this.on(ev, ...args) + } -var isWindows = (process.platform === "win32") + off (ev, ...args) { + const ret = super.off(ev, ...args) + if (ev === 'data' || ev === 'readable') { + this[kReading] = ( + this.listenerCount('data') > 0 || + this.listenerCount('readable') > 0 + ) + } + return ret + } -function defaults (options) { - var methods = [ - 'unlink', - 'chmod', - 'stat', - 'lstat', - 'rmdir', - 'readdir' - ] - methods.forEach(function(m) { - options[m] = options[m] || fs[m] - m = m + 'Sync' - options[m] = options[m] || fs[m] - }) + removeListener (ev, ...args) { + return this.off(ev, ...args) + } - options.maxBusyTries = options.maxBusyTries || 3 - options.emfileWait = options.emfileWait || 1000 - if (options.glob === false) { - options.disableGlob = true + push (chunk) { + if (this[kConsume] && chunk !== null && this.readableLength === 0) { + consumePush(this[kConsume], chunk) + return this[kReading] ? super.push(chunk) : true + } + return super.push(chunk) } - if (options.disableGlob !== true && glob === undefined) { - throw Error('glob dependency not found, set `options.disableGlob = true` if intentional') + + // https://fetch.spec.whatwg.org/#dom-body-text + async text () { + return consume(this, 'text') } - options.disableGlob = options.disableGlob || false - options.glob = options.glob || defaultGlobOpts -} -function rimraf (p, options, cb) { - if (typeof options === 'function') { - cb = options - options = {} + // https://fetch.spec.whatwg.org/#dom-body-json + async json () { + return consume(this, 'json') } - assert(p, 'rimraf: missing path') - assert.equal(typeof p, 'string', 'rimraf: path should be a string') - assert.equal(typeof cb, 'function', 'rimraf: callback function required') - assert(options, 'rimraf: invalid options argument provided') - assert.equal(typeof options, 'object', 'rimraf: options should be object') + // https://fetch.spec.whatwg.org/#dom-body-blob + async blob () { + return consume(this, 'blob') + } - defaults(options) + // https://fetch.spec.whatwg.org/#dom-body-arraybuffer + async arrayBuffer () { + return consume(this, 'arrayBuffer') + } - var busyTries = 0 - var errState = null - var n = 0 + // https://fetch.spec.whatwg.org/#dom-body-formdata + async formData () { + // TODO: Implement. + throw new NotSupportedError() + } - if (options.disableGlob || !glob.hasMagic(p)) - return afterGlob(null, [p]) + // https://fetch.spec.whatwg.org/#dom-body-bodyused + get bodyUsed () { + return util.isDisturbed(this) + } - options.lstat(p, function (er, stat) { - if (!er) - return afterGlob(null, [p]) + // https://fetch.spec.whatwg.org/#dom-body-body + get body () { + if (!this[kBody]) { + this[kBody] = ReadableStreamFrom(this) + if (this[kConsume]) { + // TODO: Is this the best way to force a lock? + this[kBody].getReader() // Ensure stream is locked. + assert(this[kBody].locked) + } + } + return this[kBody] + } - glob(p, options.glob, afterGlob) - }) + dump (opts) { + let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144 + const signal = opts && opts.signal - function next (er) { - errState = errState || er - if (--n === 0) - cb(errState) - } - - function afterGlob (er, results) { - if (er) - return cb(er) - - n = results.length - if (n === 0) - return cb() - - results.forEach(function (p) { - rimraf_(p, options, function CB (er) { - if (er) { - if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && - busyTries < options.maxBusyTries) { - busyTries ++ - var time = busyTries * 100 - // try again, with the same exact callback as this one. - return setTimeout(function () { - rimraf_(p, options, CB) - }, time) - } + if (signal) { + try { + if (typeof signal !== 'object' || !('aborted' in signal)) { + throw new InvalidArgumentError('signal must be an AbortSignal') + } + util.throwIfAborted(signal) + } catch (err) { + return Promise.reject(err) + } + } - // this one won't happen if graceful-fs is used. - if (er.code === "EMFILE" && timeout < options.emfileWait) { - return setTimeout(function () { - rimraf_(p, options, CB) - }, timeout ++) - } + if (this.closed) { + return Promise.resolve(null) + } - // already gone - if (er.code === "ENOENT") er = null - } + return new Promise((resolve, reject) => { + const signalListenerCleanup = signal + ? util.addAbortListener(signal, () => { + this.destroy() + }) + : noop - timeout = 0 - next(er) - }) + this + .on('close', function () { + signalListenerCleanup() + if (signal && signal.aborted) { + reject(signal.reason || Object.assign(new Error('The operation was aborted'), { name: 'AbortError' })) + } else { + resolve(null) + } + }) + .on('error', noop) + .on('data', function (chunk) { + limit -= chunk.length + if (limit <= 0) { + this.destroy() + } + }) + .resume() }) } } -// Two possible strategies. -// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR -// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR -// -// Both result in an extra syscall when you guess wrong. However, there -// are likely far more normal files in the world than directories. This -// is based on the assumption that a the average number of files per -// directory is >= 1. -// -// If anyone ever complains about this, then I guess the strategy could -// be made configurable somehow. But until then, YAGNI. -function rimraf_ (p, options, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') - - // sunos lets the root user unlink directories, which is... weird. - // so we have to lstat here and make sure it's not a dir. - options.lstat(p, function (er, st) { - if (er && er.code === "ENOENT") - return cb(null) - - // Windows can EPERM on stat. Life is suffering. - if (er && er.code === "EPERM" && isWindows) - fixWinEPERM(p, options, er, cb) - - if (st && st.isDirectory()) - return rmdir(p, options, er, cb) - - options.unlink(p, function (er) { - if (er) { - if (er.code === "ENOENT") - return cb(null) - if (er.code === "EPERM") - return (isWindows) - ? fixWinEPERM(p, options, er, cb) - : rmdir(p, options, er, cb) - if (er.code === "EISDIR") - return rmdir(p, options, er, cb) - } - return cb(er) - }) - }) +// https://streams.spec.whatwg.org/#readablestream-locked +function isLocked (self) { + // Consume is an implicit lock. + return (self[kBody] && self[kBody].locked === true) || self[kConsume] } -function fixWinEPERM (p, options, er, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') - if (er) - assert(er instanceof Error) - - options.chmod(p, _0666, function (er2) { - if (er2) - cb(er2.code === "ENOENT" ? null : er) - else - options.stat(p, function(er3, stats) { - if (er3) - cb(er3.code === "ENOENT" ? null : er) - else if (stats.isDirectory()) - rmdir(p, options, er, cb) - else - options.unlink(p, cb) - }) - }) +// https://fetch.spec.whatwg.org/#body-unusable +function isUnusable (self) { + return util.isDisturbed(self) || isLocked(self) } -function fixWinEPERMSync (p, options, er) { - assert(p) - assert(options) - if (er) - assert(er instanceof Error) - - try { - options.chmodSync(p, _0666) - } catch (er2) { - if (er2.code === "ENOENT") - return - else - throw er +async function consume (stream, type) { + if (isUnusable(stream)) { + throw new TypeError('unusable') } - try { - var stats = options.statSync(p) - } catch (er3) { - if (er3.code === "ENOENT") - return - else - throw er - } + assert(!stream[kConsume]) - if (stats.isDirectory()) - rmdirSync(p, options, er) - else - options.unlinkSync(p) -} - -function rmdir (p, options, originalEr, cb) { - assert(p) - assert(options) - if (originalEr) - assert(originalEr instanceof Error) - assert(typeof cb === 'function') - - // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) - // if we guessed wrong, and it's not a directory, then - // raise the original error. - options.rmdir(p, function (er) { - if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) - rmkids(p, options, cb) - else if (er && er.code === "ENOTDIR") - cb(originalEr) - else - cb(er) - }) -} + return new Promise((resolve, reject) => { + stream[kConsume] = { + type, + stream, + resolve, + reject, + length: 0, + body: [] + } -function rmkids(p, options, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') - - options.readdir(p, function (er, files) { - if (er) - return cb(er) - var n = files.length - if (n === 0) - return options.rmdir(p, cb) - var errState - files.forEach(function (f) { - rimraf(path.join(p, f), options, function (er) { - if (errState) - return - if (er) - return cb(errState = er) - if (--n === 0) - options.rmdir(p, cb) + stream + .on('error', function (err) { + consumeFinish(this[kConsume], err) }) - }) + .on('close', function () { + if (this[kConsume].body !== null) { + consumeFinish(this[kConsume], new RequestAbortedError()) + } + }) + + process.nextTick(consumeStart, stream[kConsume]) }) } -// this looks simpler, and is strictly *faster*, but will -// tie up the JavaScript thread and fail on excessively -// deep directory trees. -function rimrafSync (p, options) { - options = options || {} - defaults(options) +function consumeStart (consume) { + if (consume.body === null) { + return + } - assert(p, 'rimraf: missing path') - assert.equal(typeof p, 'string', 'rimraf: path should be a string') - assert(options, 'rimraf: missing options') - assert.equal(typeof options, 'object', 'rimraf: options should be object') + const { _readableState: state } = consume.stream - var results + for (const chunk of state.buffer) { + consumePush(consume, chunk) + } - if (options.disableGlob || !glob.hasMagic(p)) { - results = [p] + if (state.endEmitted) { + consumeEnd(this[kConsume]) } else { - try { - options.lstatSync(p) - results = [p] - } catch (er) { - results = glob.sync(p, options.glob) - } + consume.stream.on('end', function () { + consumeEnd(this[kConsume]) + }) } - if (!results.length) - return - - for (var i = 0; i < results.length; i++) { - var p = results[i] + consume.stream.resume() - try { - var st = options.lstatSync(p) - } catch (er) { - if (er.code === "ENOENT") - return + while (consume.stream.read() != null) { + // Loop + } +} - // Windows can EPERM on stat. Life is suffering. - if (er.code === "EPERM" && isWindows) - fixWinEPERMSync(p, options, er) - } +function consumeEnd (consume) { + const { type, body, resolve, stream, length } = consume - try { - // sunos lets the root user unlink directories, which is... weird. - if (st && st.isDirectory()) - rmdirSync(p, options, null) - else - options.unlinkSync(p) - } catch (er) { - if (er.code === "ENOENT") - return - if (er.code === "EPERM") - return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) - if (er.code !== "EISDIR") - throw er + try { + if (type === 'text') { + resolve(toUSVString(Buffer.concat(body))) + } else if (type === 'json') { + resolve(JSON.parse(Buffer.concat(body))) + } else if (type === 'arrayBuffer') { + const dst = new Uint8Array(length) + + let pos = 0 + for (const buf of body) { + dst.set(buf, pos) + pos += buf.byteLength + } - rmdirSync(p, options, er) + resolve(dst.buffer) + } else if (type === 'blob') { + if (!Blob) { + Blob = (__nccwpck_require__(181).Blob) + } + resolve(new Blob(body, { type: stream[kContentType] })) } + + consumeFinish(consume) + } catch (err) { + stream.destroy(err) } } -function rmdirSync (p, options, originalEr) { - assert(p) - assert(options) - if (originalEr) - assert(originalEr instanceof Error) +function consumePush (consume, chunk) { + consume.length += chunk.length + consume.body.push(chunk) +} - try { - options.rmdirSync(p) - } catch (er) { - if (er.code === "ENOENT") - return - if (er.code === "ENOTDIR") - throw originalEr - if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") - rmkidsSync(p, options) +function consumeFinish (consume, err) { + if (consume.body === null) { + return } -} -function rmkidsSync (p, options) { - assert(p) - assert(options) - options.readdirSync(p).forEach(function (f) { - rimrafSync(path.join(p, f), options) - }) + if (err) { + consume.reject(err) + } else { + consume.resolve() + } - // We only end up here once we got ENOTEMPTY at least once, and - // at this point, we are guaranteed to have removed all the kids. - // So, we know that it won't be ENOENT or ENOTDIR or anything else. - // try really hard to delete stuff on windows, because it has a - // PROFOUNDLY annoying habit of not closing handles promptly when - // files are deleted, resulting in spurious ENOTEMPTY errors. - var retries = isWindows ? 100 : 1 - var i = 0 - do { - var threw = true - try { - var ret = options.rmdirSync(p, options) - threw = false - return ret - } finally { - if (++i < retries && threw) - continue - } - } while (true) + consume.type = null + consume.stream = null + consume.resolve = null + consume.reject = null + consume.length = 0 + consume.body = null } /***/ }), -/***/ 1867: -/***/ ((module, exports, __nccwpck_require__) => { - -/* eslint-disable node/no-deprecated-api */ -var buffer = __nccwpck_require__(4300) -var Buffer = buffer.Buffer +/***/ 7655: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] - } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer -} +const assert = __nccwpck_require__(2613) +const { + ResponseStatusCodeError +} = __nccwpck_require__(8707) +const { toUSVString } = __nccwpck_require__(3440) -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} +async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) { + assert(body) -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) + let chunks = [] + let limit = 0 -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') + for await (const chunk of body) { + chunks.push(chunk) + limit += chunk.length + if (limit > 128 * 1024) { + chunks = null + break + } } - return Buffer(arg, encodingOrOffset, length) -} -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') + if (statusCode === 204 || !contentType || !chunks) { + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)) + return } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) + + try { + if (contentType.startsWith('application/json')) { + const payload = JSON.parse(toUSVString(Buffer.concat(chunks))) + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload)) + return } - } else { - buf.fill(0) - } - return buf -} -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') + if (contentType.startsWith('text/')) { + const payload = toUSVString(Buffer.concat(chunks)) + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload)) + return + } + } catch (err) { + // Process in a fallback if error } - return Buffer(size) -} -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)) } +module.exports = { getResolveErrorBodyCallback } + /***/ }), -/***/ 6062: -/***/ (function() { +/***/ 1093: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -(function (global, undefined) { - "use strict"; - if (global.setImmediate) { - return; - } - var nextHandle = 1; // Spec says greater than zero - var tasksByHandle = {}; - var currentlyRunningATask = false; - var doc = global.document; - var registerImmediate; +const { + BalancedPoolMissingUpstreamError, + InvalidArgumentError +} = __nccwpck_require__(8707) +const { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kRemoveClient, + kGetDispatcher +} = __nccwpck_require__(8640) +const Pool = __nccwpck_require__(5076) +const { kUrl, kInterceptors } = __nccwpck_require__(6443) +const { parseOrigin } = __nccwpck_require__(3440) +const kFactory = Symbol('factory') + +const kOptions = Symbol('options') +const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor') +const kCurrentWeight = Symbol('kCurrentWeight') +const kIndex = Symbol('kIndex') +const kWeight = Symbol('kWeight') +const kMaxWeightPerServer = Symbol('kMaxWeightPerServer') +const kErrorPenalty = Symbol('kErrorPenalty') - function setImmediate(callback) { - // Callback can either be a function or a string - if (typeof callback !== "function") { - callback = new Function("" + callback); - } - // Copy function arguments - var args = new Array(arguments.length - 1); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i + 1]; - } - // Store and register the task - var task = { callback: callback, args: args }; - tasksByHandle[nextHandle] = task; - registerImmediate(nextHandle); - return nextHandle++; - } +function getGreatestCommonDivisor (a, b) { + if (b === 0) return a + return getGreatestCommonDivisor(b, a % b) +} + +function defaultFactory (origin, opts) { + return new Pool(origin, opts) +} + +class BalancedPool extends PoolBase { + constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) { + super() - function clearImmediate(handle) { - delete tasksByHandle[handle]; + this[kOptions] = opts + this[kIndex] = -1 + this[kCurrentWeight] = 0 + + this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100 + this[kErrorPenalty] = this[kOptions].errorPenalty || 15 + + if (!Array.isArray(upstreams)) { + upstreams = [upstreams] } - function run(task) { - var callback = task.callback; - var args = task.args; - switch (args.length) { - case 0: - callback(); - break; - case 1: - callback(args[0]); - break; - case 2: - callback(args[0], args[1]); - break; - case 3: - callback(args[0], args[1], args[2]); - break; - default: - callback.apply(undefined, args); - break; - } + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') } - function runIfPresent(handle) { - // From the spec: "Wait until any invocations of this algorithm started before this one have completed." - // So if we're currently running a task, we'll need to delay this invocation. - if (currentlyRunningATask) { - // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a - // "too much recursion" error. - setTimeout(runIfPresent, 0, handle); - } else { - var task = tasksByHandle[handle]; - if (task) { - currentlyRunningATask = true; - try { - run(task); - } finally { - clearImmediate(handle); - currentlyRunningATask = false; - } - } - } + this[kInterceptors] = opts.interceptors && opts.interceptors.BalancedPool && Array.isArray(opts.interceptors.BalancedPool) + ? opts.interceptors.BalancedPool + : [] + this[kFactory] = factory + + for (const upstream of upstreams) { + this.addUpstream(upstream) } + this._updateBalancedPoolStats() + } - function installNextTickImplementation() { - registerImmediate = function(handle) { - process.nextTick(function () { runIfPresent(handle); }); - }; + addUpstream (upstream) { + const upstreamOrigin = parseOrigin(upstream).origin + + if (this[kClients].find((pool) => ( + pool[kUrl].origin === upstreamOrigin && + pool.closed !== true && + pool.destroyed !== true + ))) { + return this } + const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions])) - function canUsePostMessage() { - // The test against `importScripts` prevents this implementation from being installed inside a web worker, - // where `global.postMessage` means something completely different and can't be used for this purpose. - if (global.postMessage && !global.importScripts) { - var postMessageIsAsynchronous = true; - var oldOnMessage = global.onmessage; - global.onmessage = function() { - postMessageIsAsynchronous = false; - }; - global.postMessage("", "*"); - global.onmessage = oldOnMessage; - return postMessageIsAsynchronous; - } + this[kAddClient](pool) + pool.on('connect', () => { + pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty]) + }) + + pool.on('connectionError', () => { + pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) + this._updateBalancedPoolStats() + }) + + pool.on('disconnect', (...args) => { + const err = args[2] + if (err && err.code === 'UND_ERR_SOCKET') { + // decrease the weight of the pool. + pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) + this._updateBalancedPoolStats() + } + }) + + for (const client of this[kClients]) { + client[kWeight] = this[kMaxWeightPerServer] } - function installPostMessageImplementation() { - // Installs an event handler on `global` for the `message` event: see - // * https://developer.mozilla.org/en/DOM/window.postMessage - // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages + this._updateBalancedPoolStats() - var messagePrefix = "setImmediate$" + Math.random() + "$"; - var onGlobalMessage = function(event) { - if (event.source === global && - typeof event.data === "string" && - event.data.indexOf(messagePrefix) === 0) { - runIfPresent(+event.data.slice(messagePrefix.length)); - } - }; + return this + } - if (global.addEventListener) { - global.addEventListener("message", onGlobalMessage, false); - } else { - global.attachEvent("onmessage", onGlobalMessage); - } + _updateBalancedPoolStats () { + this[kGreatestCommonDivisor] = this[kClients].map(p => p[kWeight]).reduce(getGreatestCommonDivisor, 0) + } - registerImmediate = function(handle) { - global.postMessage(messagePrefix + handle, "*"); - }; + removeUpstream (upstream) { + const upstreamOrigin = parseOrigin(upstream).origin + + const pool = this[kClients].find((pool) => ( + pool[kUrl].origin === upstreamOrigin && + pool.closed !== true && + pool.destroyed !== true + )) + + if (pool) { + this[kRemoveClient](pool) } - function installMessageChannelImplementation() { - var channel = new MessageChannel(); - channel.port1.onmessage = function(event) { - var handle = event.data; - runIfPresent(handle); - }; + return this + } - registerImmediate = function(handle) { - channel.port2.postMessage(handle); - }; + get upstreams () { + return this[kClients] + .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true) + .map((p) => p[kUrl].origin) + } + + [kGetDispatcher] () { + // We validate that pools is greater than 0, + // otherwise we would have to wait until an upstream + // is added, which might never happen. + if (this[kClients].length === 0) { + throw new BalancedPoolMissingUpstreamError() } - function installReadyStateChangeImplementation() { - var html = doc.documentElement; - registerImmediate = function(handle) { - // Create a